FB.UI callback with scopes on Backbone - backbone.js

var obj={
method: 'feed',
name: 'Je viens de créer son premier domaine : "' + this.model.attributes.name + '"',
caption: 'Entrez dans l\'univers du vin avec Vinoga',
description: (
'Ayez un domaine plus grand, plus beau ou plus prestigieux que vos amis. Challengez vos amis à travers de nombreux mini-jeux et rendez-leur visite '
),
link: 'http://www.vinoga.com',
picture: 'https://twimg0-a.akamaihd.net/profile_images/3095682321/79e5bb5014d6b118b08c5b11bd2a81e8.jpeg'
};
function callback(response)
{
this.model.setActivation(); // HERE
alert('toto');
}
FB.ui(obj, callback);
},
I got an error about this.model.setActivation is undefined ...
Do you have any idea how to solve this?
Thanks in Advance
Pierre

You can use underscore's bind helper to set the context for the callback.
FB.ui(obj, _.bind(callback, this));

Related

"Cannot read property 'cache' of undefined" when I check a member role

I want to make a mute command for my Discord bot but that create errors:
C:\Program Files\nodejs\node.exe .\index.js
|------ Bot on ------|
index.js:22
Uncaught TypeError: Cannot read property 'cache' of undefined
No debugger available, can not send 'variables'
Process exited with code 1
I want to check if the user who is mentionned has already the mute role and if the executor has an admin role. But that create this error.
My code:
bot.on("message", async message => {
if(message.content.startsWith(prefix + "mute")){
let User = message.mentions.users.first();
let time = message.content.split(" ").slice(2)
let reason = message.content.split(" ").slice(3)
if(!reason){ let reason = "aucune"}
if(!time || !User) return message.reply("Veuillez entrer une commande valide !\n" + prefix + "mute #user <temps> <raison>")
let dUser = User.id
if(dUser == message.author.id) return message.reply("Vous ne pouvez pas vous mute vous même !")
if(isNaN(time[0]) || time < 1) return message.reply("Veuillez entrer une valeur chiffrée et supérieur à 1 !")
let muterole = "793840735266013205"
che
if(User.roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
if(!message.author.roles.cache.has("783758067111428126" || "783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
if(User.roles.cache.has("783758067111428126" || "783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
let emb = new Discord.MessageEmbed()
.setTitle(Mute)
.setDescription(User.username + " a bien été mute par " + message.author.username + " pendant " + time[0] + " secondes pour la raison suivante : " + reason)
.setColor("#E74C3C")
pendant " + time[0] + " secondes pour la raison suivante : " + reason)
User.roles.add(muterole)
setTimeout(() => {
User.roles.remove(muterole)
let reply = new Discord.MessageEmbed()
.setDescription(User + " a bien été unmute !")
.setColor("#E74C3C")
message.guild.channels.cache.get("795063422386569298").send(reply)
let mp = new Discord.MessageEmbed()
.setDescription("Vous avez été unmute de " + guild)
.setColor("#E74C3C")
message.author.send(mp)
}, time[0] = 60000
)}
})
Don’t worry about French words.
Your code is not going to do what you want it to do, because you messed up some parts. User will be the first mentioned user that can be found in your arguments. So if you mention the user right at the first position of your arguments, it will be at index 0. That is because the arguments get stored in an array and arrays always starts at index 0. That means now your following arguments have to be at index 1 and 2. So you can change your time and reason into:
let time = message.content.split(" ").slice(1);
let reason = message.content.split(" ").slice(2).join(" ");
Make sure you use .join(" ") at your reason, that will allow you to add multiple words for the reason. The next mistake is in the if-statement where you ask if there is no reason. You create a new variable inside the statement, which makes no sense. You just have to do:
if(!reason){ reason = "aucune"; }
Now if there is no reason provided the reason will be aucune.
If you want to ask if a user has the mute role already, you can use a GuildMember Object. That would look like this:
if(message.guild.member(User).roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
After that if-statement you ask if a user has certain roles and if he don't has this roles, he has no permission. Something like that should always be the first line of code of such a command and it should look like this:
if(!message.author.roles.cache.has("783758067111428126") || !message.author.roles.cache.has("783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
The same procedure with the following if-statement:
if(User.roles.cache.has("783758067111428126") || User.roles.cache.has("783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
Then in your embed you are using time[0], although time is not an array. It just has to be time.
Your code should look like this now:
bot.on("message", async message => {
if(message.content.startsWith(prefix + "mute")){
if(!message.author.roles.cache.has("783758067111428126") || !message.author.roles.cache.has("783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
let User = message.mentions.users.first();
if(User.roles.cache.has("783758067111428126") || User.roles.cache.has("783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
let time = message.content.split(" ").slice(2)
let reason = message.content.split(" ").slice(3)
if(!reason){ reason = "aucune"; }
if(!time || !User) return message.reply("Veuillez entrer une commande valide !\n" + prefix + "mute #user <temps> <raison>")
let dUser = User.id
if(dUser == message.author.id) return message.reply("Vous ne pouvez pas vous mute vous même !")
if(isNaN(time) || time < 1) return message.reply("Veuillez entrer une valeur chiffrée et supérieur à 1 !")
let muterole = "793840735266013205"
if(message.guild.member(User).roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
let emb = new Discord.MessageEmbed()
.setTitle(Mute)
.setDescription(User.username + " a bien été mute par " + message.author.username + " pendant " + time + " secondes pour la raison suivante : " + reason)
.setColor("#E74C3C")
User.roles.add(muterole)
setTimeout(() => {
User.roles.remove(muterole)
let reply = new Discord.MessageEmbed()
.setDescription(User + " a bien été unmute !")
.setColor("#E74C3C")
message.guild.channels.cache.get("795063422386569298").send(reply)
let mp = new Discord.MessageEmbed()
.setDescription("Vous avez été unmute de " + message.guild)
.setColor("#E74C3C")
message.author.send(mp)
}, time
)}
})

ZAPIER CODE STEP HTTP REQUEST

I need generate the following request in zapier with a code step. I use webhook function but for some reason the answer is a separated comma value and i need the full json. I try in postman and works perfect. But i dont unterstand so fine how i can do with code. I use postman to format the code in nodejs the code run but dont geck back anything. Somebody can help so fin the problem? thans so much. (i´m a basic user for that reason i dont untersant all)
The request:
curl -X POST \
'https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2017-10-13&consumption_preferences=false&raw_scores=true' \
-H 'accept: application/json' \
-H 'accept-language: es' \
-H 'authorization: Basic here is the token' \
-H 'cache-control: no-cache' \
var http = require("https");
var options = {
"method": "POST",
"hostname": "gateway.watsonplatform.net",
"port": null,
"path": "/personality-insights/api/v3/profile?version=2017-10-13&consumption_preferences=false&raw_scores=false",
"headers": {
"content-type": "application/json",
"accept": "application/json",
"authorization": "Basic HEREISTHETOKEN==",
"accept-language": "es",
"cache-control": "no-cache",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(JSON.stringify({ contentItems:
[ { content: 'Wow, I liked #TheRock before, nowLa evaluada aseguró que no adulteró, falsificó u omitió intencionalmente alguna información en su solicitud de empleo, dice que toda la información suministrada en este proceso de selección es completamente legal y en cualquier momento se puede validar. I really SEE how special he is. The daughterIndicó que consume licor solo en ocasiones especiales, las bebidas que acostumbra a consumir son: cerveza, teniendo un consumo máximo por ocasión de 5 cervezas. Aseguró no haber tenido dependencia de las sustancias alcohólicas e indicó no tener antecedentes de alcoholismo en la familia. Agregó no haber tenido incumplimientos o problemas laborales a causa del licor. story was IT for me. So great! #MasterClass So great! #MasterClasWow, I liked #TheRock before, nowLa evaluada aseguró que no adulteró, falsificó u omitió intencionalmente alguna información en su solicitud de empleo, dice que toda la información suministrada en este proceso de selección es completamente legal y en cualquier momento se puede validar. I really SEE how special he is. The daughterIndicó que consume licor solo en ocasiones especiales, las bebidas que acostumbra a consumir son: cerveza, teniendo un consumo máximo por ocasión de 5 cervezas. Aseguró no haber tenido dependencia de las sustancias alcohólicas e indicó no tener antecedentes de alcoholismo en la familia. Agregó no haber tenido incumplimientos o problemas laborales a causa del licor. story was IT for me. So great! #MasterClasss',
contenttype: 'text/plain',
created: 1447639154000,
id: '666073008692314113',
language: 'es' } ] }));
req.end();
return {DATA: http.text};

Datatables change interface language

I am currently using angular-datatables.
How can I see the interface of the table in other languages?
I mean the "Show entries", "Search:", "Showing 1 to 10 of 20 entries" literals fore example in Spanish.
You need to define a language struct like this (danish implementation, what I am using in my angular-datatables apps) :
var language = {
"sEmptyTable": "Ingen tilgængelige data (prøv en anden søgning)",
"sInfo": "Viser _START_ til _END_ af _TOTAL_ rækker",
"sInfoEmpty": "Viser 0 til 0 af 0 rækker",
"sInfoFiltered": "(filtreret ud af _MAX_ rækker ialt)",
"sInfoPostFix": "",
"sInfoThousands": ",",
"sLengthMenu": "Vis _MENU_ rækker",
"sLoadingRecords": "Henter data...",
"sProcessing": "Processing...",
"sSearch": "Filter:",
"sZeroRecords": "Ingen rækker matchede filter",
"oPaginate": {
"sFirst": "Første",
"sLast": "Sidste",
"sNext": "Næste",
"sPrevious": "Forrige"
},
"oAria": {
"sSortAscending": ": activate to sort column ascending",
"sSortDescending": ": activate to sort column descending"
}
}
There is a bunch of languages here -> https://www.datatables.net/plug-ins/i18n/
And then you include the language using the withLanguage() option method
.withLanguage(language)
demo -> http://plnkr.co/edit/RCrqM3z7qwsUfFwy8HE6?p=preview
I created a .ts file like this:
export class LanguageApp {
public static spanish_datatables = {
processing: "Procesando...",
search: "Buscar:",
lengthMenu: "Mostrar _MENU_ &elementos",
info: "Mostrando desde _START_ al _END_ de _TOTAL_ elementos",
infoEmpty: "Mostrando ningún elemento.",
infoFiltered: "(filtrado _MAX_ elementos total)",
infoPostFix: "",
loadingRecords: "Cargando registros...",
zeroRecords: "No se encontraron registros",
emptyTable: "No hay datos disponibles en la tabla",
paginate: {
first: "Primero",
previous: "Anterior",
next: "Siguiente",
last: "Último"
},
aria: {
sortAscending: ": Activar para ordenar la tabla en orden ascendente",
sortDescending: ": Activar para ordenar la tabla en orden descendente"
}
}
}
Then in the component that was loading the DataTable just put that config inside dtOptions:
this.dtOptions = {
language: LanguageApp.spanish_datatables
};
In Angular2+ what worked for me is quite the same as mentioned by #davidkonrad, but without the starting letters (s and o), and adding the language as an attribute of the dtOptions. I.e.:
this.dtOptions = {
pagingType: 'full_numbers',
pageLength: 10,
dom: 'Bfrtip',
buttons: [
/*'print',
'csv'*/
],
responsive: true,
/* below is the relevant part, e.g. translated to spanish */
language: {
processing: "Procesando...",
search: "Buscar:",
lengthMenu: "Mostrar _MENU_ éléments",
info: "Mostrando desde _START_ al _END_ de _TOTAL_ elementos",
infoEmpty: "Mostrando ningún elemento.",
infoFiltered: "(filtrado _MAX_ elementos total)",
infoPostFix: "",
loadingRecords: "Cargando registros...",
zeroRecords: "No se encontraron registros",
emptyTable: "No hay datos disponibles en la tabla",
paginate: {
first: "Primero",
previous: "Anterior",
next: "Siguiente",
last: "Último"
},
aria: {
sortAscending: ": Activar para ordenar la tabla en orden ascendente",
sortDescending: ": Activar para ordenar la tabla en orden descendente"
}
}
};

Get an array dynamicaly from a factory

I'm trying to get information from a factory and trying to print it dynamic.
Before I did it like this:
<div class="articlePage">
<h4> {{ posts[0].title }} </h4> <span style="color: #666;"> {{ posts[0].date }} </span>
<p> {{ posts[0].text }} </p> {{id}}
</div>
But now I said "[0]" so I asked only the first one in the array but from now on it is one page so it need to dynamic.
On my home page I have many posts and when I click on one I want to read the full post on a specific page.
This is how my factory looks like:
App.factory('PostsService', [function () {
var postsService = {};
var _posts = [{
id: 00,
title: 'Kabinet in hoger beroep tegen klimaatvonnis',
text: 'Dat bevestigen Haagse bronnen na berichtgeving in dagblad Trouw. Het kabinet zegt tegelijkertijd wel bereid te zijn om extra maatregelen te nemen om de uitstoot van broeikasgassen terug te dringen. Staatssecretaris Mansveld van Milieu maakt naar verluidt dinsdagmiddag bekend hoe het kabinet dat wil doen. De zaak tegen de overheid werd aangespannen door actiegroep Urgenda en negenhonderd klagers. Die stelden dat de Staat zich meer moet inspannen om de CO2-uitstoot in Nederland terug te dringen.',
date: '28 september 2015'
},
{
id: 01,
title: '\'Leraren kritisch over passend onderwijs\'',
text: 'Dat blijkt uit onderzoek van het AD en Duo Onderwijsonderzoek. Door passend onderwijs kunnen leerlingen die meer hulp nodig hebben, vaker terecht in het reguliere onderwijs. Bijna de helft van docenten (47 procent) in het voorgezet onderwijs zegt echter te weinig tijd te hebben om dergelijke jongeren goed te helpen. In het basisonderwijs is dat zelfs 84 procent. Extra handen in de klas staan dan ook op het verlanglijstje van vrijwel alle docenten in het voortgezet onderwijs (84 procent) en het basisonderwijs (99 procent). Ook zegt 98 procent van de leraren op de middelbare school behoefte te hebben aan kleinere klassen, tegenover ongeveer 95 procent van hun collega\'s in het basisonderwijs. Het onderzoek werd uitgevoerd onder 1668 onderwijsmedewerkers, zoals leraren, directeuren en zorgcoördinatoren.',
date: '15 januari 2015'
},
{
id: 02,
title: 'Premier Curaçao dient ontslag in',
text: 'De partij van Asjes, Pueblo Soberano (PS), had eerder op de dag het vertrouwen in de minister-president opgezegd. De partij heeft niet bekendgemaakt waarom het vertrouwen in de premier is opgezegd, maar de PS-fractie botste de afgelopen maanden een aantal keer openlijk met Asjes over verschillende beleidskwesties. Het vertrek van Asjes leidt niet direct tot de val van het kabinet. Een van de meningsverschillen draaide om de steun die de premier bleef geven aan de gevolmachtigde minister van Curaçao in Nederland, Marvelyne Wiels. Zij ligt zwaar onder vuur na het verschijnen van een kritisch rapport van de Curaçaose Ombudsman over haar functioneren. De fractie zou haar niet meer willen steunen. Minister van Volksgezondheid Ben Whiteman is maandagavond door de gouverneur gevraagd de functie van minister-president waar te nemen voor een periode van drie maanden. Whiteman heeft de functie geaccepteerd. Hij zei tegen de pers de gang van zaken rond het vertrek van Asjes te betreuren.',
date: '31 augustus 2015'
},
{
id: 03,
title: 'Asscher heeft nog geen akkoord met Marokko over uitkeringen',
text: 'Desondanks hoopt de bewindsman nog steeds tot een akkoord te komen, schrijft hij dinsdag aan de Tweede Kamer. Het socialezekerheidsverdrag regelt de uitbetaling van Nederlandse uitkeringen voor Marokkaanse-Nederlanders in Marokko. Asscher wil die uitkeringen aanpassen aan het levenspeil in Marokko en dus verlagen. De regering in Rabat voelt hier echter niets voor. Het is de tweede keer dat Asscher moet meldden dat hij niet tot een akkoord is gekomen. Eerder hoopte hij er al op 15 juni uit te zijn. Later verschoof die datum naar 1 september. In de afgelopen periode is intensief overleg gevoerd met Marokko. Tot op heden heeft dit echter nog niet geresulteerd in een akkoord, aldus Asscher. Een nieuwe datum voor een mogelijk akkoord noemt hij niet. Vooral regeringspartij VVD heeft zich hard gemaakt voor aanpassing van het socialezekerheidsverdrag. De Tweede Kamer nam vorig jaar een VVD-motie aan waarin stond dat het verdrag moest worden opgezegd als de onderhandelingen niet snel vruchten zouden afwerpen.',
date: '02 april 2015'
}
];
postsService.posts = _posts;
return postsService;
}
I hope you understand my problem if you don't ask something that you need to know I hope that you can help me.
Updated Answer
HTML
<div ng-controller="myCtrl">
<div >Post</div>
<div ng-repeat="post in posts | filter:filters">
<h4 ng-click="filters.id = post.id"> {{ post.title }}</h4>
<span style="color: #666;"> {{ post.date }} </span>
<p> {{ post.text }} </p>
</div>
<div ng-click="filters.id = ''" ng-if="filters.id == ''">Go Back</div>
</div>
Controller
app.controller("myCtrl" , function($scope,PostsService) {
$scope.posts = PostsService.posts;
$scope.filters = {};
});
Refer plunker.
Explaination
Click on the header of the post and then only that post is visible and then a 'Go Back' button is visible to go back to all post page.
The handling is done using a filters object which filter only that post on which the click is performed.

Cakephp Data validation - This field cannot be left blank

I'm using cakephp and I get a strange behavior with it.
Here is my validation rule in the Model:
public $validate = array(
'flyer' => array(
'rule' => array('fileValidation', 'flyer', array('image/jpeg', 'image/pjpeg'), NULL, TRUE)
)
// Other rules...
);
Here is the fileValidation method (yes I'm french =) )
public function fileValidation(array $check, $field, array $allowedMimeTypes = NULL, $maxFileSize = NULL, $allowEmpty = FALSE)
{
$file = array_shift($check);
$message = NULL;
if($file['error'] === UPLOAD_ERR_OK){
// checking uploaded file
if(empty($file['tmp_name']) || empty($file['tmp_name']) || $file['tmp_name'] === 'none' || !is_uploaded_file($file['tmp_name'])){
$message = "Une erreur est survenue lors de l'envoi du fichier, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
// checking mimeTypes if required
elseif(!empty($allowedMimeTypes) && !in_array($file['type'], $allowedMimeTypes)){
$message = "Le type de fichier envoyé n'est pas celui attendu.";
}
// checking file size if required
elseif(!empty($maxFileSize) && $file['size'] > $maxFileSize){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
else{
return TRUE;
}
}
elseif($file['error'] === UPLOAD_ERR_NO_FILE){
// validates if no upload is allowed
if(!$allowEmpty){
$message = "Une erreur est survenue lors de l'envoi du fichier, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
else{
return TRUE;
}
}
elseif($file['error'] === UPLOAD_ERR_INI_SIZE){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
elseif($file['error'] === UPLOAD_ERR_FORM_SIZE){
$message = "Le fichier envoyé est trop volumineux, réduisez sa taille et réessayez.";
}
elseif($file['error'] === UPLOAD_ERR_PARTIAL){
$message = "Une erreur est survenue lors de l'envoi du fichier, le serveur n'a reçu qu'une partie du fichier, veuillez réessayer à nouveau.";
}
elseif($file['error'] >= UPLOAD_ERR_NO_TMP_DIR){
$message = "Une erreur interne est survenue, veuillez réessayer à nouveau. Si le problème persiste, merci de contacter le support technique.";
}
// Here is the problem
$this->validationErrors[$field][] = $message;
return FALSE;
}
So far so good, my Validation rule seems to work correctly but when à get an error, I have two messages: "My custom message" and "This file cannot be left blank".
How to remove this message, where am I wrong?
Thanks in advance.
May be it will works for you
$this->validationErrors[$field][] = $message; // comment this Line
return FALSE // comment this Line
And Add the following line at last of your fileValidation function
return implode("\n", $message);
Cakephp.Saint's solution doesn't work because $message is a string, not an array but this works fine:
return $message;

Resources