Ionic 2 File Newline Character - ionic2

I am writing some data to a file. I first generate a string with the following code:
for(var t of transactions){
outputString += t.playerID + '|' + t.equipmentID + '|' + t.transaction + '|' + this.datePipe.transform(t.transactionTime, 'MM/dd/yyyy hh:ss a') + '|\n';
}
And then I write to the file:
this.writeFileHelper('HHTransactions.txt', outputString);
....
public writeFileHelper(fileName: string, outputString: string) {
this.file.writeFile(this.baseDir + '/mobile', fileName, outputString, true).then((Result) => {
console.log(Result);
}, (error) => {
console.log(error)
});
}
When I read the file on my mobile device, the output data shows data on separate lines, which I would expect \n to do. However, when the file is read by a PC, I end up with all the data in the same line.
Does anyone know why I am seeing this issue? I realize I can use:
writeFile(path, fileName, text, {append: true, replace: false})
But that seems silly to make a call for each record I'm writing into the file.
Thanks in advance.

Found out that I needed to add an \r\n for it to do do a carriage return. Obscure piece of knowledge, but hope it helps someone!

Related

How to automatically go through and edit long txt files?

I have an issue: I've got some chat logs that are thousands of lines ong, and I'm trying to isolate the messages from one specific user. The log looks like this:
[dd-mm-yy hh:mm pm/am] Username
message
[dd-mm-yy hh:mm pm/am] Username
message
[dd-mm-yy hh:mm pm/am] Username
message
In my file, I want to only keep the messages (not the other information like day hour or their username) that one specific user has send, and delete everything else, so I can process the contents of those messages. Is there anything out there that can help me achieve it, because as you can see its a very tedious process to go through thousands of lines of logs doing this by hand.
I ended up writing a js script to do what I wanted since I couldnt find anything anywhere else, here it is:
const fs = require("fs");
const readline = require("readline");
async function processLineByLine() {
const fileStream = fs.createReadStream("./input.txt");
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
// Note: we use the crlfDelay option to recognize all instances of CR LF
// ('\r\n') in input.txt as a single line break.
let trigger = false;
for await (const line of rl) {
// Each line in input.txt will be successively available here as `line`.
console.log(`Line from file: ${line}`);
if (line.includes("YOU DID THIS TO MY BOI LIM#7483") == true) {
console.log("true");
trigger = true;
}
else if (trigger == true) {
console.log(`Line sent by user: ${line}`);
fs.appendFile("output.txt", line + " ", (err) => {
// throws an error, you could also catch it here
if (err) throw err;
// success case, the file was saved
console.log("line saved");
});
trigger = false;
}
}
}
processLineByLine();

How to make sublime text 3's 'SublimeOnSaveBuild' package not compile the file named beginning with '_' prefix

How to make sublime text 3's SublimeOnSaveBuild package not compile the file named beginning with _ prefix?
For Example. I want a.scss or a_b.scss files can be complied when I saving this files. But not include the files such as named _a.scss.
I saw the guide in github is to set the filename_filter configuring.
So I create a SublimeOnSaveBuild.sublime-settings.Contents:
{
"filename_filter": "/^([^_])\\w*.(sass|less|scss)$/"
}
I used two \ , because it seems would saved as a .sublime-settings file which format likes JSON.
But it doesn't work.I use JavaScript to test it, it works well !
let reg = /^[^\_]\w*.(sass|less|scss)$/,
arr = [
'a.scss',
'_a.scss',
'a_b.scss'
];
arr.forEach(function( filename ) {
console.log( filename + '\t' + reg.test(filename) );
});
// a.scss true
// _a.scss false
// a_b.scss true
Thanks!
I found a solution in joshuawinn. But I can't understand why my codes can't work...
{
"filename_filter": "(/|\\\\|^)(?!_)(\\w+)\\.(css|js|sass|less|scss)$",
"build_on_save": 1
}
Sorry for my poor English !
let reg = /^(_|)\w*.(sass|less|scss)$/,
arr = [
'a.scss',
'_a.scss',
'a_b.scss'
];
arr.forEach(function( filename ) {
console.log( filename + '\t' + reg.test(filename) );
});

