Used to allow performing API requests in parallal instead of series
971241
def concurrent_map
      threads = services.map{|s| Thread.new{ yield s } }
      threads.each(&:join)
      threads.map(&:value)
    end
518419
def _map_player_request_to_func(self, player_request_type):
        """"""
        # calbacks for on_playback requests are optional
        view_func = self._intent_view_funcs.get(player_request_type, lambda: None)

        argspec = inspect.getargspec(view_func)
        arg_names = argspec.args
        arg_values = self._map_params_to_view_args(player_request_type, arg_names)

        return partial(view_func, *arg_values)
186382
def _request(self):
        
        caller_frame = inspect.getouterframes(inspect.currentframe())[1]
        args, _, _, values = inspect.getargvalues(caller_frame[0])
        caller_name = caller_frame[3]
        kwargs = {arg: values[arg] for arg in args if arg != 'self'}
        func = reduce(
            lambda resource, name: resource.__getattr__(name),
            self.mappings[caller_name].split('.'), self)
        return func(**kwargs)
788075
function(seriesCallback) {
                if(!obtainDates) {
                    seriesCallback();
                    return;
                }

                getDatesForPinsFromScraping(pinsThatNeedScrapedDates, null, function (pinDateMap) {
                    for (var i = 0; i < allPinsData.length; i++) {
                        if (allPinsData[i].created_at == null && pinDateMap[allPinsData[i].id] && pinDateMap[allPinsData[i].id].date) {
                            allPinsData[i].created_at = pinDateMap[allPinsData[i].id].date;
                            allPinsData[i].created_at_source = pinDateMap[allPinsData[i].id].source;
                        }
                    }
                    seriesCallback();
                    return;
                });
            }
394523
function (callback) {
        self.client.query(sql, function (err, result) {
          if (err) {
            if (err.indexOf('Couldn\'t find series: ') > -1)
              result = []; //allow this error to fly
            else
              return callback(err);
          }

          results.push(result);
          return callback(null);
        });
      }
