django admin custom time widget - django

I am trying to override django's time widget.
if (!$) {
$ = django.jQuery;
}
function overrideTimeOptions() {
$('.timelist').each(function(num, el) {
var time_format = '%H:%M';
$(el).html('');
for (var i=1; i<25; i++) {
var time = new Date(1970,1,1,i,0,0);
console.log(time)
var lnk = "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '" + time.strftime(time_format) + "');"
console.log("this is link");
console.log(lnk);
$(el).append('<li>' + time.strftime(time_format) + '</li>');
}
});
}
setTimeout(function(){overrideTimeOptions()},500);
Here I can see the time options but when I click the time it gives me some weired value in the input field like NaNaNa
Can anyone help me on this whats going on here ??

Related

Dynamic controllers in Ember.js

I want to make some dynamic controllers based on the top-level keys of a JSON object where the second level keys become variables for the view. Is this possible?
E.g.
App.dat = { "First": {Var1: "x", Var2: "y"}, "Second": {Var3: "z"}}
I then want to have a FirstController, SecondController, etc. created automatically and then be able to access {{Var1}}, {{Var2}} and {{Var3}} in my view.
The routes work fine:
App.Router.map(function() {
this.route('data');
for(var key in App.dat) {
this.route(key);
}
});
But I can't get the controllers to work. The closest I came was with some hacky eval code:
for(var key in App.dat) {
console.log("App." + key + "Controller = Ember.Controller.extend();");
eval("App." + key + "Controller = Ember.Controller.extend();");
Ember.$.each(eval("App.dat."+key), function(kkey,v) {
console.log("App." + key + "Controller." + kkey + " = '" + v + "';");
eval("App." + key + "Controller." + kkey + " = '" + v + "';");
});
}
That results in the following evaluations:
App.FirstController = Ember.Controller.extend();
App.FirstController.Var1 = "x";
App.FirstController.Var2 = "y";
App.SecondController = Ember.Controller.extend();
App.FirstController.Var2 = "z";
But I'm clearly missing something because I can't access {{x}},{{y}} or {{z}} from the view. I am aware the correct way to instantiate variables for the view is with a constructor object like:
App.FirstController = Ember.Controller.extend({Var1: "x", Var2: "y"});
But that isn't practical and I can't figure out where the constructor object gets stored.
Thanks in advance.
You can override Ember.DefaultResolver's resolveController method. Which is responsible for lookuping controller classes.
App = Ember.Application.create({
Resolver: Ember.DefaultResolver.extend({
resolveController: function(parsedName) {
var props = Ember.get(App.dat, parsedName.name);
if (!Ember.isNone(props)){
return Ember.Controller.extend(props);
}
return this._super(parsedName);
}
})
});
jsbin
After some careful bug hunting, the following code works fine:
for(var key in App.dat) {
properties = Array();
Ember.$.each(eval("App.dat."+key), function(kkey,v) {
properties.push(kkey + ": '" + v + "'")
});
console.log("App." + key + "Controller = Ember.ObjectController.extend({" +properties + "})");
eval("App." + key + "Controller = Ember.ObjectController.extend({"+ properties + "})");
}
Is there a less hacky way to do this than by eval()ing everything? Remember this data comes from JSON, so I can't imagine this would be safe in a real app.

App Part issues, spPageContextInfo

