How to return/yield from map function - dart

Why can I do:
var userArray = ['User 1', 'User 2', 'User 3'];
var userList = userArray.map((user) => user).toList();
But in a function body nor return or yield works:
var userArray = ['User 1', 'User 2', 'User 3'];
var userList = userArray.map((user) => {return user}).toList();
var userList = userArray.map((user) => {yield user}).toList();

var userArray = ['User 1', 'User 2', 'User 3'];
var userList = userArray.map((user) => {return user}).toList();
If you want to use {} braces, you can't use an arrow function (=>). Instead:
var userArray = ['User 1', 'User 2', 'User 3'];
var userList = userArray.map((user) {
return user;
}).toList();
(you also need the semicolon).

Related

Dinamic table with PdfMake

It dont display in format. I'm using Angular 8.
This part is for getting the info.
var med = MyData....;//[name,price,description]
var col = [];
med.forEach(element => {
var row=[];
row.push([element.name]);
row.push([element.price])
row.push([element.description]);
console.log(row);
col.push(row);
});
then this part is for displaying in pdfMake
let dd= {
content: [
{
table: {
`body`: [
col
]
},
}
]
}
Sometimes it displays vertically.
In pdfmake.org/playground.html when you put this code:
var ex = [['example 1', '10','d1'],['example 2', '12','d2'], ['example 3', '18','d3']];
var dd = {
content: [
{
style: 'tableExample',
table: {
widths:['auto','auto','*'],
body: [
['name', 'price ','description'],
ex
]
}
},
]
}
this is te result:
and I need something like this, no matter how much values I get in my array:
var ex = [['example 1', '10','d1'],['example 2', '12','d2'], ['example 3', '18','d3']];
var dd = {
content: [
{
style: 'tableExample',
table: {
widths:['auto','auto','*'],
body: [
['name', 'price ','description'],
ex[0],
ex[1],
ex[2]
]
}
},
]
}
I need this result:

Creating subscription in stripe

