Delimiter ";" doesnt work - papaparse

I using the following code to achieve the result below
function handleFileSelect(evt) {
var file = evt.target.files[0];
var asd = Papa.parse(file, {
delimeter: ";",
newline: "",
quoteChar: '"',
header: true,
complete: processResults
});
}
My .csv file looks like this:
2000;51013;;Kronospan Szczecinek Sp.z o.o.;ul. Waryńskiego 1 78-400 SZCZECINEK;PL6731657551;PLN;PL;;PL;D;51013
In the returned file it is written as:
2000,51013,,Kronospan Szczecinek Sp.z o.o.,ul. Waryńskiego 1 78-400 SZCZECINEK,PL6731657551 Zweryfikowany poprawnie,PLN,PL,,PL,D,51013
Note that the ; became ,.
anyone can help me?

for autodetect delimiter
delimiter: "",
1.
var asd = Papa.parse(file, {
delimeter: "",//automatic detect delimiter
newline: "",
quoteChar: '"',
header: true,
complete: processResults
});
2. you can remove delimiter from config
var asd = Papa.parse(file, {
newline: "",
quoteChar: '"',
header: true,
complete: processResults
});

Related

Convert "," to ";" in a CSV file Google script

With the below code my goal is to extract a sheet from the Google sheet file in CSV format. However, when I want to convert the , to ; the following error message appears:
r.join is not a function
Could you please help me to solve this problem.
Also, do you think it is possible to download this new file directly to the desktop of the computer ?
function sheetToCsv(){
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "Int_Module";
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var newfile = [result].map(r => r.join(";")).join("\n");
newfile.createFile(fileName, outputData, MimeType.PLAIN_TEXT);
}
I understand that there is 2 questions ... how to produce CSV file with semi-colon, and how to download the file directly to your PC.
1- To produce the csv content, try
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
2- To download, you will have to go through an html page.
Try this for both needs
function downloadMyCSVFile() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var sep = ';'
const content = sh.getDataRange().getValues().reduce((s, r) => s += r.map(c => c + sep).join("") + '\n', "")
var html = HtmlService.createHtmlOutput(`
<html><body onload="document.getElementById('dwn-btn').click()">
<textarea id="text-val" rows="10" style="display:none;">${content}</textarea>
<input type="button" id="dwn-btn" value="Download text file" style="display:none;"/>
<script>
window.close = function(){window.setTimeout(function(){google.script.host.close()},100)}
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("dwn-btn").addEventListener("click", function(){
var text = document.getElementById("text-val").value;
var filename = "${sh.getName()}.csv";
download(filename, text);
close();
}, false);
</script>
</body></html>
`)
.setWidth(250).setHeight(100);
SpreadsheetApp.getUi().showModalDialog(html, "Downloading ...");
}

Github API Create issue Markdown not rendering