I am trying to create an SharePoint hosted app that contains an app part, this app part should show what the user is following. I have used working code as an example in the app, but I don't get it to work inside of the App Part.
I get this within the app part: "Uncaught ReferenceError: _spPageContextInfo is not defined".
If anyone has a real example how to make this work inside an app part, and using social.following, please help!
This is the code in App.js:
var headline = new Array("People", "Documents", "Sites");
var ActorImg = new Array("/_layouts/15/images/person.gif", "/_layouts/15/images/lg_ICGEN.gif", "/_layouts/15/images/siteicon_16x16.png");
function doJSON(RESTuri, success, fail) {
var restUrl = _spPageContextInfo.webAbsoluteUrl + RESTuri;
var executor = new SP.RequestExecutor(_spPageContextInfo.webAbsoluteUrl);
executor.executeAsync(
{
url: restUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: success,
error: fail
}
);
}
function renderSuccess(data) {
var jsonObject = JSON.parse(data.body);
var n = document.getElementById('jsonout');
n.innerHTML = data.body;
var results = jsonObject.d.Followed.results;
var str = '';
var old = -1;
var img = null;
for (j = 0; j < 5; j++) {
str += "<div class=\"container container" + j + "\">";
for (i = 0; i < results.length; i++) {
if (j != results[i].ActorType) continue;
if (old != results[i].ActorType) str += "<h1 class=\"headline" + results[i].ActorType + "\">" + headline[results[i].ActorType] + "</h1>";
img = results[i].ImageUri;
if (img == null) img = ActorImg[results[i].ActorType];
switch (results[i].ActorType) {
case 0:
// Use case: depending on ActorType if you want to use indiviual markup for every item-type
str += "<a title=\"" + results[i].Name + "\" class=\"link" + results[i].ActorType + "\" style=\"background-image:url(" + img + ")\" href=\"" + results[i].Uri + "\">" + results[i].Name + "</a>";
break;
default:
str += "<a title=\"" + results[i].Name + "\" class=\"link" + results[i].ActorType + "\" style=\"background-image:url(" + img + ")\" href=\"" + results[i].Uri + "\">" + results[i].Name + "</a>";
break;
}
old = results[i].ActorType;
}
str += "</div>";
}
n = document.getElementById('htmlout');
n.innerHTML = str + "<h1></h1>";
}
function renderFail(data, errorCode, errorMessage) {
n = document.getElementById('htmlout');
n.innerHTML = errorMessage;
}
$(document).ready(function () {
doJSON("/_api/social.following/my/followed%28types=15%29", renderSuccess, renderFail);
});
This is the div that's being used in both the app page(default.aspx) and the app part page(AppPart.aspx):
<div class="classic">
<pre id="jsonout" style="display: none;"></pre>
<div id="htmlout"></div>
</div>
Sorry guys. I solved it by just adding a reference to the sp.requestexecutor.js file, and parsed the host- and app-url from the querystring

How to pass multipart file data to a web service