I am getting this error
`Stripe::InvalidRequestError (This customer has no attached payment source):
app/controllers/subscriptions_controller.rb:24:in `create`
when I try to subscribe to a plan.
here is my code
`
class SubscriptionsController < ApplicationController
layout "subscribe"
before_action :authenticate_user!, except: [:new, :create]
def new
if user_signed_in? && current_user.subscribed?
redirect_to root_path, notice: "You are already a subscriber"
end
end
def create
Stripe.api_key = Rails.application.credentials.stripe_api_key
plan_id = params[:plan_id]
plan = Stripe::Plan.retrieve(plan_id)
token = params[:stripeToken]
customer = if current_user.stripe_id?
Stripe::Customer.retrieve(current_user.stripe_id)
else
Stripe::Customer.create(email: current_user.email, source: token)
end
subscription = customer.subscriptions.create(plan: plan.id)
options = {
stripe_id: customer.id,
stripe_subscription_id: subscription.id,
subscribed: true
}
options.merge!(
card_last4: params[:user][:card_last4],
card_exp_month: params[:user][:card_exp_month],
card_exp_year: params[:user][:card_exp_year],
card_type: params[:user][:card_type]
) if params[:user][:card_last4]
current_user.update(options)
redirect_to root_path, notice: "Your subscription was setup successfully!"
end
def destroy
customer = Stripe::Customer.retrieve(current_user.stripe_id)
customer.subscriptions.retrieve(current_user.stripe_subscription_id).delete
current_user.update(stripe_subscription_id: nil)
current_user.subscribed = false
redirect_to root_path, notice: "Your subscription has been canceled."
end
end
`
stripe.js
document.addEventListener("turbolinks:load", () => {
const publishableKey = document.querySelector("meta[name='stripe-key']").content;
const stripe = Stripe(publishableKey);
const elements = stripe.elements({
fonts: [{
cssSrc: "https://rsms.me/inter/inter-ui.css"
}],
locale: "auto"
});
const style = {
base: {
color: "#32325d",
fontWeight: 500,
fontFamily: "Inter UI, Open Sans, Segoe UI, sans-serif",
fontSize: "16px",
fontSmoothing: "antialiased",
"::placeholder": {
color: "#CFD7DF"
}
},
invalid: {
color: "#E25950"
}
};
const card = elements.create('card', {
style
});
card.mount("#card-element");
card.addEventListener('change', ({
error
}) => {
const displayError = document.getElementById('card-errors');
if (error) {
displayError.textContent = error.message;
} else {
displayError.textContent = "";
}
});
const form = document.getElementById('payment-form');
form.addEventListener('submit', async(event) => {
event.preventDefault();
const {
token,
error
} = await stripe.createToken(card);
if (error) {
const errorElement = document.getElementById('card-errors');
errorElement.textContent = error.message;
} else {
stripeTokenHandler(token);
}
});
const stripeTokenHandler = (token) => {
const form = document.getElementById('payment-form');
const hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
["type", "last4", "exp_month", "exp_year"].forEach(function(field) {
addCardField(form, token, field);
});
form.submit();
}
function addCardField(form, token, field) {
let hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', "user[card_" + field + "]");
hiddenInput.setAttribute('value', token.card[field]);
form.appendChild(hiddenInput);
}
});
I have all the plans and stripe Api configured correctly but something is wrong with the code. i am not very good in Js. So most of the code is a copy and paste and modified to fit my needs
i have search all over i can't find a solution. i need help.

ChartJs Uncaught ReferenceError for labels value from ViewBag

I'm struggling with passing the csv strings via ViewBag in the correct format.
I know the result should be like ["Blue","Brown","Green"] but my script is generated as [Blue,Brown,Green] instead.
And then I get the Uncaught ReferenceError : Blue is not defined.
How can I format it in my controller to pass in the correct way?
This is my code in the controller
public ActionResult Index()
{
List<string> teamsList = new List<string>();
List<string> salesCount = new List<string>();
foreach (var team in Db.Teams)
{
teamsList.Add(team.Name);
int count = Db.LeadCampaigns.Count(i => Db.Agents.FirstOrDefault(a => a.AgentId == i.AgentId).TeamId == team.TeamId && i.LeadStatusId == Db.LeadStatuses.FirstOrDefault(s => s.Name == "SALE").LeadStatusId);
salesCount.Add(count.ToString());
}
ViewBag.SaleCount_List = string.Join(",", salesCount);
ViewBag.TeamName_List = string.Join(",", teamsList);
return View();
}
And here is my script in the view.
<script>
var barChartData =
{
labels: [#Html.Raw(ViewBag.TeamName_List)],
datasets: [{
label: 'TeamWise Sales Count',
backgroundColor: [
"#f990a7",
"#aad2ed",
"#9966FF",
"#99e5e5",
"#f7bd83",
],
borderWidth: 2,
data: [#ViewBag.SaleCount_List]
}]
};
window.onload = function () {
var ctx1 = document.getElementById("barcanvas").getContext("2d");
window.myBar = new Chart(ctx1,
{
type: 'bar',
data: barChartData,
options:
{
title:
{
display: true,
text: "TeamWise Sales Count"
},
responsive: true,
maintainAspectRatio: true
}
});
}
Your plugin expects an array of values, but your passing it a string by using String.Join().
Pass the array using
ViewBag.SaleCount_List = salesCount;
ViewBag.TeamName_List = teamsList;
(or better pass a view model with 2 IEnumerable<string> properties) and then convert it to a jacascript array
var saleCounts = #Html.Raw(Json.Encode(ViewBag.SaleCount_List))
var teamNames = #Html.Raw(Json.Encode(ViewBag.TeamName_List))
var barChartData =
{
labels: teamNames,
datasets: [{
....
],
borderWidth: 2,
data: saleCounts
}]
};
Using your current syntax:
const string quote = "\"";
foreach (var team in Db.Teams)
{
teamsList.Add(quote + team.Name + quote);
int count = Db.LeadCampaigns.Count(i => Db.Agents.FirstOrDefault(a => a.AgentId == i.AgentId).TeamId == team.TeamId && i.LeadStatusId == Db.LeadStatuses.FirstOrDefault(s => s.Name == "SALE").LeadStatusId);
salesCount.Add(count.ToString());
}

How do get LineString to show using Leaflet?

I have pipe model in my database and it has geometry attribute (LineString). I added this to pipes_controller.rb:
def index
#pipes = Pipe.all
#geojson = Array.new
#pipes.each do |pipe|
#geojson<< {
type: "FeatureCollection",
crs: { type: "name", properties: { name: "urn:ogc:def:crs:OGC:1.3:CRS84" } },
features: [
type: 'Feature',
properties: {
geometry: {
type: 'LineString',
coordinates: pipe.get_coordinates
},
stroke: "#1087bf"
}
]}
end
respond_to do |format|
format.html
format.json { render json: #geojson } # respond with the created JSON object
end
end
This is pipes.js file:
$(document).ready(function() {
if ($("#pipes_map").length>0) {
var geojson;
var map = L.map('pipes_map', {
center: [42.44, 19.26],
zoom: 16
});
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
max_zoom: 22
}).addTo(map);
L.geoJson(geojson).addTo(map);
$.ajax({
dataType: 'text',
url: 'http://localhost:3000/pipes.json',
success: function(data) {
var myStyle = {
"color": "#ff7800",
"weight": 5,
"opacity": 0.65
};
geojson = $.parseJSON(data);
L.geoJson(geojson).addTo(map);
},
error : function() {
alert('Error!');
}
})
}
})
But my pipes don't appear on the map. What am I doing wrong? Maybe my pipes.json is poorly formated? Or style is not ok?
This is what the controller should look like:
def index
#pipes = Pipe.all
#geojson = Array.new
#pipes.each do |pipe|
#geojson<< {
type: 'Feature',
properties: {
:category=> pipe.category.name
},
geometry: {
type: 'LineString',
coordinates: pipe.get_coordinates
}
}
end
respond_to do |format|
format.html
format.json { render json: #geojson } # respond with the created JSON object
end
end
The rest is fine.

Rails PaperClip drag and drop multiple files

I am using PaperClip with Rails to upload files and it works fine, however it would like to implment a drag and drop fileupload that allows for uploading of multiple files. and that each file shoudn't be more than a certain size.
Edit:
Here is what is what i have so far, i have created the javascript part. However i am lost as how to create the controller part:
var $dropArea = $(".drop-area");
$dropArea.bind({
dragover: function () {
$(this).addClass('hover');
return false;
},
dragend: function () {
$(this).removeClass('hover');
return false;
},
drop: function (e) {
e = e || window.event;
e.preventDefault();
e = e.originalEvent || e;
var files = (e.files || e.dataTransfer.files);
var $img = $('<img src="" class="uploadPic" title="" alt="" />');
for (var i = 0; i < files.length; i++) {
(function (i) {
var reader = new FileReader();
reader.onload = function (event) {
var newImg = $img.clone().attr({
src: event.target.result,
title: (files[i].name),
alt: (files[i].name)
});
$("body").append(newImg);
};
reader.readAsDataURL(files[i]);
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append(files[i].name, files[i]);
xhr.open("POST", 'url', true);
xhr.send(fd);
})(i);
}
return false;
}
});
And this is the basic controller part:
def create
#image = Image.new(params[:image])
if #image.save
respond_to do |format|
format.html { redirect_to action: 'index', :notice => 'Image saved'}
format.js { redirect_to action: 'index', :notice => 'Image saved'}
format.xml { redirect_to action: 'index', :notice => 'Image saved'}
end
else
flash[:notice] = "Error, Please try again"
redirect_to action: 'new'
end
end
How can i do this?
Thanks
After some research, i found that it could be easily done like this:
var dropArea = document.getElementById("droparea"),
viewArea = document.getElementById("previewarea");
dropArea.addEventListener("drop", function(evt){
evt.preventDefault();
evt.stopPropagation();
previewFiles(evt.dataTransfer.files);
return false;
}, false);
function previewFiles(files){
for (i=0; i < files.length; i++){
if (typeof FileReader != "undefined"){
var img = document.createElement("img");
viewArea.appendChild(img);
var reader = new FileReader();
reader.onload = (function(theImg){
return function(evt){
theImg.src = evt.target.result;
}
}(img));
reader.readAsDataURL(files[i]);
}
}
uploadFiles(files);
}
function uploadFiles(files){
var fd = FormData();
var position = 0;
var max = files.length;
if (typeof fd != "undefined"){
function queue(){
if (max >= 1 && position <= max - 1){
fd.append("file", files[position]);
upload();
}
}
function upload(){
$.ajax({
url: '/boxes/hiThere',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
position = position + 1;
queue();
}
});
}
queue();
}
}
dropArea.addEventListener("dragenter", function(evt){
if (evt){
this.className = "drag-enter";
}
endFn(evt);
}, false);
dropArea.addEventListener("dragleave", function(evt){
this.className = "";
endFn(evt);
}, false);
dropArea.addEventListener("dragover", function(evt){
endFn(evt);
evt.dataTransfer.dropEffect = 'move';
return false;
}, false);
function endFn(evt){
evt.preventDefault();
evt.stopPropagation();
}
and simply add the normal save in rails like this:
def hiThere
box = Box.new(params[:box])
box.user_id = current_user.id
box.file_path = params[:file]
if box.save!
set_flash "File saved sucessfully"
else
set_flash "Error, please try again"
end
respond_to do |format|
format.js { redirect_to action: :index, :notice => "Done" }
end
end

Resources