I am creating a GitHub issue via the API using a script.
var labels = [];
labels.push('proposal');
var body = \n*Title:* ' + title + '\n##Abstract: \n' + abstract;
var payload = {
"title": title,
"body": body,
"labels": labels
};
var options = {
"method": "POST",
"contentType": "application/json",
"payload": JSON.stringify(payload)
};
options.headers = {"Authorization": "Basic " + Utilities.base64Encode(handle + ":" + token)};
var response = UrlFetchApp.fetch("https://api.github.com/repos/"+org+"/"+repo+"/issues", options);
The issue is getting posted correctly to Github, except that the markdown is not rendered when I look at the issue in Github. It just shows up as ## and * instead of headers and italics. If I go ahead and edit the issue manually in Github and mark the headers using the visual editor, it puts in another # and then renders it correctly. How do I get it to show correctly using the API?
TL;DR
The markdown text in the body is not correctly formatted. Every markdown syntax character should be having whitespace around it, which in OP's case is absent.
Code :
var reqHeaders = new Headers();
reqHeaders.append("Authorization", "Bearer <token>");
reqHeaders.append("Content-Type", "application/json");
var rawBody = JSON.stringify({
"title": "Markdown not rendering due to malformed markdown text in request body ",
"body": "\n*Title:* This is some title \n## Abstract: \n And this is some abstract",
"assignees": [
"akmalick"
],
"labels": [
"bug",
"good first issue",
"help wanted"
]
});
var requestOptions = {
method: 'POST',
headers: reqHeaders,
body: rawBody
};
fetch("https://api.github.com/repos/<owner>/<repo>/issues", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Below is the end result :

Retrieve date value in jenkinsfile

I have a job to push some values to consul based on user parameters and 2 values are generated when the pipeline is run like shutdown_date and termination_date:
def now, shutdown_date, termination_date
pipeline {
parameters {
string(name: 'env', defaultValue: 'abc')
string(name: 'owr', defaultValue: 'abc')
string(name: 'de', defaultValue: 'abc')
string(name: 'tct', defaultValue: 'abc-123')
}
agent { label 'abc' }
stages {
stage ('Update ENV'){
steps {
script {
now = new Date()
println now.format("yyyy-MM-dd", TimeZone.getTimeZone('UTC'))
shutdown_date = now + 170
shutdown_date = (shutdown_date.format("yyyy-MM-dd", TimeZone.getTimeZone('UTC'))).trim()
println shutdown_date
termination_date = now + 365
termination_date = (termination_date.format("yyyy-MM-dd", TimeZone.getTimeZone('UTC'))).trim()
println termination_date
step([$class: 'ConsulKVBuilder', aclToken: '', apiUri: '', debugMode: 'DISABLED', envVarKey: 'env_status', hostUrl: '', key: 'env_status/${env_name}', keyValue: '{ "owr":"${owr}", "de":"${de}", "tct":"${tct}", "shutdown_date": "${shutdown_date}", "termination_date": "${termination_date}" }', requestMode: 'WRITE'])
}
}
}
}
}
Expected result:
{ "owr":"abc", "de":"abc", "tct":"abc-123", "shutdown_date": "2020-02-15", "termination_date": "2020-08-15" }
Actual result:
{ "owr":"abc", "de":"abc", "tct":"abc-123", "shutdown_date": "${shutdown_date}", "termination_date": "${termination_date}" }
As mentioned in this answer, single-quoted strings won't interpolate variables.
You need to change your step to use double quotes and escape the ones in json.
step([$class: 'ConsulKVBuilder', aclToken: '', apiUri: '', debugMode: 'DISABLED', envVarKey: 'env_status', hostUrl: '', key: "env_status/${env_name}", keyValue: "{ \"owr\":\"${owr}\", \"de\":\"${de}\", \"tct\":\"${tct}\", \"shutdown_date\": \"${shutdown_date}\", \"termination_date\": \"${termination_date}\" }", requestMode: 'WRITE'])
String interpolation

FBInstant.shareAsync( ) failed with 500

I'm doing the sharing in my instant game.
I'm firing next req from the game:
FBInstant.shareAsync(
{
intent: 'REQUEST',
image: 'image-encoded-here',
text: 'Edgar just played BASH for 9 points!',
data: { myReplayData: 'message sent' },
}
).then( function()
{
console.log("sharing is done");
})
.catch( function(err)
{
console.log('failed to share: ' + err.code + " :: " + err.message);
});
but I'm receiving 500-error:
https://www.facebook.com/games/quicksilver/share_score/?dpr=2 500 ()
failed to share: NETWORK_FAILURE ::
=====================================
in My particulare case problems was with encoded image.
As i remember, image to share should include all the encoded image stuff with "data:image/jpeg;base64,/" in front.
Look at your "image" parameter in the shareAsync(). You must send a Base64 url or it will go wrong.
Try removing the "," from the line
data: { myReplayData: 'message sent' },
data: { myReplayData: 'message sent' }

remote autocomplete by typeahead works only on unique queries

I am having problem setting up typeahead with bloodhound on two fields - symbol and name. You can try live version on my DGI portfolio manager and autocomplete remote source here.
Typeahead sometimes works and sometimes it does not.
If I type symbols like "jnj", "mcd", "aapl" it works.
However, when I type string from name like "corporation" and "inc" that have around 3000 objects with this name, it does not work. I doubt it is because it is loading, since json file is served quickly(under 250ms on localhost).
Firstly, I thought symbols work correctly and names are ignored. But I do get proper typeahead for some names: "apple" and "homestreet" for instance.
I believe it only works if there are 1 or 2 results. But I don't understand, json file serves always max 5 results.
Here are my codes:
views.py for autocomplete url:
from haystack.query import SearchQuerySet
import json
def autocomplete(request):
if request.GET.get('q', '') == '':
array = []
else:
sqs = SearchQuerySet().models(Stock)
sqs_symbol = sqs.filter(symbol_auto=request.GET.get('q', ''))
sqs_name = sqs.filter(name_auto=request.GET.get('q', ''))
sqs_result = sqs_symbol | sqs_name
array = []
print sqs_result.count()
for result in sqs_result[:5]:
data = {"symbol": str(result.symbol),
"name": str(result.name),
"tokens": str(result.name).split()
}
array.insert(0, data)
print array
return HttpResponse(json.dumps(array), content_type='application/json')
I added print so I know when it does not work.
search_indexes.py file:
from haystack import indexes
from stocks.models import Stock
class StockIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
symbol = indexes.CharField(model_attr='symbol')
name = indexes.CharField(model_attr='name')
# We add this for autocomplete.
symbol_auto = indexes.EdgeNgramField(model_attr='symbol')
name_auto = indexes.EdgeNgramField(model_attr='name')
def get_model(self):
return Stock
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()
And in my template html file:
<script type="text/javascript">
$(function(){
var stocks = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.tokens);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 5,
remote: {
url: "/search/autocomplete/",
replace: function(url, query) {
return url + "?q=" + query;
},
filter: function(stocks) {
return $.map(stocks, function(data) {
return {
tokens: data.tokens,
symbol: data.symbol,
name: data.name
}
});
}
}
});
stocks.initialize();
$('.typeahead').typeahead(null, {
name: 'stocks',
displayKey: 'name',
minLength: 1, // send AJAX request only after user type in at least X characters
source: stocks.ttAdapter(),
templates: {
suggestion: function(data){
return '<p>' + data.name + ' (<strong>' + data.symbol + '</strong>)</p>';
}
}
}).on('typeahead:selected', function (obj, stock) {
window.location.href = "/stocks/detail/" + stock.symbol;
});
});
</script>
EDIT: Some Examples
Json response:
[{"tokens": ["Johnson", "&", "Johnson"], "symbol": "JNJ", "name": "Johnson & Johnson"}]
Not working for "sto":
json response:
[{"tokens": ["QKL", "Stores,", "Inc."], "symbol": "QKLS", "name": "QKL Stores, Inc."}, {"tokens": ["SPDR", "DJ", "STOXX", "50"], "symbol": "FEU", "name": "SPDR DJ STOXX 50 "}, {"tokens": ["Statoil", "ASA"], "symbol": "STO", "name": "Statoil ASA"}, {"tokens": ["STORE", "Capital", "Corporation"], "symbol": "STOR", "name": "STORE Capital Corporation"}, {"tokens": ["StoneMor", "Partners", "L.P."], "symbol": "STON", "name": "StoneMor Partners L.P."}]
It is typeahead.js's bug. It should be fixed in version 0.11.2.