I wanna do something like this.
1.Uploading a file from a jsp in multipart
2.Calling a servlet
3.In dopost of that servlet i wanna call a webservice which takes all the params passed by jsp to servlet along with the multipart data.
dopost(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response){
webserviceMethod(request,response);
}
I'm stuck on third point where I can set all request params to webservice method. But I don't know how to pass multipart file data to that websevice. I failed to do so. How can i do that part??
Have a look at that jquery plugin:
http://jquery.malsup.com/form/
I'm also using this in my Application together with a java servlet:
uploadImage: function (e) {
var self = this;
self.ignoreDrag(e);
if ($('#feed_imageUploader').find('input').hasClass('error')) {
return;
}
//cant put this in an model - ajaxSubmit has no done callback
$('#img_uploaded h1').text(polyglot.t('iview.loading'));
$('#feed_imageUploader').ajaxSubmit({
target: '#img_uploaded',
type: "POST",
url: path.apiPath + 'item.uploadImg/' + self.itemId + '/' + token,
dataType: "text",
async: true,
success: function () {
self.afterUploadImage();
}
});
},
afterUploadImage: function () {
var self = this;
self.changed = true;
var xFactorItemImage = 0;
var yFactorItemImage = 0;
var randomnumber = Math.floor(Math.random() * 10100000);
$('#img_uploaded').html("<img src=\"" + path.tempImage + userId + "_" + self.itemId + ".jpg?id=" + randomnumber + "\" style=\"display:none\" id=\"cropPhoto_uploaded\">");
var theImage = new Image();
var cropPhoto = $('#cropPhoto_uploaded');
theImage.src = cropPhoto.attr("src");
var widthPhoto = 0;
var heightPhoto = 0;
var NwidthPhoto = 0;
var NheightPhoto = 0;
$(theImage).load(function () {
$('#img_uploaded h1').empty();
$('#additemimage').hide();
NwidthPhoto = theImage.width;
NheightPhoto = theImage.height;
cropPhoto.css({
maxHeight: $('#img_uploaded').height() + 'px',
maxWidth: $('#img_uploaded').width() + 'px'
});
cropPhoto.show();
$('#addimage_upload').fadeIn(aSpeed.middle);
widthPhoto = cropPhoto.width();
heightPhoto = cropPhoto.height();
xFactorItemImage = NwidthPhoto / widthPhoto;
yFactorItemImage = NheightPhoto / heightPhoto;
cropPhoto.Jcrop({
setSelect: helper.getMiddleSelectionOfImage(widthPhoto, heightPhoto, widthPhoto, heightPhoto),
bgOpacity: 0.3,
onChange: showItemImageCoords,
onSelect: showItemImageCoords
});
});
function showItemImageCoords(c) {
$('#x111').val(parseInt(xFactorItemImage * c.x));
$('#y111').val(parseInt(yFactorItemImage * c.y));
$('#x222').val(parseInt(xFactorItemImage * c.w));
$('#y222').val(parseInt(yFactorItemImage * c.h));
}
},
And the servlet part:
public void UploadImage(HttpServletRequest request, String filename, String folder,String bucketname) {
File file;
PropertyReader mainconf = new PropertyReader();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items ;
mainconf.getProb("conf/MainConfig.properties");
s3 s3=new s3();
try {
items = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = items.iterator();
//Iterate through the items
String finalPath = "";
FileItem fi;
while (i.hasNext()) {
fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String your_os = System.getProperty("os.name").toLowerCase();
String workingDir = "images";
finalPath = mainconf.read("imagePath");
if (your_os.indexOf("win") >= 0) {
finalPath = finalPath + workingDir + "\\" + folder + "\\";
} else if (your_os.indexOf("nix") >= 0 || your_os.indexOf("nux") >= 0) {
finalPath = finalPath + workingDir + "/" + folder + "/";
} else {
finalPath = finalPath + workingDir + "{others}" + folder + "{others}";
}
file = new File(finalPath + filename + ".jpg");
fi.write(file);
s3.writeFile(bucketname, file, filename+".jpg");
file.delete();
}
break;
}
} catch (Exception ex) {
Logger.getLogger(UploadItemImage.class.getName()).log(Level.SEVERE, null, ex);
}
}

Random alert text and pop up only once

