MVC - What can I do if I do not want my Email field display error when regular expression validation fails? - regex

I'm creating an MVC page that uses Kendo validation.
I have the following Model:
public class ForgotPasswordModel
{
[Required(ErrorMessage = " ")]
public string UserName { get; set; }
[Required(ErrorMessage = " ")]
[EmailAddress(ErrorMessage = " ")]
public string Email { get; set; }
public string PhoneNumber { get; set; }
[Required(ErrorMessage = " ")]
public string Code { get; set; }
}
I do not want my view to show Error Message for the Email field. I want it to show only exclamation sign when validation fails.
Currently I have the following code in my View:
#model Site.Models.ForgotPasswordModel
#{
ViewBag.Title = "Forgot Password";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/kendo/kendo.common-material.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.custom.css" rel="stylesheet" />
<link href="~/Content/kendo/custom.css" rel="stylesheet" />
<script src="~/Scripts/kendo/kendo.all.min.js"></script>
<script src="~/Scripts/kendo/kendo.aspnetmvc.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<style>
input[type=text]::-ms-clear {
display: none;
}
input[type=password]::-ms-reveal {
display: none;
}
.errMsg {
font-weight: bolder;
color: red;
}
span#UserName_validationMessage, span#Email_validationMessage,span#Code_validationMessage {
display: inline-block;
width: 160px;
text-align: left;
border: 0;
padding: 0;
margin: -20px;
background: none;
box-shadow: none;
color: red;
}
.k-invalid-msg {
display: none;
}
</style>
</head>
<body>
<div>
</div>
<div style="margin-top: 20px;">
<div style="margin: 0 auto; width: 940px; height: 409px; background-image: url('../../Content/images/finance-globe.jpg');"/>
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "ForgotPasswordForm" }))
{
<div style="margin: 0 auto; margin-top: 20px;">
<table id="ForgotPassword" style="margin: 0" auto;">
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.UserName, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "username" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.Email, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "email" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.PhoneNumber, new { htmlAttributes = new { #class = "form-control k-textbox", placeholder = "phone number" } })</td>
</tr>
<tr style="height:40px;">
<td>#Html.EditorFor(x => x.Code, new { htmlAttributes = new { #class = "form-control k-textbox checkError", placeholder = "code" } })</td>
</tr>
</table>
</div>
}
</div>
</body>
</html>
<script>
$(document).ready(function () {
$("#ForgotPasswordForm").kendoValidator();
});
</script>
The Model and View produce the following:
enter image description here
I do not want "Email is not valid" message to be displayed in case of regular expression validation fails.
I just need an exclamation sign.
How can I do that?

For your email field you can try adding data-email-msg attribute, which is way to customize the validation message for wrong email field value.
For ex: If you want to display a blank message for wrong value for email id you can do something like:
<input type="email" name="email" id="email" name="email" data-email-msg="">
And if you want to customize the required field validation message too, then you can add an another attribute data-required-msg as below:
<input type="email" name="email" id="email" name="email" data-email-msg="" data-required-msg="">

Related

Use stripe token to charge credit card with stripe element

I'm really stuck in this subject and maybe someone can help me out. I can always generate a token with stripe successfully but somehow my charge function doesn't wan't to work. I'm using the stripe element from their official documentation.
How can I find out where I have to search for the mistake because I don't get any error from the code. In the stripe dashboard I can see the generated tokens, that's why I think until this point there is everything right but I guess my mistake is in the view function. More precise I think the view function doesn't get the generated token from the javascript. Many thanks for your help in advance!
stripe_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
{% load static %}
<link rel="stylesheet" href="{% static 'css/stripe.css' %}">
<title>Document</title>
</head>
<body>
<div id="collapseStripe" class="wrapper">
<script src="https://js.stripe.com/v3/"></script>
<form action="" method="post" id="payment-form">
{% csrf_token %}
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element" class="StripeElement StripeElement--empty">
<div class="__PrivateStripeElement" style="margin: 0px !important; padding: 0px !important; border: none !important; display: block !important; background: transparent !important; position: relative !important; opacity: 1 !important;"><iframe frameborder="0" allowtransparency="true" scrolling="no" name="__privateStripeFrame4" allowpaymentrequest="true" src="https://js.stripe.com/v3/elements-inner-card-bfbabea0af3ed365b5fe9ce78692fd3c.html#style[base][color]=%2332325d&style[base][fontFamily]=%22Helvetica+Neue%22%2C+Helvetica%2C+sans-serif&style[base][fontSmoothing]=antialiased&style[base][fontSize]=16px&style[base][::placeholder][color]=%23aab7c4&style[invalid][color]=%23fa755a&style[invalid][iconColor]=%23fa755a&componentName=card&wait=false&rtl=false&keyMode=test&origin=https%3A%2F%2Fstripe.com&referrer=https%3A%2F%2Fstripe.com%2Fdocs%2Fstripe-js%2Felements%2Fquickstart&controllerId=__privateStripeController1" title="Secure payment input frame" style="border: none !important; margin: 0px !important; padding: 0px !important; width: 1px !important; min-width: 100% !important; overflow: hidden !important; display: block !important; height: 19.2px;"></iframe><input class="__PrivateStripeElement-input" aria-hidden="true" aria-label=" " autocomplete="false" maxlength="1" style="border: none !important; display: block !important; position: absolute !important; height: 1px !important; top: 0px !important; left: 0px !important; padding: 0px !important; margin: 0px !important; width: 100% !important; opacity: 0 !important; background: transparent !important; pointer-events: none !important; font-size: 16px !important;"></div>
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button>Submit Payment</button>
</form>
</div>
<div id="stripe-token-handler" class="is-hidden">Success! Got token: <span class="token"></span></div>
{% load static %}
<script src="{% static 'js/stripe.js' %}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function toggleDisplay() {
var x = document.getElementById("collapseStripe");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
};
</script>
</body>
</html>
views.py
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
def charge (request):
publishKey = settings.STRIPE_PUBLISHABLE_KEY
if request.method == 'POST':
try:
token = request.POST['stripeToken']
charge = stripe.Charge.create(
amount=999,
currency='usd',
description='Example charge',
source=token,
)
return redirect(request, 'registration/stripe_form.html')
except stripe.CardError as e:
message.info(request, "Your card has been declined.")
return render(request, 'registration/stripe_form.html')
stripe.js
var stripe = Stripe('pk_test_');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
stripeTokenHandler(result.token);
}
});
});
// Submit the form with the token ID.
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
var successElement = document.getElementById('stripe-token-handler');
document.querySelector('.wrapper').addEventListener('click', function() {
successElement.className = 'is-hidden';
});
// Not in demo.
function stripeTokenHandler(token) {
successElement.className = '';
successElement.querySelector('.token').textContent = token.id;
}