Convert markdown links from inline to reference

I have a changelog file formatted using Github's markdown.
Initially I used inline links for every link I needed to add, that is:
This is some [example](http://www.stackoverflow.com) line of text.
Over time, as the file grew in size, it became a bit messy due mainly to this way of inserting links.
I'd like to convert all links from inline to reference (see description of each), that is convert the above line to this:
This is some [example][1] line of text.
[1]: http://www.stackoverflow.com
Since the file is rather large and contains many inline links, I was wondering if there is some automated way to do this. I use Sublime Text 3 to edit, but I couldn't find a suitable package for this task. Perhaps some clever regex?
That's a great requirement!
I've just created a new Node.js program (I know it's not a GUI but seems something more people would like the capability of) to do this on GitHub.
Here's also the code:
// node main.js test.md result.md
var fs = require('fs')
fs.readFile(process.argv[2], 'utf8', function (err, markdown) {
if (err) {
return console.log(err);
}
var counter = 1;
var matches = {};
var matcher = /\[.*?\]\((.*?)\)/g;
while (match = matcher.exec(markdown)) {
if (!matches[match[1]]) matches[match[1]] = counter++;
}
console.log(matches);
Object.keys(matches).forEach(function(url) {
var r = new RegExp("(\\[.*?\\])\\(" + url + "\\)", "g");
markdown = markdown.replace(r, "$1[" + matches[url] + "]");
markdown += "\n[" + matches[url] + "]: " + url;
});
fs.writeFile(process.argv[3], markdown, 'utf8', function (err) {
if (err) return console.log(err);
});
});
Save this as mdrelink.py in your Packages folder, and you can then run it with
view.run_command('mdrelink');
from within the command console.
I think I got the order thingy right – reversing is necessary because otherwise it would mess up the already cached indexes of next items. It should also automatically skip already used link numbers. My first Python and my first Sublime plugin, so please be gentle with me.
import sublime, sublime_plugin
class mdrelinkCommand(sublime_plugin.TextCommand):
def run(self, edit):
oldlinks = []
self.view.find_all("^\s*(\[\d+\]):", sublime.IGNORECASE, "\\1", oldlinks)
newlinkpos = self.view.find_all("\[.+?\](\(.+?\))")
orgtext = []
self.view.find_all("(\[.+?\])\(.+?\)", sublime.IGNORECASE, "\\1", orgtext)
orglink = []
self.view.find_all("\[.+?\]\((.+?)\)", sublime.IGNORECASE, "\\1", orglink)
orglink.reverse()
self.view.insert(edit, self.view.size(), '\n\n')
counter = 1
newnumbers = []
for r in newlinkpos:
while '['+str(counter)+']' in oldlinks:
counter += 1
oldlinks.append('['+str(counter)+']')
line = '[' + str(counter)+']: '+ orglink.pop() + '\n'
newnumbers.append(' ['+str(counter)+']')
self.view.insert(edit, self.view.size(), line)
for r in reversed(newlinkpos):
self.view.replace(edit, r, orgtext.pop()+newnumbers.pop())
Came across this question thanks to Google. Maybe this can help others:
My answer isn't Sublime specific, but if you're using JavaScript (Node) already, I'd use a Markdown parser and CST transformer like remark.
For example, to transform all the inline links in README.md to numerically-ascending reference-style links, you could run the following at your project's root:
npm install --save-dev remark-cli remark-renumber-references
npx remark --no-stdout --output --use renumber-references README.md
Or, if you want reference-style links derived from the source uri:
npm install --save-dev remark-cli remark-defsplit
npx remark --no-stdout --output --use defsplit README.md
Hopefully this info helps people like me not waste a whole day hacking together some horrendously unreliable regexp-based solution to this :)
extending #bjfletcher's answer, below is the code that considers any existing reference links.
Link to GitHub gist.
// node filename.js ReadMe.md RefLinks.md
import * as fs from 'fs'
fs.readFile(process.argv[2], 'utf8', function (err, mainMarkdown) {
if (err) {
return console.log(err);
}
let newMarkdown = existingRefLinks(mainMarkdown);
var counter = 1;
var matches = {};
var matcher = /\[.*?\]\((.*?)\)/g
let match;
while (match = matcher.exec(newMarkdown)) {
if (!matches[match[1]]) matches[match[1]] = counter++;
}
console.log(matches);
Object.keys(matches).forEach(function (url) {
var r = new RegExp("(\\[.*?\\])\\(" + url + "\\)", "g");
newMarkdown = newMarkdown.replace(r, "$1[" + matches[url] + "]");
newMarkdown += "\n[" + matches[url] + "]: " + url;
});
fs.writeFile(process.argv[3], newMarkdown, 'utf8', function (err) {
if (err) return console.log(err);
});
});
function existingRefLinks(markdown) {
let refLinks = {}, match;
const matcher = /\[(\d)]:\s(.*)/g; // /\[.*?\]\((.*?)\)/g
while (match = matcher.exec(markdown)) {
if (!refLinks[match[1]]) refLinks[match[1]] = match[2];
}
markdown = markdown.replaceAll(matcher, "")
Object.keys(refLinks).forEach(function (int) {
markdown = markdown.replace("][" + int + "]", "](" + refLinks[int] + ")");
});
return markdown
}
Note that I prefer using #Xunnamius's answer:
npm install --save-dev remark-reference-links remark-cli
npx remark README.md -o --use reference-links