682214
function makeApiUrl(options,parameters) {

    var query = parameters;

    //
    // If any parameter given in array, make it string separated by semicolon(;)
    //
    for(let key in query){
        if( _.isArray(query[key]) ){
            query[key] = _.join(query[key],';');
        }
    }

    let curTime = Math.floor(Date.now() / 1000);
    let randomToken = randomstring.generate(6);

    query.time = curTime;
    query.apiKey  = options.API_KEY;

    //
    // Sort parameters according to codeforces API rules
    //
    query = _
        .chain(query)
        .map( (value, key) => {
            return { key, value };
        })
        .orderBy(['key', 'value'], ['desc', 'desc'])
        .reverse()
        .keyBy('key')
        .mapValues('value')
        .value();

    let qsFy = qs.stringify(query,{ encode: false });
    let apiSig = `${randomToken}/${options.method}?${qsFy}#${options.API_SECRET}`;

    apiSig = sha512(apiSig).toString();
    query.apiSig = randomToken + apiSig;
    qsFy = qs.stringify(query,{ encode: false });

    let url = `${options.API_URL}/${options.method}?${qsFy}`;

    return url;
}
319957
function processJson (json) {
                        if (json.length != 1) {
                            renderContext.renderErrors[graph.id] = "TSDB results doesn't contain exactly 1 metric, was "+json.length;
                            renderContext.renderMessages[graph.id] = "";
                            return;
                        }

                        var series = json[0];

                        if (heatmapOptions.excludeNegative) {
                            for (var i=0; i<series.dps.length; i++) {
                                if (series.dps[i][1] < 0) {
                                    series.dps[i][1] = 0;
                                }
                            }
                        }

                        var isFilteredOutFn = function(value) {
                            return false;
                        }
                        var tsdbLinkRangeLower = "";
                        var tsdbLinkRangeUpper = "";
                        if ((heatmapOptions.filterLowerBound != null && heatmapOptions.filterLowerBound != "") || (heatmapOptions.filterUpperBound != null && heatmapOptions.filterUpperBound != "")) {
                            if (heatmapOptions.filterUpperBound == null || heatmapOptions.filterUpperBound == "") {
                                try {
                                    var lower = parseInt(heatmapOptions.filterLowerBound);
                                    tsdbLinkRangeLower = lower;
                                    isFilteredOutFn = function(value) {
                                        return value < lower
                                    };
                                }
                                catch (e) {
                                    // ignore
                                }
                            }
                            else if (heatmapOptions.filterLowerBound == null || heatmapOptions.filterLowerBound == "") {
                                try {
                                    var upper = parseInt(heatmapOptions.filterUpperBound);
                                    tsdbLinkRangeUpper = upper;
                                    isFilteredOutFn = function(value) {
                                        return value > upper
                                    };
                                }
                                catch (e) {
                                    // ignore
                                }
                            }
                            else {
                                try {
                                    var lower = parseInt(heatmapOptions.filterLowerBound);
                                    var upper = parseInt(heatmapOptions.filterUpperBound);
                                    tsdbLinkRangeLower = lower;
                                    tsdbLinkRangeUpper = upper;
                                    isFilteredOutFn = function(value) {
                                        return value < lower || value > upper
                                    };
                                }
                                catch (e) {
                                    // ignore
                                }
                            }
                        }

                        // remove old heatmaps..
                        d3.select(divSelector)
                            .selectAll("svg")
                            .remove();

                        var heatmap = renderer.heatmap()
                            .cellSize(cellSize)
                            .scale(d3.scale.quantize())
                            .dps(series.dps)
                            .width(width)
                            .height(height)
                            .colourScheme(heatmapOptions.colourScheme);

                        if (style == "week_day") {
                            heatmap.weekDayRender(divSelector, fromYear, toYear, isFilteredOutFn);
                        }
                        else if (style == "day_hour") {
                            heatmap.dayHourRender(divSelector, fromMonth, toMonth, isFilteredOutFn);
                        }

                        if (heatmapOptions.excludeNegative && true && (tsdbLinkRangeLower == "" || tsdbLinkRangeLower < 0)) {
                            tsdbLinkRangeLower = 0;
                        }
                        var yAxisParams = {
                            range: "[" + tsdbLinkRangeLower + ":" + tsdbLinkRangeUpper + "]"
                        };
                        ret.tsdb_export_link = graphServices.tsdbGraphUrl("/#", renderContext, config, global, graph, queries, "x1y1", downsampleOverrideFn, yAxisParams, /*y2AxisParams*/null, /*keyParams*/{}, /*lineSmoothing*/false, /*style*/null, /*globalAnnotations*/false);
                        renderContext.renderMessages[graph.id] = "";
                        renderContext.graphRendered(graph.id);
                        return;
                    }
605516
private ApiListType executeRequest(Call call) throws IOException, ApiException {
    return client.handleResponse(call.execute(), listType);
  }
1016362
def api_request(request, *args, **kwargs):
    
    plugin = pm.api_plugin_for_request(request)
    if plugin and plugin.request_class:
        req = plugin.request_class(*args, **kwargs)
    else:
        raise Exception("Invalid request type")
    return req
1112333
def wrap_requests(requests_func):
    """"""
    def call(url, *args, **kwargs):
        blacklist_hostnames = execution_context.get_opencensus_attr(
            'blacklist_hostnames')
        parsed_url = urlparse(url)
        if parsed_url.port is None:
            dest_url = parsed_url.hostname
        else:
            dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
        if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
            return requests_func(url, *args, **kwargs)

        _tracer = execution_context.get_opencensus_tracer()
        _span = _tracer.start_span()
        _span.name = '[requests]{}'.format(requests_func.__name__)
        _span.span_kind = span_module.SpanKind.CLIENT

        # Add the requests url to attributes
        _tracer.add_attribute_to_current_span(HTTP_URL, url)

        result = requests_func(url, *args, **kwargs)

        # Add the status code to attributes
        _tracer.add_attribute_to_current_span(
            HTTP_STATUS_CODE, str(result.status_code))

        _tracer.end_span()
        return result

    return call