I'm try to write up code that will allow me to create a message with text that randomly displays one of three messages. In addition, this message will appear as an alert after you click a button. I now want to also program the button so it will only appear once per user. I've been able to make the random text part work, but not the one-time pop up feature. Let me know what I should do! Below is my code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Random thingy</title>
<script language type="text/javascript">
<!--
function getMessage() {
var ar = new Array(20)
ar[0] = "your assignment will be GRADED"
ar[1] = "your assignment will be UNGRADED"
ar[2] = "your assignment will be FUN"
// add as many more that you can stand but make
// sure you update the value '7' in the alert box
var now = new Date()
var sec = now.getSeconds()
alert("Your Grading Scheme:\n\n" + ar[sec % 3])
}
<!-- Begin
var expDays = 1; // number of days the cookie should last
var page = "only-popup-once.html";
var windowprops = "width=300,height=200,location=no,toolbar=no,menubar=no,scrollbars=no,resizable=yes";
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function amt(){
var count = GetCookie('count')
if(count == null) {
SetCookie('count','1')
return 1
}
else {
var newcount = parseInt(count) + 1;
DeleteCookie('count')
SetCookie('count',newcount,exp)
return count
}
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function checkCount() {
var count = GetCookie('count');
if (count == null) {
count=1;
SetCookie('count', count, exp);
alert('MESSAGE');
}
else {
count++;
SetCookie('count', count, exp);
}
}
// End -->
</script>
</head>
<body onLoad="getMessage(); checkCount()">
<form>
<input type="button" name="again" value="Your Self-Assessment Grading Scheme. Click To Find Out." onClick="getMessage()">
</form>
</body>
</html>

Google Friend Connect fcauth cookie in php

this may be easy for most of you .. but not me.
I am using some "sample" Google code - as it fits my purpose so why change what works - but for the life of me I cannot access/find/get etc the FCAuth cookie after a user is logged in.
Help please - thanks in advance.
Here is my code (the Site ID is in a set variable, and all the calls work todate. just need to find/get the FCAuth cookie.
var viewer, ownerFriends, activities;
google.friendconnect.container.setParentUrl('/api/' /* location of rpc_relay.html and canvas.html */);
google.friendconnect.container.loadOpenSocialApi({
site: SITE_ID,
onload: function() { initAllData(); }});
function initAllData() {
var params = {};
params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
[opensocial.Person.Field.ID,opensocial.Person.Field.NAME,opensocial.Person.Field.THUMBNAIL_URL,opensocial.Person.Field.PROFILE_URL];
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest('VIEWER', params), 'viewer');
req.add(req.newFetchPeopleRequest(
new opensocial.IdSpec({'userId' : 'OWNER', 'groupId' : 'FRIENDS'}), params),
'ownerFriends');
req.add(req.newFetchActivitiesRequest(new opensocial.IdSpec({'userId' : 'OWNER', 'groupId' : 'FRIENDS'})), 'activities');
var idspec = new opensocial.IdSpec({ 'userId' : 'VIEWER','groupId' : 'FRIENDS' });
req.add(req.newFetchPeopleRequest(idspec), 'viewer_friends');
req.send(onData);
req.send(setupData);
};
function setupData(data) {
ownerFriends = data.get('ownerFriends').getData().asArray();
var html = "";
for (var i = 0; i < ownerFriends.length && i < 8; i++) {
var person = ownerFriends[i];
html += "<a title='" + person.getField("displayName") + "' href='" + person.getField("profileUrl") + "'>";
html += "<img class='memberPhoto' src='" + person.getField("thumbnailUrl") + "' width='50px' alt='" + person.getField("displayName") + "'/>";
html += "</a> ";
};
document.getElementById('members').innerHTML = html;
viewer = data.get('viewer').getData();
if (viewer) {
document.getElementById('memberstate').innerHTML =
'<h2>' + viewer.getField("displayName") + ' welcome to the Yoga Council of Canada </h2>' ;
} else {
document.getElementById('memberstate').innerHTML =
'<h2>Join with one click</h2> After joining, you will automatically appear as a recent member.';
}
viewer = data.get('viewer').getData();
if (viewer) {
document.getElementById('profile').innerHTML =
'<img align="left" src="' + viewer.getField("thumbnailUrl") + '" style="margin-right: 20px;" >' +
'<strong>' + viewer.getField("displayName") + '</strong><br>' +
'Settings<br>' +
'Invite a friend<br>' +
'Sign out<br>';
} else {
google.friendconnect.renderSignInButton({ 'id': 'profile' });
}
};
function onData(data) {
if (!data.get("viewer_friends").hadError()) {
var site_friends = data.get("viewer_friends").getData();
var list = document.getElementById("friends-list");
list.innerHTML = "";
site_friends.each(function(friend) {
list.innerHTML += "<li>" + friend.getDisplayName() + "</li>";
});
}
};
OK, I am/was being totally thick, the cookie is automatically set as
$_COOKIE['fcauth<your appID>'];
So you can "just call it" i.e.
<?php if($_COOKIE['fcauth<your appID>']): do something endif; ?>