#StackBounty: #javascript #jquery Running a jQuery function multiple times sequentially (for a Bookmarklet)

Bounty: 50

I’ve got the following jQuery code which I use in a Bookmarklet. It clicks on all the buttons on the page (with the class “Unfollow”) one by one, with a random time between each one…

javascript: (function() {
    var unfollowButtons = $('button.Unfollow');
    var index = unfollowButtons.length - 1;
    unfollow();

    function unfollow() {
        if (index >= 0) {
            $(unfollowButtons[index--])
                .click();
            setTimeout(unfollow, Math.floor((Math.random() * 1000) + 500));
        }
    }
})();

I’d like to run the above function again twice once it has completed its cycle.

Just running the function again causes that to run in parallel with the first function call.

How do I run the unfollow() function 2 or 3 times without them all running in parallel?


Get this bounty!!!

#StackBounty: #javascript #stackexchange #chat #userscript Onebox hider for Stack Exchange chat

Bounty: 50

I sometimes don’t like to look at images in chat. When they’re just a URL then I’m fine, as then I have the choice to look at the image or not, and blends in with the other text. Therefore, I decided to make a onebox hider for chat. It hides the onebox, and adds onebox: <link> before the onebox, with the ability to click the ‘onebox’ text, to show or hide the onebox.

There, however, are some allowed oneboxes such as SE blog posts, SE post and Twitter links. This is as they don’t normally have images, which I think is ok. These are stored in allowed_oneboxes, so that if another user wants, they can add or remove allowed oneboxes with ease.

I looked through “Desktop Notifications for flags and queue items” and added some of the recommendations as I had problems with jQuery and wanted to make sure my environment was at least somewhat well setup.

When I started to write this question I was also notified about Badge Oneboxer for Chat.SE, where I found out about MutationObserver, which was better than what I was doing with setInterval.

I’ve tried to make this as clean as possible. However, as I’ve not done too much with Greasemonkey and JavaScript, I’d like to make sure I’ve kept everything clean and correct.

/** @preserve
// ==UserScript==
// @name        Onebox Hider
// @namespace   
// @description Hides oneboxes from SE chat.
// @author      Peilonrayz
// @version     0.0.1
// @copyright   2017, Peilonrayz
// @license     MIT; https://opensource.org/licenses/MIT
// @require     https://code.jquery.com/jquery-3.2.1.min.js
// @match       *://chat.stackexchange.com/*
// @match       *://chat.stackoverflow.com/rooms/*
// @match       *://chat.meta.stackexchange.com/rooms/*
// @grant       none
// ==/UserScript==
*/

// Copyright 2017 Peilonrayz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

"use strict";