50991
function p() {

    // global promise object to wait for all plot options to be completed before writing
    this.promises = [];
    // global array for options to plot
    this.optArray = [];

    // simple plot
    this.plot = function(seriesArr, title, yLabel, xLabel) {
        // console.log("plotting")
        var defer = q.defer();
        this.promises.push(defer.promise);

        title = title || false;
        yLabel = yLabel || false;
        xLabel = xLabel || false;

        var opt = _.cloneDeep(tmpOpt),
        set = _.set.bind(null, opt);

        set('series', seriesArr);
        set('title.text', title);
        set('yAxis.title.text', yLabel);
        set('xAxis.title.text', xLabel);

        // setTimeout(function() {}, 2000);
        this.optArray.push(opt);
        defer.resolve();
        return opt;
    };

    // advance plot = specify your own highcharts options
    this.advPlot = function(opt) {
        var defer = q.defer();
        this.promises.push(defer.promise);
        this.optArray.push(opt);
        defer.resolve();

        return opt;
    };

    // write highchart options to json for rendering
    // if autosave is true, charts will save on view
    this.write = function(autosave) {
        var defer = q.defer();
        for (var i = 0; i < this.optArray.length; i++) {
            _.set(this.optArray[i], 'chart.renderTo', 'hchart' + i);
            _.set(this.optArray[i], 'autosave', autosave);
        }
        fs.writeFile(__dirname + '/src/options.json', JSON.stringify(this.optArray), defer.resolve);

        return defer.promise;
    };

    // serialize optArray and write to
    this.serialize = function(autosave) {
        var defer = q.defer();

        q.all(this.promises)
        .then(this.write(autosave))
        .then(defer.resolve());

        return defer.promise;
    };

    // finally, render after all plots specified
    // if autosave is true, charts will save on view
    this.render = function(autosave) {
        var gulpplot = require(__dirname + '/../gulpfile.js').gulpplot;
        
        this.serialize(autosave)
        .then(gulpplot)
    };

    this.dynrender = function() {
        this.serialize()
        // .then(dyngulpplot)
    };
}
372843
function setParallaxTransform(el, progress) {
            el = $(el);
            var p, pX, pY;
            var rtlFactor = s.rtl ? -1 : 1;
        
            p = el.attr('data-swiper-parallax') || '0';
            pX = el.attr('data-swiper-parallax-x');
            pY = el.attr('data-swiper-parallax-y');
            if (pX || pY) {
                pX = pX || '0';
                pY = pY || '0';
            }
            else {
                if (s.isHorizontal()) {
                    pX = p;
                    pY = '0';
                }
                else {
                    pY = p;
                    pX = '0';
                }
            }
        
            if ((pX).indexOf('%') >= 0) {
                pX = parseInt(pX, 10) * progress * rtlFactor + '%';
            }
            else {
                pX = pX * progress * rtlFactor + 'px' ;
            }
            if ((pY).indexOf('%') >= 0) {
                pY = parseInt(pY, 10) * progress + '%';
            }
            else {
                pY = pY * progress + 'px' ;
            }
        
            el.transform('translate3d(' + pX + ', ' + pY + ',0px)');
        }
1039222
def _api_views(self, plugin):
        
        response.content_type = 'application/json; charset=utf-8'

        if plugin not in self.plugins_list:
            abort(400, "Unknown plugin %s (available plugins: %s)" % (plugin, self.plugins_list))

        # Update the stat
        # self.__update__()

        try:
            # Get the JSON value of the stat views
            ret = self.stats.get_plugin(plugin).get_views()
        except Exception as e:
            abort(404, "Cannot get views for plugin %s (%s)" % (plugin, str(e)))
        return ret