how to make first letter capital in of string in angular js

I am trying to make a filter which show first letter capital of string .I am able to solve the problem but when I have one Question on that .I need to understand the regex .Mean what regax is doing here .
http://codepen.io/anon/pen/JddwwV
Could you please tell me what is the meaning of regex replace(/([^\W_]+[^\s-]*)
what is use of this expression.
angular.module('CustomFilter', []).
filter('capitalize', function() {
return function(input, all) {
console.log(input)
return (!!input) ? input.replace(/([^\W_]+[^\s-]*) */g, function(txt){
console.log(txt+":txt")
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}) : '';
}
});
function Ctrl($scope) {
$scope.msg = 'hello, world.';
}

Added plus sign before number input in angularjs

I am using this directive to keep user typing only number into input tag.
app.directive('validNumber', function () {
return {
require: '?ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function (val) {
if (angular.isUndefined(val)) {
var val = '';
}
var clean = val.replace(/[^0-9\.]/g, '');
var decimalCheck = clean.split('.');
if (!angular.isUndefined(decimalCheck[0])) {
decimalCheck[0] = decimalCheck[0].slice(0, 10);
if (!angular.isUndefined(decimalCheck[1])) {
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
else {
clean = decimalCheck[0];
}
//console.log(decimalCheck[0][0]);
}
if (!angular.isUndefined(decimalCheck[1])) {
decimalCheck[1] = decimalCheck[1].slice(0, 3);
clean = decimalCheck[0] + '.' + decimalCheck[1];
}
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function (event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
But now i want to custome this, that means user can type ONLY ONE of "+" or "-" in the first. I think i have to change this pattern of
var clean = val.replace(/[^0-9\.]/g, '');
i also try to change into val.replace(/[^0-9.+-]/g, ''). It works but incorrectly, with this pattern user can type more "+" and "-" in any position of input field. I just wanna keep user typing ONLY ONE of "+" or "-" in the first like "+1234" or "-1234"
This is more of a regex problem than an AngularJS one, so you might have more luck there: https://stackoverflow.com/questions/tagged/regex
I'll try help you though. I think the regex you want matches a single +-, then any number of digits, then optionally a decimal point, then any number of digits. A single regex to match that is:
^[+-]?[0-9]*\.?[0-9]*
Have a read about groups and the '?' operator. This regex allows:
+.
-.
which don't make sense as input. You could design clever regexes to omit those results, but I think it would be easier to check the entry programmatically.
Finally, there are also very likely regexes online to help you solve any regex problem you ever come across more comprehensivley than you could. Just google an english description next time, and check out this for what you want:
http://www.regular-expressions.info/floatingpoint.html