Data is not displayed on the browser from the blockchain server on solidity

I am trying to make a voting app using Blockchain on truffle framework. The data from the network is not rendered on the webpage.
Only loading is displayed but the actual content is not displayed even though I have connected by Blockchain accounts from Ganache to my metamask extension.
Here is my code:
Election.sol
pragma solidity ^0.5.0;
contract Election {
// Model a Candidate for first past the post system
struct Candidatepost {
uint id;
string name;
uint voteCount;
}
// Model as candidate for proportional party system
struct Candidateparty {
uint id;
string name;
uint voteCount;
}
// Store accounts that have voted
mapping(address => bool) public voters;
// Store Candidates
// Fetch Candidate
mapping(uint => Candidatepost) public cand_post;
mapping(uint => Candidateparty) public cand_party;
// Store Candidates Count
uint public partyCount;
uint public postCount;
uint[] public candidatesCount = [postCount,partyCount];
constructor () public {
addpostCandidate("Candidate 1");
addpostCandidate("Candidate 2");
addpartyCandidate("Candidate 1");
addpartyCandidate("Candidate 2");
candidatesCount = [postCount,partyCount];
}
function addpostCandidate (string memory _name) private {
postCount ++;
cand_post[postCount] = Candidatepost(postCount, _name, 0);
}
function addpartyCandidate (string memory _name) private {
partyCount ++;
cand_party[partyCount] = Candidateparty(partyCount, _name, 0);
}
// voted event
event votedEvent (
uint indexed _candidateId1,
uint indexed _candidateId2
);
function vote (uint _candidateId1, uint _candidateId2) public {
// require that they haven't voted before
require(!voters[msg.sender]);
// require a valid candidate
require(_candidateId1 > 0 && _candidateId1 <= postCount && _candidateId2 > 0 && _candidateId2 <= partyCount);
// record that voter has voted
voters[msg.sender] = true;
// update candidate vote Count
cand_post[_candidateId1].voteCount ++;
cand_party[_candidateId2].voteCount ++;
// trigger voted event
emit votedEvent(_candidateId1, _candidateId2);
}
}
App.js
App = {
web3Provider: null,
contracts: {},
account: '0x0',
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// TODO: refactor conditional
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContract();
},
initContract: function() {
$.getJSON("Election.json", function(election) {
// Instantiate a new truffle contract from the artifact
App.contracts.Election = TruffleContract(election);
// Connect provider to interact with contract
App.contracts.Election.setProvider(App.web3Provider);
App.listenForEvents();
return App.render();
});
},
// Listen for events emitted from the contract
listenForEvents: function() {
App.contracts.Election.deployed().then(function(instance) {
// Restart Chrome if you are unable to receive this event
// This is a known issue with Metamask
// https://github.com/MetaMask/metamask-extension/issues/2393
instance.votedEvent({}, {
fromBlock: 0,
toBlock: 'latest'
}).watch(function(error, event) {
console.log("event triggered", event)
// Reload when a new vote is recorded
App.render();
});
});
},
render: function() {
var electionInstance;
var loader = $("#loader");
var content = $("#content");
loader.show();
content.hide();
// Load account data
web3.eth.getCoinbase(function(err, account) {
if (err === null) {
App.account = account;
$("#accountAddress").html("Your Account: " + account);
}
});
//load contract data
App.contracts.Election.deployed().then(function(instance) {
electionInstance = instance;
return electionInstance.candidatesCount();
}).then(function(1) {
var postcandidatesResults = $("#postcandidatesResults");
postcandidatesResults.empty();
var partycandidatesResults = $("#partycandidatesResults");
partycandidatesResults.empty();
var postcandidatesSelect = $('#postcandidatesSelect');
postcandidatesSelect.empty();
var partycandidatesSelect = $('#partycandidatesSelect');
partycandidatesSelect.empty();
for (var i = 1; i <= 2; i++) {
electionInstance.cand_post(i).then(function(candidate) {
var id = candidate[0];
var name = candidate[1];
var voteCount = candidate[2];
// Render candidate Result
var candidateTemplate = "<tr><th>" + id + "</th><td>" + name + "</td><td>" + voteCount + "</td></tr>";
postcandidatesResults.append(candidateTemplate);
// Render candidate ballot option
var candidateOption = "<option value='" + id + "' >" + name + "</ option>";
postcandidatesSelect.append(candidateOption);
});
}
for (var j = 1; j <= 2; j++) {
electionInstance.cand_party(i).then(function(candidate) {
var id2 = candidate[0];
var name2 = candidate[1];
var voteCount2 = candidate[2];
// Render candidate Result
var candidateTemplate2 = "<tr><th>" + id2 + "</th><td>" + name2 + "</td><td>" + voteCount2 + "</td></tr>";
partycandidatesResults.append(candidateTemplate2);
// Render candidate ballot option
var candidateOption2 = "<option value='" + id2 + "' >" + name2 + "</ option>";
partycandidatesSelect.append(candidateOption2);
});
}
return electionInstance.voters(App.account);
}).then(function(hasVoted) {
// Do not allow a user to vote
if(hasVoted) {
$('form').hide();
}
loader.hide();
content.show();
}).catch(function(error) {
console.warn(error);
});
},
castVote: function() {
var candidateId1 = $('#postcandidatesSelect').val();
var candidateId2 = $('#partycandidatesSelect').val();
App.contracts.Election.deployed().then(function(instance) {
return instance.vote(candidateId1, candidateId2, { from: App.account });
}).then(function(result) {
// Wait for votes to update
$("#content").hide();
$("#loader").show();
}).catch(function(err) {
console.error(err);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Election Results</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" style="width: 650px;">
<div class="row">
<div class="col-lg-12">
<h1 class="text-center">
<div class="row d-flex justify-content-center" style="border:none;background:white;">
<div class="col-md-1 col-3">
<img class="mx-auto d-block img-fluid" src="images/logo.png" style="" alt="">
</div>
</div></h1>
<hr/>
<br/>
<h1 class="text-center">National Election-2075</h1>
<h1 class="text-center">Election Updates</h1>
<div id="loader">
<p class="text-center">Loading...</p>
</div>
<div id="content" style="display: none;">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="postcandidatesResults">
</tbody>
</table>
<hr/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody id="partycandidatesResults">
</tbody>
</table>
<hr/>
<form onSubmit="App.castVote(); return false;">
<div class="form-group">
<label for="postcandidatesSelect">Select Candidate</label>
<select class="form-control" id="postcandidatesSelect">
</select>
</div>
<div class="form-group">
<label for="partycandidatesSelect">Select Candidate</label>
<select class="form-control" id="partycandidatesSelect">
</select>
</div>
<button type="submit" class="btn btn-primary">Vote</button>
<hr />
</form>
<p id="accountAddress" class="text-center"></p>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Any call to the blockchain is async(returns a promise). You need to either handle the promise with a .then() or you can use async await. Basically anything chained after electionInstance is async. For example:
electionInstance.candidatesCount();
electionInstance.cand_party
electionInstance.voters

DataTables using Export Buttons and YADCF causes select lists to be exported

Is there a way to use the export buttons and yadcf chozen filter together without messing up the column headers in the export see below the column Order Number has Select appended
Order NumberSelect
value20766903232802532374885123748865237490732374944323749625x
Code:
<!doctype html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.3.1/css/buttons.dataTables.min.css">
<link rel="stylesheet" href="/newwebadmin/mvc/orders/assets/css/cancellationStatistics.css" />
<link rel="stylesheet" type="text/css" href="/newwebadmin/js/chosen/chosen.min.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/yadcf/0.9.1/jquery.dataTables.yadcf.css">
<script src="/newwebadmin/mvc/orders/assets/js/cancellations/ChartNew.js"></script>
<script src="/newwebadmin/mvc/orders/assets/js/cancellations/shapesInChart.js"></script>
<script src="/newwebadmin/mvc/orders/assets/js/cancellations/specialInChartData.js"></script>
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.3.1/js/buttons.flash.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/buttons/1.3.1/js/buttons.print.min.js"></script>
<script src="/newwebadmin/js/Chosen/chosen.jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript" language="javascript" src="//cdnjs.cloudflare.com/ajax/libs/yadcf/0.9.1/jquery.dataTables.yadcf.min.js"></script>
<style>
input[type="search"] {
border:1px #cccccc solid;
padding:2px;
border-radius: 2px;
}
</style>
<title>Cancel Order Reportle></title>
</head>
<cfset local.getCancellationReportData = rc.cancellations>
<body>
<!--- <cfdump var="#local#"> --->
<cfoutput>
<div class="flexbox-container">
<div class="main-content clearfix">
<div class="container">
<form action="" method="post">
<label for="startDate">Date Range: </label>
<input type="text" id="startDate" name="startDate" class="button" value="#structKeyExists(form, "startDate") ? form.startDate : DateFormat(Now(),'mm/dd/yyyy') #">
<label for="endDate">to</label>
<input type="text" id="endDate" name="endDate" class="button" value="#structKeyExists(form, "endDate") ? form.endDate : DateFormat(DateAdd('m',1,Now()),'mm/dd/yyyy') #">
<input type="submit" id="btnFilter" value="Filter" class="button">
</form>
<br><br>
<button id="platinum" class="button">Show Platinum Customers</button>
<button id="nonplatinum" class="button">Show Non-Platinum Customers</button>
<button id="all" class="button">Show All</button>
<br><br>
<table id="report" class="display" cellspacing="0" width="100%">
<thead>
<th align="left">Order Number</th>
<th align="left">VendorID</th>
<th align="left">User Index</th>
<th align="left">Customer Type</th>
<th align="left">Date</th>
<th align="left">## of items cancelled</th>
<th align="left">Total$</th>
<th align="left">Canceled By</th>
<th align="left">Reason</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="5" style="text-align:right">Total:</th>
<th style="text-align:left"></th>
<th colspan="2" style="text-align:left"></th>
<th></th>
</tr>
</tfoot>
<tbody>
<cfloop query="local.getCancellationReportData">
<tr data-isPlatinum="#is_platinum#">
<td>#order_number#</td>
<td>#len(vendorID) ? vendorID: 'unknown'#</td>
<td>#len(dbo_tblEmployee_ID) ? dbo_tblEmployee_ID: 'unknown'#</td>
<td>#customerType#</td>
<td>#DateFormat(date,'mm/dd/yyyy')# #timeFormat(date,'hh:mm TT')#</td>
<td>#qty#</td>
<td align="right">#DollarFOrmat(ExtendedCost)#</td>
<td>#cancelledBy#</td>
<td>#cancellation_reason#</td>
</tr>
</cfloop>
</tbody>
</table>
</div>
</div>
</div>
</cfoutput>
<script>
$(document).ready(function() {
var table = $('#report').DataTable( {
dom: 'Bfrtip',
buttons: [
{extend :'excel', text:'Export to Excel'}
,{extend :'pdf' , text:'Export to PDF', orientation: 'landscape', pageSize: 'LEGAL'}
,'print'
],
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
total = api
.column( 6 )
.data()
.reduce( function (a, b) {
return intVal(intVal(a) + intVal(b)).toFixed(2);
} );
// Total over this page
pageTotal = api
.column( 6, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(intVal(a) + intVal(b)).toFixed(2);
}, 0 );
// Total over all pages
cantotal = api
.column( 5 )
.data()
.reduce( function (a, b) {
return intVal(intVal(a) + intVal(b));
} );
// Total over this page
canpageTotal = api
.column( 5, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(intVal(a) + intVal(b));
}, 0 );
// Update footer
$( api.column( 6 ).footer() ).html(
'$'+pageTotal +' ( $'+ total +' total )'
);
// Update footer
$( api.column( 5 ).footer() ).html(
''+canpageTotal +' ( out of '+ cantotal +')'
);
}
});
$("#platinum").click(function() {
$.fn.dataTable.ext.search.pop();
table.draw();
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) {
return $(table.row(dataIndex).node()).attr('data-isPlatinum') == 1;
}
);
table.draw();
});
$("#nonplatinum").click(function() {
$.fn.dataTable.ext.search.pop();
table.draw();
$.fn.dataTable.ext.search.push(
function(settings, data, dataIndex) {
return $(table.row(dataIndex).node()).attr('data-isPlatinum') == 0;
}
);
table.draw();
});
$("#all").click(function() {
$.fn.dataTable.ext.search.pop();
table.draw();
});
$('.button').button();
var dateFormat = "mm/dd/yy",
from = $( "#startDate" )
.datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
.on( "change", function() {
to.datepicker( "option", "minDate", getDate( this ) );
}),
to = $( "#endDate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3
})
.on( "change", function() {
from.datepicker( "option", "maxDate", getDate( this ) );
});
function getDate( element ) {
var date;
try {
date = $.datepicker.parseDate( dateFormat, element.value );
} catch( error ) {
date = null;
}
return date;
};
yadcf.init(table, [
{column_number : 0},
{column_number : 1, filter_type: "multi_select",select_type: 'chosen'},
{column_number : 2},
{column_number : 3},
{column_number : 4},
{column_number : 5},
{column_number : 6},
{column_number : 7},
{column_number : 8},
{column_number : 9}
]);
});
</script>
I have tied this
buttons: [
{extend :'excel', text:'Export to Excel'}
,{extend :'pdf' , text:'Export to PDF', orientation: 'landscape', pageSize: 'LEGAL'
,exportOptions:{
rows: ':not(.notPrintable)'
}
}
,'print'
],
...
yadcf.init(table, [
{column_number : 0},
{column_number : 1, filter_type: "multi_select",select_type: 'chosen'},
{column_number : 2},
{column_number : 3},
{column_number : 4},
{column_number : 5},
{column_number : 6},
{column_number : 7},
{column_number : 8}
]);
$(".yadcf-filter-wrapper").addClass("notPrintable");
This is what worked for me
buttons: [
{extend :'excel', text:'Export to Excel'
,exportOptions: {
format: {
header: function ( data, row, column, node ) {
var newdata = data;
newdata = newdata.replace(/<.*?<\/*?>/gi, '');
newdata = newdata.replace(/<div.*?<\/div>/gi, '');
newdata = newdata.replace(/<\/div.*?<\/div>/gi, '');
return newdata;
}
}
}
}
,{extend :'pdf' , text:'Export to PDF'
,exportOptions: {
format: {
header: function ( data, row, column, node ) {
var newdata = data;
newdata = newdata.replace(/<.*?<\/*?>/gi, '');
newdata = newdata.replace(/<div.*?<\/div>/gi, '');
newdata = newdata.replace(/<\/div.*?<\/div>/gi, '');
return newdata;
}
}
}
}
,{extend :'print' , text:'Print'
,exportOptions: {
format: {
header: function ( data, row, column, node ) {
var newdata = data;
newdata = newdata.replace(/<.*?<\/*?>/gi, '');
newdata = newdata.replace(/<div.*?<\/div>/gi, '');
newdata = newdata.replace(/<\/div.*?<\/div>/gi, '');
return newdata;
}
}
}
}
],

python code error for movie project "TypeError: this constructor takes no arguments"

I am working on a code project for Udacity and I get these 2 errors I dont get I have attached the pictures. One error is with parenthesis and when I remove the parenthesis I get an error on the code saying invalid syntax.
import webbrowser
class Movie():
valid_ratings = ["G", "R", "PG-13", "R"]
def _init_(self, movie_title, movie_storyline, poster_image,
trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
webbrowser.open(self.trailer_youtube_url)
import fresh_tomatoes
import media
toy_story = media.Movie("Toy Story",
"A story of a boy and his toys come to life",
"http://upload.wikimedia.org/wikipedia/en/1/13/Toy_Story.jpg",
"http://www.youtube.com/watch?v=vwyZH85NQC4")
The_devils_double = media.Movie("The_devils_double",
"The story of the son of sadam hussain's body double",
"https://upload.wikimedia.org/wikipedia/en/4/4c/The_Devil%27s_Double.jpg",
"https://www.youtube.com/watch?v=2-MsGEWFiYg",)
Movie_300 = media.Movie("300",
"300 spartans vs an amry of persians",
"https://upload.wikimedia.org/wikipedia/en/5/5c/300poster.jpg",
"https://www.youtube.com/watch?v=wDiUG52ZyHQ")
Ratatouille = media.Movie("Ratatouille",
"A rat is a chef in paris",
"https://upload.wikimedia.org/wikipedia/en/5/50/RatatouillePoster.jpg",
"https://www.youtube.com/watch?v=c3sBBRxDAqk")
Star_Wars_Episode_III = media.Movie("Star_Wars_Episode_III",
"Akin Skywalker goes dark",
"https://upload.wikimedia.org/wikipedia/en/9/93/Star_Wars_Episode_III_Revenge_of_the_Sith_poster.jpg",
"https://www.youtube.com/watch?v=5UnjrG_N8hU")
Office_Space = media.Movie("Office_Space ",
"A movie about how work sucks",
"https://upload.wikimedia.org/wikipedia/en/8/8e/Office_space_poster.jpg",
"https://www.youtube.com/watch?v=kwQziVIzDeg")
#movies = [toy_story, The_devils_double, 300, Ratatouille, Star_Wars_Episode_III , Office_Space ]
fresh_tomatoes.open_movies_page(movies)
print(media.Movie.valid_ratings)
import webbrowser
import os
import re
# Styles and scripting for the page
main_page_head = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fresh Tomatoes!</title>
<!-- Bootstrap 3 -->
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap-theme.min.css">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<style type="text/css" media="screen">
body {
padding-top: 80px;
}
#trailer .modal-dialog {
margin-top: 200px;
width: 640px;
height: 480px;
}
.hanging-close {
position: absolute;
top: -12px;
right: -12px;
z-index: 9001;
}
#trailer-video {
width: 100%;
height: 100%;
}
.movie-tile {
margin-bottom: 20px;
padding-top: 20px;
}
.movie-tile:hover {
background-color: #EEE;
cursor: pointer;
}
.scale-media {
padding-bottom: 56.25%;
position: relative;
}
.scale-media iframe {
border: none;
height: 100%;
position: absolute;
width: 100%;
left: 0;
top: 0;
background-color: white;
}
</style>
<script type="text/javascript" charset="utf-8">
// Pause the video when the modal is closed
$(document).on('click', '.hanging-close, .modal-backdrop, .modal', function (event) {
// Remove the src so the player itself gets removed, as this is the only
// reliable way to ensure the video stops playing in IE
$("#trailer-video-container").empty();
});
// Start playing the video whenever the trailer modal is opened
$(document).on('click', '.movie-tile', function (event) {
var trailerYouTubeId = $(this).attr('data-trailer-youtube-id')
var sourceUrl = 'http://www.youtube.com/embed/' + trailerYouTubeId + '?autoplay=1&html5=1';
$("#trailer-video-container").empty().append($("<iframe></iframe>", {
'id': 'trailer-video',
'type': 'text-html',
'src': sourceUrl,
'frameborder': 0
}));
});
// Animate in the movies when the page loads
$(document).ready(function () {
$('.movie-tile').hide().first().show("fast", function showNext() {
$(this).next("div").show("fast", showNext);
});
});
</script>
</head>
'''
# The main page layout and title bar
main_page_content = '''
<body>
<!-- Trailer Video Modal -->
<div class="modal" id="trailer">
<div class="modal-dialog">
<div class="modal-content">
<a href="#" class="hanging-close" data-dismiss="modal" aria-hidden="true">
<img src="https://lh5.ggpht.com/v4-628SilF0HtHuHdu5EzxD7WRqOrrTIDi_MhEG6_qkNtUK5Wg7KPkofp_VJoF7RS2LhxwEFCO1ICHZlc-o_=s0#w=24&h=24"/>
</a>
<div class="scale-media" id="trailer-video-container">
</div>
</div>
</div>
</div>
<!-- Main Page Content -->
<div class="container">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">Fresh Tomatoes Movie Trailers</a>
</div>
</div>
</div>
</div>
<div class="container">
{movie_tiles}
</div>
</body>
</html>
'''
# A single movie entry html template
movie_tile_content = '''
<div class="col-md-6 col-lg-4 movie-tile text-center" data-trailer-youtube-id="{trailer_youtube_id}" data-toggle="modal" data-target="#trailer">
<img src="{poster_image_url}" width="220" height="342">
<h2>{movie_title}</h2>
</div>
'''
def create_movie_tiles_content(movies):
# The HTML content for this section of the page
content = ''
for movie in movies:
# Extract the youtube ID from the url
youtube_id_match = re.search(
r'(?<=v=)[^&#]+', movie.trailer_youtube_url)
youtube_id_match = youtube_id_match or re.search(
r'(?<=be/)[^&#]+', movie.trailer_youtube_url)
trailer_youtube_id = (youtube_id_match.group(0) if youtube_id_match
else None)
# Append the tile for the movie with its content filled in
content += movie_tile_content.format(
movie_title=movie.title,
poster_image_url=movie.poster_image_url,
trailer_youtube_id=trailer_youtube_id
)
return content
def open_movies_page(movies):
# Create or overwrite the output file
output_file = open('fresh_tomatoes.html', 'w')
# Replace the movie tiles placeholder generated content
rendered_content = main_page_content.format(
movie_tiles=create_movie_tiles_content(movies))
# Output the file
output_file.write(main_page_head + rendered_content)
output_file.close()
# open the output file in the browser (in a new tab, if possible)
url = os.path.abspath(output_file.name)
webbrowser.open('file://' + url, new=2)
Your init method has single underscores. It needs to have double underscores before and after "init".
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
Also, you're missing a comma when you create the Movie_300 object. It should look like this (with a comma after the wikimedia link):
Movie_300 = Movie("300",
"300 spartans vs an amry of persians",
"https://upload.wikimedia.org/wikipedia/en/5/5c/300poster.jpg",
"https://www.youtube.com/watch?v=wDiUG52ZyHQ")
As an aside, the convention to name variables in Python is to use all lowercase.

Input not being displayed

I have an input field. When the user clicks it some javascript converts the text to a Raphael JS library variable. I want to put each letter into a Raphael variable called string followed by a \n. When the user clicks on the button nothing is displayed. Can someone help me fix this?...
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var string = "";
function animate() {
var txt = document.getElementById("words").value;
var splittxt = txt.split("");
var i;
for (i = 0; i < splittxt.length; i++) {
var string = splittxt[i] + "\n\n";
}
}
</script>
<style type="text/css">
#letters
{
text-align:center;
margin-left:10px;
width:25px;
float:left;
text-shadow:10px 5px 1px #4D4D4D;
filter:DropShadow(Color=#4D4D4D, OffX=10, OffY=5);
font-weight:bold;
}
</style>
</head>
<body>
Text: <input type="text" id="words" />
<input type="button" value="Animate" onclick="animate()" />
<div id='letters'></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px; background-color:blue;">
</div>
<div id="elps" style="ma
rgin-left:100px;"/>
<script type="text/javascript"> //all your javascript goes here
var r = new Raphael("draw-here-raphael");
var string = r.text(50,50, string);
</script>
</body>
</html>
Instead of setting the variable string, you want add to it. Also, there were quite a few other updates I made to your excerpt...
Setting variables to reserved words can also cause a lot of problems.
http://jsfiddle.net/fN9Me/
<html>
<head>
<script src="raphael.js"></script>
<script src="jquery-1.7.2.js"></script>
<script type="text/javascript">
var alpha = "";
var something = "";
var r = "";
var txt = "";
var splittxt = "";
$(function() {
r = new Raphael("draw-here-raphael");
$("#animate").click(function() {
txt = $("#words").val();
splittxt = txt.split("");
var i;
for (i = 0; i < splittxt.length; i++) {
something += splittxt[i] + "\n\n";
}
alpha = r.text(50, 50, something);
});
});
</script>
<style type="text/css">
#letters
{
text-align:center;
margin-left:10px;
width:25px;
float:left;
text-shadow:10px 5px 1px #4D4D4D;
filter:DropShadow(Color=#4D4D4D, OffX=10, OffY=5);
font-weight:bold;
}
</style>
</head>
<body>
Text: <input type="text" id="words" value="" />
<input id="animate" type="button" value="Animate" />
<div id='letters'></div>
<div id="draw-here-raphael" style="height: 200px; width: 400px; margin-top:0px; background-color:blue;">
</div>
<div id="elps" style="margin-left:100px;"/>
</body>
</html>
Update:
To remove the previous text, it is just a matter of utilizing the Raphael remove function. Also we have to reset the variable something
if (alpha) alpha.remove();
http://jsfiddle.net/fN9Me/1/
You're not actually displaying anything. This line:
document.getElementById("letters").innerHTML + splittxt[i] + "<br>";
needs to be something like:
document.getElementById("letters").innerHTML += splittxt[i] + "<br>";
The value of the words input is blank => when you call the split method var splittxt = txt.split(""); the splittxt has a length == 0, and therefore the body of the for statement is never executed.