Conditional If-Else List Comprehension in Coffeescript - coffeescript

Is there a way to do this in one line of coffeescript using a list comprehension?
len = 70
msgsFormatted = []
for msg in messages
if msg.length == len
then msgsFormatted.push(msg + ' ...')
else msgsFormatted.push msg
I was attempting this but it wouldn't transpile
msgsFormatted = (msg + ' ...' if msg.length == len else msg for msg in messages)
I also tried this but it was clearly not compiling to the right javascript
msgsFormatted = (if msg.length == len then msg + ' ...' else msg for msg in messages)

List comprehension doesn't offer else, but you could use a conditional statement within that:
len = 2
messages = [1, 2, 3, 4, '22', 5]
alert ((if msg.length == len then msg + ' ...' else msg) for msg in messages)
Try yourself: https://jsfiddle.net/

Use "Mapping Arrays" like
messages = [ "Peter", "Paul", "Mary" ]
len = 5
msgsFormatted = []
msgsFormatted = messages.map (msg) -> (if msg.length == len then msg + ' ...' else msg)
console.log msgsFormatted

Related

Math operations with one line input. Any suggestions to improve this code?

'''I wrote this program so I could do the math operations like I do in a terminal. just add the numbers and the operators and hit enter. that will give me the result.
With this code same can be done. I am sharing this so I can get some feedback on how to make this more efficient, add more functionality to it, etc...'''
# Basic operator functions
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def dev(num1, num2):
return num1 / num2
operators = {'+': add, '-': sub, '*': mul, '/': dev}
def splitter(text):
"""Function to split an input string containing number and operators
in a list separating numbers and operators in given sequence"""
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', "."]
delimiter = ["+", "-", "*", "/"]
elist = []
num = ""
for char in text:
if char in numbers:
num += char
elif char in delimiter:
elist.append(float(num))
elist.append(char)
num = ""
elif char == " ":
continue
else:
print(f"Invalid input: {char}")
break
elist.append(float(num))
return elist
def calculator(splitter1):
result = splitter1
# print(result)
total = 0
while len(result) > 1:
if "/" in result:
o_index = result.index("/")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = dev(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "*" in result:
o_index = result.index("*")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = mul(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "+" in result:
o_index = result.index("+")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = add(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
elif "-" in result:
o_index = result.index("-")
n1 = (o_index - 1)
n2 = (o_index + 1)
total = sub(result[n1], result[n2])
result[o_index] = total
result.pop(n1)
result.pop(o_index)
else:
continue
# print(result)
return total
repeat = "y"
while repeat == "y":
cal = input('calc: ')
calculation = calculator(splitter(cal))
print(calculation)
repeat = input("Would you like to continue to a new calculation? type 'y' to continue: ").lower()
else:
print("Thank you!")

Auto Hot Key script to Copy data from a Doc file and Email it with an app or chrome Browser

I have some text in a .DOC File Which is stored on Desktop. Is this possible When
If I press CTRL+Q Then, Text inside that file gets copied
And email it via any app or Mail app that is included in window10 to the person that are shown in the picture. How I want to email
***> You can also help me out, as I have the url of the email, I just have
to reply there after opening the mail url and click send button.***
Once you've got the file content as text, you can then piece together a mailto: URI. By the RFC 6068 spec, a parser should accept the primary email, subject and body - the other fields (such as CC addresses) are up to the parser to implement.
Here's a quick script I threw together from snippets I've found.
#SingleInstance Force
EmailRecipient := "target#example.com"
EmailCC := ["target2#example.com", "target3#example.com"]
EmailSubject := "MY WORK PROGRESS"
^Q::
; Step 1) Gets filepath of first file
FirstFilePath := getFirstSelected()
; Step 2) Makes sure its a DOC or DOCX file
if (!(SubStr(FirstFilePath, -3) = ".doc" || SubStr(FirstFilePath, -4) = ".docx")) {
MsgBox 0x1010, Doc Mailer, % "Not a doc/docx file!"
return
}
; Learning one
; https://autohotkey.com/board/topic/73386-fileread-word-docx-com-l-line-40-error/?p=494436
; Step 3) Opens it as a COM Object and copies its text content to the clipboard
oDoc := ComObjGet(FirstFilePath)
oDoc.Range.FormattedText.Copy ; OR oDoc.Range.Text.Copy
oDoc.Close(0)
; Step 4) Takes the content on the clipboard and URI encodes it
encodedBody:=UriEncode(clipboard)
; Step 5) Build GET query string parts
params := []
if (EmailCC && EmailCC.Length()) {
params.Push("cc=" . UriEncode(StrJoin(EmailCC, ",")))
}
if (EmailSubject) {
params.Push("subject=" . UriEncode(EmailSubject))
}
if (encodedBody) {
params.Push("body=" . encodedBody)
}
paramsStr := StrJoin(params, "&")
; Step 6) Build the mailto: URI
;MsgBox % "mailto:" . EmailRecipient . (paramsStr ? "?" . paramsStr : "")
Run, % "mailto:" . EmailRecipient . (paramsStr ? "?" . paramsStr : "")
return
; ---------------------
; Modified from Masonjar13's function
; https://www.autohotkey.com/boards/viewtopic.php?p=154791#p154791
getFirstSelected(){
cO:=clipboardAll
clipboard:=
send ^c
clipWait
selected:=clipboard
clipboard:=cO
return StrSplit(selected, "`r`n")[1]
}
; ---------------------
; https://autohotkey.com/board/topic/75390-ahk-l-unicode-uri-encode-url-encode-function/?p=480216
; modified from jackieku's code (http://www.autohotkey.com/forum/post-310959.html#310959)
UriEncode(Uri, Enc = "UTF-8")
{
StrPutVar(Uri, Var, Enc)
f := A_FormatInteger
SetFormat, IntegerFast, H
Loop
{
Code := NumGet(Var, A_Index - 1, "UChar")
If (!Code)
Break
If (Code >= 0x30 && Code <= 0x39 ; 0-9
|| Code >= 0x41 && Code <= 0x5A ; A-Z
|| Code >= 0x61 && Code <= 0x7A) ; a-z
Res .= Chr(Code)
Else
Res .= "%" . SubStr(Code + 0x100, -1)
}
SetFormat, IntegerFast, %f%
Return, Res
}
UriDecode(Uri, Enc = "UTF-8")
{
Pos := 1
Loop
{
Pos := RegExMatch(Uri, "i)(?:%[\da-f]{2})+", Code, Pos++)
If (Pos = 0)
Break
VarSetCapacity(Var, StrLen(Code) // 3, 0)
StringTrimLeft, Code, Code, 1
Loop, Parse, Code, `%
NumPut("0x" . A_LoopField, Var, A_Index - 1, "UChar")
StringReplace, Uri, Uri, `%%Code%, % StrGet(&Var, Enc), All
}
Return, Uri
}
StrPutVar(Str, ByRef Var, Enc = "")
{
Len := StrPut(Str, Enc) * (Enc = "UTF-16" || Enc = "CP1200" ? 2 : 1)
VarSetCapacity(Var, Len, 0)
Return, StrPut(Str, &Var, Enc)
}
; ---------------------
StrJoin(arr, delim = ",") {
ret := ""
Loop % arr.Length()
ret := ret . (A_Index = 1 ? "" : delim) . arr[A_Index]
return ret
}

Email sender tweaking help needed

I've been trying to understand this email on edit function.
I just cannot figure it out.
I need to send informations in Columns A, B, C, F, G, H and J. The email trigger is in column K and would be selected from data validation.
I have the following function which works great. It send the email but I cannot adjust which rows to show here.
What am I doing wrong?
I want body of the Email to appear as follows when I choose email in K101
Headers in A3 : Data in cell A101
Headers in B3 : Data in cell B101
Headers in C3 : Data in cell C101
Headers in F3 : Data in cell F101
Headers in G3 : Data in cell G101
Headers in H3 : Data in cell H101
Headers in J3 : Data in cell J101
Help???
function mailOnEdit(e) {
var sheet = e.source.getActiveSheet();
if (sheet.getName() !== 'Registry Sheet' || e.range.columnStart !== 11 || e.range.rowStart < 4 || !e.value) return;
var h = sheet.getRange(1, 1, 1, 8)
.getValues()[0],
val = sheet.getRange(e.range.rowStart, 1, 1, 8)
.getValues()[0],
i = 0,
body = "",
notCols = [3, 4];
while (i < 7) {
if (notCols.indexOf(i) == -1) {
body += h[i] + ": " + val[i] + "\n";
}
i += 1;
}
body += "\n\n Contact customer within 30 minutes and reply. Thanks";
MailApp.sendEmail(e.value, "New job", body)
}
Seems like your headers are in row three and not in row one. So
Change
var h = sheet.getRange(1, 1, 1, 8).getValues()[0]
to
var h = sheet.getRange(3, 1, 1, 8).getValues()[0]

Google Translate TTS API blocked

Google implemented a captcha to block people from accessing the TTS translate API https://translate.google.com/translate_tts?ie=UTF-8&q=test&tl=zh-TW. I was using it in my mobile application. Now, it is not returning anything. How do I get around the captcha?
Add the qualifier '&client=tw-ob' to the end of your query.
https://translate.google.com/translate_tts?ie=UTF-8&q=test&tl=zh-TW&client=tw-ob
This answer no longer works consistently. Your ip address will be blocked by google temporarily if you abuse this too much.
there are 3 main issues:
you must include "client" in your query string (client=t seems to work).
(in case you are trying to retrieve it using AJAX) the Referer of the HTTP request must be https://translate.google.com/
"tk" field changes for every query, and it must be populated with a matching hash:
tk = hash(q, TKK), where q is the text to be TTSed, and TKK is a var in the global scope when you load translate.google.com: (type 'window.TKK' in the console). see the hash function at the bottom of this reply (calcHash).
to summarize:
function generateGoogleTTSLink(q, tl, tkk) {
var tk = calcHash(q, tkk);
return `https://translate.google.com/translate_tts?ie=UTF-8&total=1&idx=0&client=t&ttsspeed=1&tl=${tl}&tk=${tk}&q=${q}&textlen=${q.length}`;
}
generateGoogleTTSLink('ciao', 'it', '410353.1336369826');
// see definition of "calcHash" in the bottom of this comment.
=> to get your hands on a TKK, you can open Google Translate website, then type "TKK" in developer tools' console (e.g.: "410353.1336369826").
NOTE that TKK value changes every hour, and so, old TKKs might get blocked at some point, and refreshing it may be necessary (although so far it seems like old keys can work for a LONG time).
if you DO wish to periodically refresh TKK, it can be automated pretty easily, but not if you're running your code from the browser.
you can find a full NodeJS implementation here:
https://github.com/guyrotem/google-translate-server.
it exposes a minimal TTS API (query, language), and is deployed to a free Heroku server, so you can test it online if you like.
function shiftLeftOrRightThenSumOrXor(num, opArray) {
return opArray.reduce((acc, opString) => {
var op1 = opString[1]; // '+' | '-' ~ SUM | XOR
var op2 = opString[0]; // '+' | '^' ~ SLL | SRL
var xd = opString[2]; // [0-9a-f]
var shiftAmount = hexCharAsNumber(xd);
var mask = (op1 == '+') ? acc >>> shiftAmount : acc << shiftAmount;
return (op2 == '+') ? (acc + mask & 0xffffffff) : (acc ^ mask);
}, num);
}
function hexCharAsNumber(xd) {
return (xd >= 'a') ? xd.charCodeAt(0) - 87 : Number(xd);
}
function transformQuery(query) {
for (var e = [], f = 0, g = 0; g < query.length; g++) {
var l = query.charCodeAt(g);
if (l < 128) {
e[f++] = l; // 0{l[6-0]}
} else if (l < 2048) {
e[f++] = l >> 6 | 0xC0; // 110{l[10-6]}
e[f++] = l & 0x3F | 0x80; // 10{l[5-0]}
} else if (0xD800 == (l & 0xFC00) && g + 1 < query.length && 0xDC00 == (query.charCodeAt(g + 1) & 0xFC00)) {
// that's pretty rare... (avoid ovf?)
l = (1 << 16) + ((l & 0x03FF) << 10) + (query.charCodeAt(++g) & 0x03FF);
e[f++] = l >> 18 | 0xF0; // 111100{l[9-8*]}
e[f++] = l >> 12 & 0x3F | 0x80; // 10{l[7*-2]}
e[f++] = l & 0x3F | 0x80; // 10{(l+1)[5-0]}
} else {
e[f++] = l >> 12 | 0xE0; // 1110{l[15-12]}
e[f++] = l >> 6 & 0x3F | 0x80; // 10{l[11-6]}
e[f++] = l & 0x3F | 0x80; // 10{l[5-0]}
}
}
return e;
}
function normalizeHash(encondindRound2) {
if (encondindRound2 < 0) {
encondindRound2 = (encondindRound2 & 0x7fffffff) + 0x80000000;
}
return encondindRound2 % 1E6;
}
function calcHash(query, windowTkk) {
// STEP 1: spread the the query char codes on a byte-array, 1-3 bytes per char
var bytesArray = transformQuery(query);
// STEP 2: starting with TKK index, add the array from last step one-by-one, and do 2 rounds of shift+add/xor
var d = windowTkk.split('.');
var tkkIndex = Number(d[0]) || 0;
var tkkKey = Number(d[1]) || 0;
var encondingRound1 = bytesArray.reduce((acc, current) => {
acc += current;
return shiftLeftOrRightThenSumOrXor(acc, ['+-a', '^+6'])
}, tkkIndex);
// STEP 3: apply 3 rounds of shift+add/xor and XOR with they TKK key
var encondingRound2 = shiftLeftOrRightThenSumOrXor(encondingRound1, ['+-3', '^+b', '+-f']) ^ tkkKey;
// STEP 4: Normalize to 2s complement & format
var normalizedResult = normalizeHash(encondingRound2);
return normalizedResult.toString() + "." + (normalizedResult ^ tkkIndex)
}
// usage example:
var tk = calcHash('hola', '409837.2120040981');
console.log('tk=' + tk);
// OUTPUT: 'tk=70528.480109'
You can also try this format :
pass q= urlencode format of your language
(In JavaScript you can use the encodeURI() function & PHP has the rawurlencode() function)
pass tl = language short name (suppose bangla = bn)
Now try this :
https://translate.google.com.vn/translate_tts?ie=UTF-8&q=%E0%A6%A2%E0%A6%BE%E0%A6%95%E0%A6%BE+&tl=bn&client=tw-ob
First, to avoid captcha, you have to set a proper user-agent like: "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0"
Then to not being blocked you must provide a proper token ("tk" get parameter) for each single request.
On the web you can find many different kind of scripts that try to calculate the token after a lot of reverse engineering...but every time the big G change the algorithm you're stuck again, so it's much easier to retrieve your token just observing in deep similar requests to translate page (with your text in the url).
You can read the token time by time grepping "tk=" from the output of this simple code with phantomjs:
"use strict";
var page = require('webpage').create();
var system = require('system');
var args = system.args;
if (args.length != 2) { console.log("usage: "+args[0]+" text"); phantom.exit(1); }
page.onConsoleMessage = function(msg) { console.log(msg); };
page.onResourceRequested = function(request) { console.log('Request ' + JSON.stringify(request, undefined, 4)); };
page.open("https://translate.google.it/?hl=it&tab=wT#fr/it/"+args[1], function(status) {
if (status === "success") { phantom.exit(0); }
else { phantom.exit(1); }
});
so in the end you can get your speech with something like:
wget -U "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:46.0) Gecko/20100101 Firefox/46.0"
"http://translate.google.com/translate_tts?ie=UTF-8&tl=it&tk=52269.458629&q=ciao&client=t" -O ciao.mp3
(token are probably time based so this link may not work tomorrow)
I rewrote Guy Rotem's answer in Java, so if you prefer Java over Javascript, feel free to use:
public class Hasher {
public long shiftLeftOrRightThenSumOrXor(long num, String[] opArray) {
long result = num;
int current = 0;
while (current < opArray.length) {
char op1 = opArray[current].charAt(1); // '+' | '-' ~ SUM | XOR
char op2 = opArray[current].charAt(0); // '+' | '^' ~ SLL | SRL
char xd = opArray[current].charAt(2); // [0-9a-f]
assertError(op1 == '+'
|| op1 == '-', "Invalid OP: " + op1);
assertError(op2 == '+'
|| op2 == '^', "Invalid OP: " + op2);
assertError(('0' <= xd && xd <= '9')
|| ('a' <= xd && xd <='f'), "Not an 0x? value: " + xd);
int shiftAmount = hexCharAsNumber(xd);
int mask = (op1 == '+') ? ((int) result) >>> shiftAmount : ((int) result) << shiftAmount;
long subresult = (op2 == '+') ? (((int) result) + ((int) mask) & 0xffffffff)
: (((int) result) ^ mask);
result = subresult;
current++;
}
return result;
}
public void assertError(boolean cond, String e) {
if (!cond) {
System.err.println();
}
}
public int hexCharAsNumber(char xd) {
return (xd >= 'a') ? xd - 87 : Character.getNumericValue(xd);
}
public int[] transformQuery(String query) {
int[] e = new int[1000];
int resultSize = 1000;
for (int f = 0, g = 0; g < query.length(); g++) {
int l = query.charAt(g);
if (l < 128) {
e[f++] = l; // 0{l[6-0]}
} else if (l < 2048) {
e[f++] = l >> 6 | 0xC0; // 110{l[10-6]}
e[f++] = l & 0x3F | 0x80; // 10{l[5-0]}
} else if (0xD800 == (l & 0xFC00) &&
g + 1 < query.length() && 0xDC00 == (query.charAt(g + 1) & 0xFC00)) {
// that's pretty rare... (avoid ovf?)
l = (1 << 16) + ((l & 0x03FF) << 10) + (query.charAt(++g) & 0x03FF);
e[f++] = l >> 18 | 0xF0; // 111100{l[9-8*]}
e[f++] = l >> 12 & 0x3F | 0x80; // 10{l[7*-2]}
e[f++] = l & 0x3F | 0x80; // 10{(l+1)[5-0]}
} else {
e[f++] = l >> 12 | 0xE0; // 1110{l[15-12]}
e[f++] = l >> 6 & 0x3F | 0x80; // 10{l[11-6]}
e[f++] = l & 0x3F | 0x80; // 10{l[5-0]}
}
resultSize = f;
}
return Arrays.copyOf(e, resultSize);
}
public long normalizeHash(long encondindRound2) {
if (encondindRound2 < 0) {
encondindRound2 = (encondindRound2 & 0x7fffffff) + 0x80000000L;
}
return (encondindRound2) % 1_000_000;
}
/*
/ EXAMPLE:
/
/ INPUT: query: 'hola', windowTkk: '409837.2120040981'
/ OUTPUT: '70528.480109'
/
*/
public String calcHash(String query, String windowTkk) {
// STEP 1: spread the the query char codes on a byte-array, 1-3 bytes per char
int[] bytesArray = transformQuery(query);
// STEP 2: starting with TKK index,
// add the array from last step one-by-one, and do 2 rounds of shift+add/xor
String[] d = windowTkk.split("\\.");
int tkkIndex = 0;
try {
tkkIndex = Integer.valueOf(d[0]);
}
catch (Exception e) {
e.printStackTrace();
}
long tkkKey = 0;
try {
tkkKey = Long.valueOf(d[1]);
}
catch (Exception e) {
e.printStackTrace();
}
int current = 0;
long result = tkkIndex;
while (current < bytesArray.length) {
result += bytesArray[current];
long subresult = shiftLeftOrRightThenSumOrXor(result,
new String[] {"+-a", "^+6"});
result = subresult;
current++;
}
long encondingRound1 = result;
//System.out.println("encodingRound1: " + encondingRound1);
// STEP 3: apply 3 rounds of shift+add/xor and XOR with they TKK key
long encondingRound2 = ((int) shiftLeftOrRightThenSumOrXor(encondingRound1,
new String[] {"+-3", "^+b", "+-f"})) ^ ((int) tkkKey);
//System.out.println("encodingRound2: " + encondingRound2);
// STEP 4: Normalize to 2s complement & format
long normalizedResult = normalizeHash(encondingRound2);
//System.out.println("normalizedResult: " + normalizedResult);
return String.valueOf(normalizedResult) + "."
+ (((int) normalizedResult) ^ (tkkIndex));
}
}

Why is the following for loop not printing anything?

ages = {paul: 11, rick: 7 }
for n,a in ages
console.log("names: #{n}, ages: #{a}")
So nothing is being printed in the console. What I'm doing wrong?
That translates into the following JavaScript:
var a, ages, n, _i, _len;
ages = {
paul: 11,
rick: 7
};
for (a = _i = 0, _len = ages.length; _i < _len; a = ++_i) {
n = ages[a];
console.log("names: " + n + ", ages: " + a);
}
Note that it's trying to loop through the ages object using the length property, which doesn't exist.
Change your script so the loop uses for n,a of ages syntax instead (relevant documentation), and your code translates into valid JavaScript and prints to the console.
var a, ages, n;
ages = {
paul: 11,
rick: 7
};
for (n in ages) {
a = ages[n];
console.log("names: " + n + ", ages: " + a);
}