(function (window, undefined) {
window.$.noConflict();
(function ($) {


var allowed_oneboxes = ['ob-post', 'ob-blog', 'ob-tweet'];

function change_onebox(onebox) {
    var href = onebox.find('a')[0].href;
    var show = onebox
        .hide()
        .before('
onebox: '+href+'
') .prev() .find('span') .click(() => onebox.toggle()); return onebox; } function flatten(arrayOfArrays) { return Array.concat.apply([], arrayOfArrays); } function toArray(it) { return Array.slice(it); } function update_oneboxes(mutations) { var msgs; if (mutations == undefined) { msgs = $('.message .content .onebox'); } else { msgs = $(flatten(mutations.map(m => toArray(m.addedNodes)))) .find('.onebox'); } msgs.map((i, onebox) => $(onebox)) .filter((i, onebox) => !onebox.prev().hasClass('onebox-toggle')) .filter((i, onebox) => !allowed_oneboxes.some(c => onebox.hasClass(c))) .map((i, onebox) => change_onebox(onebox)); } new MutationObserver(update_oneboxes) .observe(document.getElementById('chat'), {childList: true}); })(window.jQuery); })(Function("return this")());


Get this bounty!!!

#StackBounty: #javascript #node.js #firebase #google-cloud-platform #google-cloud-storage Why is my solution so slow and how can I impr…

Bounty: 100

Currently I was able to optimise performance quite a bit, but it is still somewhat slow :/

LATEST EDIT:

My current solution (the fastest atm (but still slow) and keeps order):

server

router.post('/images', function(req, res, next) {
    var image = bucket.file(req.body.image);
    image.download(function(err, contents) {
        if (err) {
            console.log(err);
        } else {
            var resultImage = base64_encode(contents);
            var index = req.body.index;
            var returnObject = {
                image: resultImage,
                index: index
            }
            res.send(returnObject);
        }
    });
});

client query

$scope.getDataset = function() {

                fb.orderByChild('id').startAt(_start).limitToFirst(_n).once("value", function(dataSnapshot) {

                    dataSnapshot.forEach(function(childDataSnapshot) {
                        _start = childDataSnapshot.child("id").val() + 1;

                        var post = childDataSnapshot.val();
                        var image = post.image;

                        var imageObject = {
                            image: image,
                            index: position
                        };
                        position++;
                        $.ajax({
                            type: "POST",
                            url: "images",
                            data: imageObject,
                        }).done(function(result) {
                            post.image = result.image;
                            $scope.data[result.index] = post;
                            $scope.$apply();
                            firstElementsLoaded = true; 
                        });
                    })  
                });
            };

client HTML

{{d.title}} by {{d.username}}

-50}}">
{{d.upvotes - d.downvotes}} HP
</div> </div> </div>


Get this bounty!!!

#StackBounty: #javascript #object #inheritance Update an instance's property, from another instance

Bounty: 50

I’m looking for the best way to update in object instance, for the example in this case first‘s name property. The only way I understand to achieve this would be to pass reference to the object instance as a parameter into either the new mySecondObj(first) constructor, or a method of the second instance like so second.update(first).

function myFirstObj(){
    this.name = 'jordan';
}
function mySecondObj(firstObj){
    this.firstObj = firstObj;
    this.update=()=>{
        this.firstObj.name = 'john';
    };
}
var init=()=>{
     var first = new myFirstObj();
     var second = new mySecondObj(first);
     second.update();
}
document.addEventListener('DOMContentLoaded',init);

Question: Is there any way to pass the first instance to the second instance so that it can manipulate the first‘s properties, other then new mySecondObj(first) or second.update(first)?


Get this bounty!!!

#StackBounty: #javascript #regex Basic JavaScript template engine using replace, match and RegExp

Bounty: 50

To practice with regular expressions, I wrote this basic template engine in JavaScript in addition to a simple test case to make sure it works correctly.

I am wondering if there is any improvements I can do or if I am correctly following JavaScript coding style and conventions. Thanks in advance.

In short,

  1. {{= expression}} –> evaluates expression (context is optional)
  2. {{0}} –> evaluates based on given array index
  3. {{name}} –> evaluates based on given json values

Template code (does not require any dependency):

(function() {
    this.amirTemplateEngine = function() {
        var self = this;
        var _tokensToReplace, _values, _array;

        // evaluate in-line expressions
        self.evaluateString = function(string, options) {
            _tokensToReplace = string.match(new RegExp(/({{=[^}]*}})/g)) || [];

            _tokensToReplace.map(function(token) {
                string = string.replace(token, (function() {
                    return eval(token.replace("{{=", "").replace("}}", ""));
                }).call(options && options.context ? options.context : self));
            });

            return string;
        };

        // replace given object
        self.replaceGivenObject = function(string, options) {
            _values = options && options.values ? options.values : {};
            _tokensToReplace = string.match(new RegExp(/({{[ ]*[^}.]+[ ]*}})/g)) || [];

            _tokensToReplace.map(function(token) {
                string = string.replace(token, _values[token.replace(" ", "").replace("{{", "").replace("}}", "")]);
            });

            return string;
        };

        // replace given array index
        self.replaceGivenArray = function(string, options) {
            _array = options && options.array ? options.array : {};
            _tokensToReplace = string.match(new RegExp(/({{[ ]*[0-9]+[ ]*}})/g)) || [];

            _tokensToReplace.map(function(token) {
                string = string.replace(token, _array[parseInt(token.replace(" ", "").replace("{{", "").replace("}}", ""))]);
            });

            return string;
        };

        // helper function
        self.format = function(string, options) {
            // evaluate expressions
            string = self.evaluateString(string, options);

            // if options.array is defined, then evaluate template
            string = self.replaceGivenArray(string, options);

            // if options.values is defined, then evaluate template
            string = self.replaceGivenObject(string, options);

            return string;
        };

        // for chainability
        return self;
    };
})();

Testing the code (making sure output is correct):

var template = require('./amir-template-engine');

(function() {
    var self = this;
    something = "something else!";
    var template = "
                    <h2 class='{{= (true).toString()}}'>{{0}} {{1}} {{2}}</h2>
                    <p>{{= 4 > 0 ? 'good' : 'bad'}}</p>
                    <p>{{= something }}</p>
                    <p>{{name}}</p>
                ";

    var result = "
                    <h2 class='true'>seyed amir hossein</h2>
                    <p>good</p>
                    <p>something else!</p>
                    <p>amir</p>
                ";

    var templateObj = new amirTemplateEngine();

    testResult = templateObj.format(template, {
        array: ["seyed", "amir", "hossein"],
        values: {
            name: "amir"
        },
        context: self
    }) == result;

    console.log("Test is" + (testResult ? "" : " NOT") + " passing!");
})();

Link to GitHub repository


Get this bounty!!!

#StackBounty: #javascript #reactjs #bpmn.io Integrating bpmn-js to modeler the react component

Bounty: 100

I have been trying to integrate the bpmn-js modeler to the react component, but has been unable to get any result. Can anyone help me with there code? All the requirement have already done. It would be very much helpful for me. Thanks


Get this bounty!!!

#StackBounty: #7 #forms #javascript #ajax Ajax callback of select form field not triggered when changed by javascript, only when change…

Bounty: 50

I have a simple ajax form with select form input:

$form['children']['number_children'] = array(
  '#title' => t('Počet detí'),
  '#type' => 'select',
  '#options' => range(0, 15),
  '#default_value' => $number_children,
  '#ajax' => array(
    'callback' => 'ajax_callback_registration_children',
    'wrapper' => 'children-div',
    'method' => 'replace',
    'effect' => 'fade',
  ),
);

When the select input is changed manually it properly executes an ajax and appends new inputs into the form. But I need to trigger the ajax callback by javasrcipt code that is changing the selected option:

$('#children-div select[name="number_children"]').val('3').change();

This changes the value, but the ajax is not triggered at all. Why is it not working and is there something I could do?


Get this bounty!!!

#StackBounty: #javascript #typescript #screenshot #nightmare Nightmare.js screenshot buffer length 0

Bounty: 50

I’m running a nightmare.js script where where I’m trying to take a screenshot of multiple elements on a page.

The first element is captured just fine, but every other element that is below the fold is captured with a zero length. I am struggling to debug this issue. Any help would be incredibly appreciated.

Basically this script walks through a page and selects all the elements on the page that match a selector. Then, using async it collects the responses and returns a buffer of objects. The issue is that the elements below the fold do not get screenshotted (buffer length ends up at zero). I tried to wait() and scroll to the element, but I have not had any success as of yet.

import * as Nightmare from 'nightmare'
import * as vo from 'vo'
import * as async from 'async'
import * as fs from 'fs'

const urls:String[] = [
  'https://yahoo.com/'
]


Nightmare.action('snap', function(selector:String, done:Function) {
  const self = this;

  this.evaluate_now(function (selector) {
    return Array.from(document.querySelectorAll(selector))
    .map((ele:Element) => {
      if (ele) {
        const rect = ele.getBoundingClientRect()
        const r:Function = Math.round
        return {
          x: r(rect.left),
          y: r(rect.top),
          width: r(rect.width),
          height: r(rect.height)
        }
      }
    })
  }, function(err, clips) {
    if (err) return done(err)
    if (!clips) return done(new Error(`Selector not found`))
    let snaps = []
    const snap = (clip, cb) => {
      self
        .scrollTo(clip.y - clip.height, clip.x)
        .screenshot(clip, cb)
        .run()
    }
    async.mapSeries(clips.reverse(), snap, (err, res) => {
      done(err, res)
    })
  }, selector)
})

const scrape = (url) => {
  const nightmare = Nightmare({
    show: true
  });
  nightmare
    .goto(url)
    .snap('.navbar')
    .end()
    .then((buffers:Buffer[]) => {
      buffers.forEach((data, index) => {
        fs.writeFileSync(`images/navbar-${index}.png`, data)
      })
    })
}

urls.forEach(scrape)


Get this bounty!!!

#StackBounty: #7 #views #forms #javascript #ajax Attach or embed node add form to a view

Bounty: 50

I want to attach or embed a node form to a view so that when a user submits the form, the view below the form will be updated in realtime via ajax. The form will be shown above the view. My views block name is Statuses Stream.

I tried formblock module and putting the form in the header section of my view using views ui, but after submit, it was redirecting to the node created page.

Then I tried Advanced Form Block module. I created a form using AFB module. It is submitting the form with ajax, but it is not updating the view in the realtime.

I have just tried the Ajax Form Entity module. It is submitting and updating via ajax, but I cannot find a way to attach a view with it. However, in its settings, I can select a view mode. I need a little more flexibility.

How to Attach or embed node form to a view so that it submits via ajax and updates the view in realtime? I am open to any solution programmatically or through a module. Better if done programmatically because it will give more flexibility.

Just as an extra note, I am trying to mimic the statuses module. It does exactly what I am looking for. The problem is that it is not an entity. So now I am trying to make the same functionality with Content type.


Get this bounty!!!

#StackBounty: #javascript #svg #twitter #oauth #sharing Share Image to Twitter without Card

Bounty: 50

Given an image at a certain address, http://www.thissite.will/never/be-finished.png, what’s the easiest way to share it to Twitter, preferably without a card?


Users customize an SVG, and when they’re satisfied, I convert it to a PNG and store it on my server.

I want to give them the option of sharing the image on Twitter. They click on a button (which I can implement), and a dialog box opens, where they can add to the tweet (which should already contain the picture).

I know similar questions have been asked on this site before, but I do not want to use a “card” to share the image. Instead, I want a typical, non-card Tweet, just with an image (like this).

I’ve looked through the Twitter Developer Documentation repeatedly, but I can’t find helpful information. The POST statuses/update_with_media method is deprecated, and the link to the “Uploading Media Guide,” a suggested replacement, is broken. This guide, I assume, is what it intended to link to, but it has no JavaScript code to suggest how this should actually be implemented.

Please help.


My attempt, based off of POST media/upload:

$.ajax({
    url: "https://upload.twitter.com/1.1/media/upload.json", 
    format: "post", 
    data: {"data" : link}
}).success(function(response) {
    console.log(":)");
    console.log(response);
}).fail(function(response) {
    console.log(":(");
    console.log(response.responseText);
});

This fails. The responseText is {"errors":[{"code":215,"message":"Bad Authentication data."}]}.


Basically, I want to do something similar to what StackOverflow does. When you click “share” on a question, then select Twitter, a new window pops up populated with a link to the question and where users can write their own message.

In my case, however, when the tweet is sent, rather then there being a link back to the page and some text pulled from it, I’d like to have just an image.


Get this bounty!!!