1298955
function calRadialBar(barSeries, api) {
    // Columns info on each category axis. Key is polar name
    var columnsMap = {};

    zrUtil.each(barSeries, function (seriesModel, idx) {
        var data = seriesModel.getData();
        var polar = seriesModel.coordinateSystem;

        var baseAxis = polar.getBaseAxis();
        var axisKey = getAxisKey(polar, baseAxis);

        var axisExtent = baseAxis.getExtent();
        var bandWidth = baseAxis.type === 'category'
            ? baseAxis.getBandWidth()
            : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());

        var columnsOnAxis = columnsMap[axisKey] || {
            bandWidth: bandWidth,
            remainedWidth: bandWidth,
            autoWidthCount: 0,
            categoryGap: '20%',
            gap: '30%',
            stacks: {}
        };
        var stacks = columnsOnAxis.stacks;
        columnsMap[axisKey] = columnsOnAxis;

        var stackId = getSeriesStackId(seriesModel);

        if (!stacks[stackId]) {
            columnsOnAxis.autoWidthCount++;
        }
        stacks[stackId] = stacks[stackId] || {
            width: 0,
            maxWidth: 0
        };

        var barWidth = parsePercent(
            seriesModel.get('barWidth'),
            bandWidth
        );
        var barMaxWidth = parsePercent(
            seriesModel.get('barMaxWidth'),
            bandWidth
        );
        var barGap = seriesModel.get('barGap');
        var barCategoryGap = seriesModel.get('barCategoryGap');

        if (barWidth && !stacks[stackId].width) {
            barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
            stacks[stackId].width = barWidth;
            columnsOnAxis.remainedWidth -= barWidth;
        }

        barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
        (barGap != null) && (columnsOnAxis.gap = barGap);
        (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
    });


    var result = {};

    zrUtil.each(columnsMap, function (columnsOnAxis, coordSysName) {

        result[coordSysName] = {};

        var stacks = columnsOnAxis.stacks;
        var bandWidth = columnsOnAxis.bandWidth;
        var categoryGap = parsePercent(columnsOnAxis.categoryGap, bandWidth);
        var barGapPercent = parsePercent(columnsOnAxis.gap, 1);

        var remainedWidth = columnsOnAxis.remainedWidth;
        var autoWidthCount = columnsOnAxis.autoWidthCount;
        var autoWidth = (remainedWidth - categoryGap)
            / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
        autoWidth = Math.max(autoWidth, 0);

        // Find if any auto calculated bar exceeded maxBarWidth
        zrUtil.each(stacks, function (column, stack) {
            var maxWidth = column.maxWidth;
            if (maxWidth && maxWidth < autoWidth) {
                maxWidth = Math.min(maxWidth, remainedWidth);
                if (column.width) {
                    maxWidth = Math.min(maxWidth, column.width);
                }
                remainedWidth -= maxWidth;
                column.width = maxWidth;
                autoWidthCount--;
            }
        });

        // Recalculate width again
        autoWidth = (remainedWidth - categoryGap)
            / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
        autoWidth = Math.max(autoWidth, 0);

        var widthSum = 0;
        var lastColumn;
        zrUtil.each(stacks, function (column, idx) {
            if (!column.width) {
                column.width = autoWidth;
            }
            lastColumn = column;
            widthSum += column.width * (1 + barGapPercent);
        });
        if (lastColumn) {
            widthSum -= lastColumn.width * barGapPercent;
        }

        var offset = -widthSum / 2;
        zrUtil.each(stacks, function (column, stackId) {
            result[coordSysName][stackId] = result[coordSysName][stackId] || {
                offset: offset,
                width: column.width
            };

            offset += column.width * (1 + barGapPercent);
        });
    });

    return result;
}
1342432
def collect_api_results(input_data, url, headers, api, batch_size, kwargs):
    
    if batch_size:
        results = []
        for batch in batched(input_data, size=batch_size):
            try:
                result = send_request(batch, api, url, headers, kwargs)
                if isinstance(result, list):
                    results.extend(result)
                else:
                    results.append(result)
            except IndicoError as e:
                # Log results so far to file
                timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
                filename = "indico-{api}-{timestamp}.json".format(
                    api=api,
                    timestamp=timestamp
                )
                if sys.version_info > (3, 0):
                    json.dump(results, open(filename, mode='w', encoding='utf-8'), cls=NumpyEncoder)
                else:
                    json.dump(results, open(filename, mode='w'), cls=NumpyEncoder)
                raise BatchProcessingError(
                    "The following error occurred while processing your data: `{err}` "
                    "Partial results have been saved to {filename}".format(
                        err=e,
                        filename=os.path.abspath(filename)
                    )
                )
        return results
    else:
        return send_request(input_data, api, url, headers, kwargs)
270806
public void renderView(HttpServerRequest request, JsonObject params) {
		renderView(request, params, null, null, 200);
	}
71582
function Api(basePath, options) {
            this._basePath = basePath;
            options = options || {};
            this._options = {
                enableBatching: options.hasOwnProperty('enableBatching') ?
                    options.enableBatching :
                    true,
                timeout: options.timeout || 0
            };
            this._batch = [];
            this._deferreds = {};
        }