text:
Q: How to make this floating menu work only when specific #divs become visible? I needed to make a floating menu, I searched online and found a script here http://www.jtricks.com/javascript/navigation/floating.html
/* Script by: www.jtricks.com
 * Version: 1.12 (20120823)
 * Latest version: www.jtricks.com/javascript/navigation/floating.html
 *
 * License:
 * GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 */
var floatingMenu =
{
    hasInner: typeof(window.innerWidth) == 'number',
    hasElement: typeof(document.documentElement) == 'object'
        && typeof(document.documentElement.clientWidth) == 'number'};

var floatingArray =
[
];

floatingMenu.add = function(obj, options)
{
    var name;
    var menu;

    if (typeof(obj) === "string")
        name = obj;
    else
        menu = obj;

    if (options == undefined)
    {
        floatingArray.push(
            {
                id: name,
                menu: menu,

                targetLeft: 0,
                targetTop: 0,

                distance: .07,
                snap: true,
                updateParentHeight: false
            });
    }
    else
    {
        floatingArray.push(
            {
                id: name,
                menu: menu,

                targetLeft: options.targetLeft,
                targetRight: options.targetRight,
                targetTop: options.targetTop,
                targetBottom: options.targetBottom,

                centerX: options.centerX,
                centerY: options.centerY,

                prohibitXMovement: options.prohibitXMovement,
                prohibitYMovement: options.prohibitYMovement,

                distance: options.distance != undefined ? options.distance : .07,
                snap: options.snap,
                ignoreParentDimensions: options.ignoreParentDimensions,
                updateParentHeight:
                    options.updateParentHeight == undefined
                    ? false
                    : options.updateParentHeight,

                scrollContainer: options.scrollContainer,
                scrollContainerId: options.scrollContainerId,

                confinementArea: options.confinementArea,

                confinementAreaId:
                    options.confinementArea != undefined
                    && options.confinementArea.substring(0, 1) == '#'
                    ? options.confinementArea.substring(1)
                    : undefined,

                confinementAreaClassRegexp:
                    options.confinementArea != undefined
                    && options.confinementArea.substring(0, 1) == '.'
                    ? new RegExp("(^|\\s)" + options.confinementArea.substring(1) + "(\\s|$)")
                    : undefined
            });
    }
};

floatingMenu.findSingle = function(item)
{
    if (item.id)
        item.menu = document.getElementById(item.id);

    if (item.scrollContainerId)
        item.scrollContainer = document.getElementById(item.scrollContainerId);
};

floatingMenu.move = function (item)
{
    if (!item.prohibitXMovement)
    {
        item.menu.style.left = item.nextX + 'px';
        item.menu.style.right = '';
    }

    if (!item.prohibitYMovement)
    {
        item.menu.style.top = item.nextY + 'px';
        item.menu.style.bottom = '';
    }
};

floatingMenu.scrollLeft = function(item)
{
    // If floating within scrollable container use it's scrollLeft
    if (item.scrollContainer)
        return item.scrollContainer.scrollLeft;

    var w = window.top;

    return this.hasInner
        ? w.pageXOffset
        : this.hasElement
          ? w.document.documentElement.scrollLeft
          : w.document.body.scrollLeft;
};

floatingMenu.scrollTop = function(item)
{
    // If floating within scrollable container use it's scrollTop
    if (item.scrollContainer)
        return item.scrollContainer.scrollTop;

    var w = window.top;

    return this.hasInner
        ? w.pageYOffset
        : this.hasElement
          ? w.document.documentElement.scrollTop
          : w.document.body.scrollTop;
};

floatingMenu.windowWidth = function()
{
    return this.hasElement
        ? document.documentElement.clientWidth
        : document.body.clientWidth;
};

floatingMenu.windowHeight = function()
{
    if (floatingMenu.hasElement && floatingMenu.hasInner)
    {
        // Handle Opera 8 problems
        return document.documentElement.clientHeight > window.innerHeight
            ? window.innerHeight
            : document.documentElement.clientHeight
    }
    else
    {
        return floatingMenu.hasElement
            ? document.documentElement.clientHeight
            : document.body.clientHeight;
    }
};

floatingMenu.documentHeight = function()
{
    var innerHeight = this.hasInner
        ? window.innerHeight
        : 0;

    var body = document.body,
        html = document.documentElement;

    return Math.max(
        body.scrollHeight,
        body.offsetHeight,
        html.clientHeight,
        html.scrollHeight,
        html.offsetHeight,
        innerHeight);
};

floatingMenu.documentWidth = function()
{
    var innerWidth = this.hasInner
        ? window.innerWidth
        : 0;

    var body = document.body,
        html = document.documentElement;

    return Math.max(
        body.scrollWidth,
        body.offsetWidth,
        html.clientWidth,
        html.scrollWidth,
        html.offsetWidth,
        innerWidth);
};

floatingMenu.calculateCornerX = function(item)
{
    var offsetWidth = item.menu.offsetWidth;

    var result = this.scrollLeft(item) - item.parentLeft;

    if (item.centerX)
    {
        result += (this.windowWidth() - offsetWidth)/2;
    }
    else if (item.targetLeft == undefined)
    {
        result += this.windowWidth() - item.targetRight - offsetWidth;
    }
    else
    {
        result += item.targetLeft;
    }

    if (document.body != item.menu.parentNode
        && result + offsetWidth >= item.confinedWidthReserve)
    {
        result = item.confinedWidthReserve - offsetWidth;
    }

    if (result < 0)
        result = 0;

    return result;
};

floatingMenu.calculateCornerY = function(item)
{
    var offsetHeight = item.menu.offsetHeight;

    var result = this.scrollTop(item) - item.parentTop;

    if (item.centerY)
    {
        result += (this.windowHeight() - offsetHeight)/2;
    }
    else if (item.targetTop === undefined)
    {
        result += this.windowHeight() - item.targetBottom - offsetHeight;
    }
    else
    {
        result += item.targetTop;
    }

    if (document.body != item.menu.parentNode
        && result + offsetHeight >= item.confinedHeightReserve)
    {
        result = item.confinedHeightReserve - offsetHeight;
    }

    if (result < 0)
        result = 0;

    return result;
};

floatingMenu.isConfinementArea = function(item, area)
{
    return item.confinementAreaId != undefined
        && area.id == item.confinementAreaId
        || item.confinementAreaClassRegexp != undefined
        && area.className
        && item.confinementAreaClassRegexp.test(area.className);
};

floatingMenu.computeParent = function(item)
{
    if (item.ignoreParentDimensions)
    {
        item.confinedHeightReserve = this.documentHeight();
        item.confinedWidthReserver = this.documentWidth();
        item.parentLeft = 0;
        item.parentTop = 0;
        return;
    }

    var parentNode = item.menu.parentNode;
    var parentOffsets = this.offsets(parentNode, item);
    item.parentLeft = parentOffsets.left;
    item.parentTop = parentOffsets.top;

    item.confinedWidthReserve = parentNode.clientWidth;

    // We could have absolutely-positioned DIV wrapped
    // inside relatively-positioned. Then parent might not
    // have any height. Try to find parent that has
    // and try to find whats left of its height for us.
    var obj = parentNode;
    var objOffsets = this.offsets(obj, item);

    if (item.confinementArea == undefined)
    {
        while (obj.clientHeight + objOffsets.top
                   < item.menu.scrollHeight + parentOffsets.top
               || item.menu.parentNode == obj
               && item.updateParentHeight
               && obj.clientHeight + objOffsets.top
                   == item.menu.scrollHeight + parentOffsets.top)
        {
            obj = obj.parentNode;
            objOffsets = this.offsets(obj, item);
        }
    }
    else
    {
        while (obj.parentNode != undefined
               && !this.isConfinementArea(item, obj))
        {
            obj = obj.parentNode;
            objOffsets = this.offsets(obj, item);
        }
    }

    item.confinedHeightReserve = obj.clientHeight
        - (parentOffsets.top - objOffsets.top);
};

floatingMenu.offsets = function(obj, item)
{
    var result =
    {
        left: 0,
        top: 0
    };

    if (obj === item.scrollContainer)
        return;

    while (obj.offsetParent && obj.offsetParent != item.scrollContainer)
    {
        result.left += obj.offsetLeft;
        result.top += obj.offsetTop;
        obj = obj.offsetParent;
    }

    if (window == window.top)
        return result;

    // we're IFRAMEd
    var iframes = window.top.document.body.getElementsByTagName("IFRAME");
    for (var i = 0; i < iframes.length; i++)
    {
        if (iframes[i].contentWindow != window)
           continue;

        obj = iframes[i];
        while (obj.offsetParent)
        {
            result.left += obj.offsetLeft;
            result.top += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }

    return result;
};

floatingMenu.doFloatSingle = function(item)
{
    this.findSingle(item);

    if (item.updateParentHeight)
    {
        item.menu.parentNode.style.minHeight =
            item.menu.scrollHeight + 'px';
    }

    var stepX, stepY;

    this.computeParent(item);

    var cornerX = this.calculateCornerX(item);

    var stepX = (cornerX - item.nextX) * item.distance;
    if (Math.abs(stepX) < .5 && item.snap
        || Math.abs(cornerX - item.nextX) <= 1)
    {
        stepX = cornerX - item.nextX;
    }

    var cornerY = this.calculateCornerY(item);

    var stepY = (cornerY - item.nextY) * item.distance;
    if (Math.abs(stepY) < .5 && item.snap
        || Math.abs(cornerY - item.nextY) <= 1)
    {
        stepY = cornerY - item.nextY;
    }

    if (Math.abs(stepX) > 0 ||
        Math.abs(stepY) > 0)
    {
        item.nextX += stepX;
        item.nextY += stepY;
        this.move(item);
    }
};

floatingMenu.fixTargets = function()
{
};

floatingMenu.fixTarget = function(item)
{
};

floatingMenu.doFloat = function()
{
    this.fixTargets();
    for (var i=0; i < floatingArray.length; i++)
    {
        this.fixTarget(floatingArray[i]);
        this.doFloatSingle(floatingArray[i]);
    }
    setTimeout('floatingMenu.doFloat()', 20);
};

floatingMenu.insertEvent = function(element, event, handler)
{
    // W3C
    if (element.addEventListener != undefined)
    {
        element.addEventListener(event, handler, false);
        return;
    }

    var listener = 'on' + event;

    // MS
    if (element.attachEvent != undefined)
    {
        element.attachEvent(listener, handler);
        return;
    }

    // Fallback
    var oldHandler = element[listener];
    element[listener] = function (e)
        {
            e = (e) ? e : window.event;
            var result = handler(e);
            return (oldHandler != undefined)
                && (oldHandler(e) == true)
                && (result == true);
        };
};

floatingMenu.init = function()
{
    floatingMenu.fixTargets();

    for (var i=0; i < floatingArray.length; i++)
    {
        floatingMenu.initSingleMenu(floatingArray[i]);
    }

    setTimeout('floatingMenu.doFloat()', 100);
};

// Some browsers init scrollbars only after
// full document load.
floatingMenu.initSingleMenu = function(item)
{
    this.findSingle(item);
    this.computeParent(item);
    this.fixTarget(item);
    item.nextX = this.calculateCornerX(item);
    item.nextY = this.calculateCornerY(item);
    this.move(item);
};

floatingMenu.insertEvent(window, 'load', floatingMenu.init);

// Register ourselves as jQuery plugin if jQuery is present
if (typeof(jQuery) !== 'undefined')
{
    (function ($)
    {
        $.fn.addFloating = function(options)
        {
            return this.each(function()
            {
                floatingMenu.add(this, options);
            });
        };
    }) (jQuery);
}

The script requires the menu to have #floatdiv id. I made my div, #floatdiv, and added the following line of javascript to the head to make the action start working:

the #floatdiv css is here,
#floatdiv{
    height:45px;
    width:830px;
    z-index:2;
}

The script is working fine. When I scroll down, the menu float as specified. But I dun wanna the menu to float all the way with scrolling. I need the float of the menu to fire only when I enter specific divs not all the way with scrolling.. Any clues?

A: is this what look like?
html

HEADER

LEFT

RIGHT

FOOTER

js
$(function() {
    var $sidebar = $("#right"),
        $window = $(window),
        rightOffset = $sidebar.offset(),
        rightDelta = $("#footer").offset().top - $("#header").offset().top - $("#header").outerHeight() - $("#right").outerHeight(),
        topPadding = 15;

    $window.scroll(function() {
            $sidebar.stop().animate({
                marginTop: Math.max(Math.min($window.scrollTop() - rightOffset.top + topPadding, rightDelta), 0)
            });
    });

});

working demo
hope this help you

A: I wrote the script listed in the question.
The script is very versatile and can make div float within a specific area (e.g. another container div). Here are the instructions:
http://www.jtricks.com/javascript/navigation/floating/confined_demo.html


text:
Q: Drupal 7 FAPI type button does not work Ik am doing a very simple form where I add a button which should do some functionality, but it's not working. Altough the button is visible on the page and when I click it the page is refreshed. Can anyone see what's wrong with this code ?
function donation_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'wedding_article_node_form') {
        $form['add_donation'] = array(
            '#type' => 'button',
            '#submit' => array('donation_add_donation'),
            '#value' => t('Add donation'),
        );
    }
}

function donation_add_donation(&$form, &$form_state) {
    dpm('test');
    dpm($form);
}

A: You need a submit type element if you want to run a submit handler. From the documentation:

When the button is pressed, the form will be submitted to Drupal, where it is validated and rebuilt. The submit handler is not invoked.

(emphasis mine)

A: Try use the property "#executes_submit_callback" and set it to TRUE
$form['preview'] = array(

  '#type' => 'button',
  '#value' => t('Preview'),
  '#weight' => 19,
  '#executes_submit_callback' => TRUE, // add this line.

);

Good Luck
Muhammad

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tensor("StatefulPartitionedCall_8:0) and Expected any non-tensor type, got a tensor instead exceptions I have been trying to use Elmo for word embedding with the downloaded imdb dataset. I found this example:
https://www.analyticsvidhya.com/blog/2019/03/learn-to-use-elmo-to-extract-features-from-text/
However, I am having different issues. The texts that I am processing are like the following:
20316    Simple story    why say more  It nails it s pr...
13180    It s cheesy  it s creepy  it s gross  but that...
23353    Astounding     This may have been A poor attem...
13658    In a penitentiary  four prisoners occupy a cel...
19625    An unusual take on time travel  instead of tra...

24173    Is this your typical women in chains navy tran...
4522     I don t know much about Tobe Hooper  or why he...
1718     what kind of sh t is this  Power rangers vs Fr...
10006    I have a piece of advice for the people who ma...
12360    I went in not knowing anything about this movi...
Name: texts, Length: 24999, dtype: object

with a shape of (24999,)
elmo=hub.load("https://tfhub.dev/google/elmo/2")
listTrain=[X_train[i:i+10] for i in range(0,X_train.shape[0],10)]
elmoTrain=[getElmo(elmo,i)for i in listTrain]

and my function getElmo is the following:
def getElmo(elmo,x):
    embed=elmo.signatures["default"](tf.constant(x))
    tf.compat.v1.disable_eager_execution()
    with tf.compat.v1.Session() as ses:
        ses.run(tf.compat.v1.global_variables_initializer())
        ses.run(tf.compat.v1.tables_initializer())
        return ses.run(tf.reduce_mean(embed,1))

The original source code of the link of the tutorial is the following:
def elmo_vectors(x):
  embeddings = elmo(x.tolist(), signature="default", as_dict=True)["elmo"]

  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(tf.tables_initializer())
    # return average of ELMo features
    return sess.run(tf.reduce_mean(embeddings,1))

However, I have the following exceptions:
ValueError: Tensor("StatefulPartitionedCall_10:0", shape=(None, 1024), dtype=float32)
and
TypeError: Expected any non-tensor type, got a tensor instead.
How can I fix them?
Actually I am using Python 3.7 and tensorflow 2.3.


text:
Q: RegEx that matches only if a string contains a word from each list I'm developing a software that has to check if a text contains a word taken from a specified list and a word taken from another specified list.
Example:
list 1: dog, cat
list 2: house, tree

the following texts has to match:
the dog is in the house -> contains dog and house
my house is full of dogs -> contains dog and house
the cat is on the tree -> contains cat and tree

the following examples must not to match
the frog is in the house -> there is no word from the first list
Boby is the name of my dog -> there is no word from the second list
Outside my house there is a tree -> there is no word from the first list

To solve quickly the problem I've made a list of pattern like:
dog.*house, house.*dog, cat.*house, ...

but I'm pretty sure there is an smarter way...

A: You can use an alternation (|) for each of the sets of alternatives, and a wrapper alternation for the order. So:
(?:(?:dog|cat).*(?:house|tree))|(?:(?:house|tree).*(?:dog|cat))

JavaScript Example (non-capturing groups and alternations work the same in Java and JavaScript):

var tests = [
    {match: true,  text: "the dog is in the house -> contains dog and house"},
    {match: true,  text: "my house is full of dogs -> contains dog and house"},
    {match: true,  text: "the cat is on the tree -> contains cat and tree"},
    {match: false, text: "the frog is in the house -> there is no word from the first list"},
    {match: false, text: "Boby is the name of my dog -> there is no word from the second list"},
    {match: false, text: "Outside my house there is a tree -> there is no word from the first list"}
];
var rex = /(?:(?:dog|cat).*(?:house|tree))|(?:(?:house|tree).*(?:dog|cat))/;
tests.forEach(function(test) {
  var result = rex.test(test.text);
  if (!!result == !!test.match) {
    console.log('GOOD: "' + test.text + '": ' + result);
  } else {
    console.log('BAD: "' + test.text + '": ' + result + ' (expected ' + test.match + ')');
  }
});
.as-console-wrapper {
  max-height: 100% !important;
}

Note that in the above we're not checking for words, just sequences of letters. If you want it to be actual words, you'll need to add word break assertions or similar. Left as an exercise to the reader...

A: Here is a solution that works for any number of lists, with any number of words in them.
RegEx is for scanning linear sequences. However, you are asking two questions, which can be true or false, irrespective of the order of the patterns. Therefore, you must enumerate all permutations of regex combinations. For small number of lists, this can be done manually, as is demonstrated in the other answer. Below is the solution for the general case.
You certainly don't want to write the regex out manually, so here is a Java program that does what you want:
import java.util.*;
import java.util.stream.*;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;

public class RegexWithPermutations {

    /** Build a regex the checks whether
      * a string contains one of the words.
      */
    public static String containsWordRegex(List<String> words) {
      StringBuilder sb = new StringBuilder();
      boolean first = true;
      for (String w: words) {
        if (!first) {
          sb.append("|");
        }
        sb.append("(?:" + w + ")");
        first = false;
      }
      return sb.toString();
    }

    /** Generates all permutations of regexes.
      */
    public static String allRegexPermutations(
      final List<String> regexes,
      final String separator
    ) {
      class PermutationHelper {
        /** Deletes one element from the array */
        private int[] remove(int[] arr, int idx) {
          int n = arr.length;
          int[] res = new int[n - 1];
          System.arraycopy(arr, 0, res, 0, idx);
          System.arraycopy(arr, idx + 1, res, idx, n - idx - 1);
          return res;
        }

        /** Helper method that generates all permutations combined with "|".
          */
        public List<String> rec(String suffix, int[] unusedIndices) {
          if (unusedIndices.length == 1) {
            return asList(regexes.get(unusedIndices[0]) + suffix);
          } else {
            return IntStream.range(0, unusedIndices.length)
              .boxed()
              .<String>flatMap(i -> rec(
                separator + regexes.get(unusedIndices[i]), // (suffix.isEmpty() ? "" : ("COMB" + suffix))
                remove(unusedIndices, i)
              ).stream())
              .collect(toList());
          }
        }
      }
      int[] startIndices = new int[regexes.size()];
      for (int i = 0; i < regexes.size(); i++) {
        startIndices[i] = i;
      }
      List<String> ps = (new PermutationHelper()).rec("", startIndices);
      StringBuilder b = new StringBuilder();
      boolean first = true;
      for (String p : ps) {
        if (!first) {
          b.append("|");
        }
        b.append(p);
        first = false;
      }
      return b.toString();
    }

    public static void main(String[] args) {
      List<String> list_1 = asList("dog", "cat");
      List<String> list_2 = asList("house", "tree");

      List<String> examples = asList(
        "the dog is in the house",
        "my house is full of dogs",
        "the cat is on the tree",
        "the frog is in the house",
        "Boby is the name of my dog",
        "Outside my house there is a tree"
      );

      String regex = ".*(?:" + allRegexPermutations(asList(
        "(?:" + containsWordRegex(list_1) + ")",
        "(?:" + containsWordRegex(list_2) + ")"
      ), ".*") + ").*";

      System.out.println("Constructed regex: " + regex);

      for (String example: examples) {
        System.out.println(example + " -> " + example.matches(regex));
      }
    }
}

Output:
    Constructed regex: .*(?:(?:(?:house)|(?:tree)).*(?:(?:dog)|(?:cat))|(?:(?:dog)|(?:cat)).*(?:(?:house)|(?:tree))).*
    the dog is in the house -> true
    my house is full of dogs -> true
    the cat is on the tree -> true
    the frog is in the house -> false
    Boby is the name of my dog -> false
    Outside my house there is a tree -> false

It works with arbitrary numbers of lists (but the length of the regex grows hyperexponentially, so it's not advisable to use it for anything longer than 3, 4, 5).


text:
Q: Infinite loop when adding 1 character to a list I am writting a program which adds a character to a list. The problem is that when I have my original list of 5 nodes and I try to add another, everything works, but than when I try to add another one the stampa function becomes infinite.
I can not find the bug. Any help would be welcomed. Here is the code:
struct nodo {
    char c;
    struct nodo *next;
};
typedef struct nodo *lista;

void mc_coda(lista *l, char el);

void stampa(lista nodo01);

int main() {
    int test[5] = {0, 1, 1, 0, 1};
    lista nodo01 = malloc(sizeof(struct nodo));
    lista nodo02 = malloc(sizeof(struct nodo));
    lista nodo03 = malloc(sizeof(struct nodo));
    lista nodo04 = malloc(sizeof(struct nodo));
    lista nodo05 = malloc(sizeof(struct nodo));

    (*nodo01).next = nodo02;
    (*nodo02).next = nodo03;
    (*nodo03).next = nodo04;
    (*nodo04).next = nodo05;
    (*nodo05).next = NULL;

    (*nodo01).c = 'a';
    (*nodo02).c = 'b';
    (*nodo03).c = 'c';
    (*nodo04).c = 'd';
    (*nodo05).c = 'e';

    mc_coda(&nodo01, 'e');
    mc_coda(&nodo01,
            'f'); // If this line is removed everything workd fine, if this line
                  // if added that it         prints infinite f

    stampa(nodo01);

    return 0;
}

void mc_coda(lista *l, char el) {
    if ((*l) == NULL) {
        struct nodo temp;
        temp.next = NULL;
        temp.c = el;
        (*l) = &temp;
    } else {
        while ((*l) != NULL) {
            l = &(*(*l)).next;
        }
        struct nodo temp;
        temp.next = NULL;
        temp.c = el;
        (*l) = &temp;
    }
}

void stampa(lista nodo01) {
    while (nodo01 != NULL) {
        printf("%c\n", (*nodo01).c);
        nodo01 = (*nodo01).next;
    }
}

A: Your implementation of mc_coda creates a local variable temp. Because temp is a local variable it will go out of scope when the function exits and then the space will be reused. Instead, you need to allocate space on the heap with malloc. See the below implementation of mc_coda for an example of how to do that:
#include <stdio.h>
#include <stdlib.h>

struct nodo {
    char c;
    struct nodo *next;
};

typedef struct nodo *lista;

void mc_coda(lista *l, char el);

void stampa(lista nodo01);

int main() {
    lista nodo01 = malloc(sizeof(struct nodo));
    lista nodo02 = malloc(sizeof(struct nodo));
    lista nodo03 = malloc(sizeof(struct nodo));
    lista nodo04 = malloc(sizeof(struct nodo));
    lista nodo05 = malloc(sizeof(struct nodo));

    (*nodo01).next = nodo02;
    (*nodo02).next = nodo03;
    (*nodo03).next = nodo04;
    (*nodo04).next = nodo05;
    (*nodo05).next = NULL;

    (*nodo01).c = 'a';
    (*nodo02).c = 'b';
    (*nodo03).c = 'c';
    (*nodo04).c = 'd';
    (*nodo05).c = 'e';

    mc_coda(&nodo01, 'e');
    mc_coda(&nodo01, 'f');

    stampa(nodo01);

    return 0;
}

void mc_coda(lista *l, char el) {
    lista tmp = malloc(sizeof(struct nodo));
    tmp->next = NULL;
    tmp->c = el;
    if ((*l) == NULL) {
        (*l) = tmp;
    } else {
        while ((*l) != NULL) {
            l = &(*(*l)).next;
        }
        (*l) = tmp;
    }
}

void stampa(lista nodo01) {
    while (nodo01 != NULL) {
        printf("%c\n", (*nodo01).c);
        nodo01 = (*nodo01).next;
    }
}


text:
Q: LINQ to SQL - Update to increment a non-primary-key field - thread-safe I have two tables (well, two relevant for this question) :
Bets (holds the bets; Columns : Id, , MessagesPosted, )
Bets_Messages (holds the bets' forum messages; Columns : Id, BetId, )
When I insert a new BetMessage in Bets_Messages I want to update (increment to be precise) the corresponding field in Bets.
In pure T-SQL that would be :
INSERT INTO Bets_Messages (BetId, <bla bla>) VALUES (23, "asfasdfasdf");
UPDATE Bets SET MessagesPosted = MessagesPosted + 1 WHERE Id = 23;

The above code would work wonderful and it is thread safe; If two threads would make DB calls to it (and for the same Bet ofcourse) the MessagesPosted column would increment nicely since the first UPDATE would put at least a ROWLOCK on it practically serializing the UPDATEs.
However using LINQ to SQL this comes to a more difficult approach:
    public void PostMessage(MyProject.Entities.BetMessage betMessageEntity)
    {
        DatabaseDataContext ctx = GetFreshContext(); // GetFreshContext is a private method that practically initializes a new DataContext
        Bets_Message msg = new Bets_Message(betMessageEntity);
        ctx.Bets_Messages.InsertOnSubmit(msg);
        Bet bet = (from b in ctx.Bets where b.Id == (long)betMessageEntity.BetId select b).Single();
        bet.MessagesPosted++;
        ctx.SubmitChanges();
    }

Looks nice, huh? Well here's what it will generate :
exec sp_executesql N'INSERT INTO [dbo].[Bets_Messages]([ParentMessageId], [BetsId], [UserId], [Subject], [DisplayXml], [Time], [ReplyDepth], [Text])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7)

SELECT CONVERT(BigInt,SCOPE_IDENTITY()) AS [value]',N'@p0 bigint,@p1 bigint,@p2 uniqueidentifier,@p3 nvarchar(6),@p4 nvarchar(114),@p5 datetime2(7),@p6 tinyint,@p7 nvarchar(8)',@p0=NULL,@p1=1,@p2='A0D253AF-6261-49AE-8C11-BA6117EF35C7',@p3=N'aaawww',@p4=N'<m ai="a0d253af-6261-49ae-8c11-ba6117ef35c7" a="AndreiR" s="aaawww" t="2009-01-31T18:04:31.282+02:00">wwwwwaaa</m>',@p5='2009-01-31 18:04:31.2820000',@p6=0,@p7=N'wwwwwaaa'

(for the BetMessage insert) and for the UPDATE :
exec sp_executesql N'UPDATE [dbo].[Bets]
SET [MessagesPosted] = @p17
WHERE ([Id] = @p0) AND ([UserId] = @p1) AND ([Bets_CategoriesId] = @p2) AND ([Bets_TypesId] = @p3) AND ([TotalSum] = @p4) AND ([TotalBetters] = @p5) AND ([CreateDate] = @p6) AND ([DeadlineDate] = @p7) AND ([ClosedDate] IS NULL) AND ([Bets_StatusesId] = @p8) AND ([LastBetAdded] IS NULL) AND ([Title] = @p9) AND ([ShortDescription] = @p10) AND ([Description] = @p11) AND ([DescriptionPlainText] = @p12) AND ([Version] = @p13) AND ([ReviewedBy] = @p14) AND ([UrlFragment] = @p15) AND ([MessagesPosted] = @p16) AND ([ClosedBy] IS NULL) AND ([OutcomeNumber] IS NULL)',N'@p0 bigint,@p1 uniqueidentifier,@p2 smallint,@p3 tinyint,@p4 money,@p5 int,@p6 datetime2(7),@p7 datetime2(7),@p8 tinyint,@p9 nvarchar(7),@p10 nvarchar(30),@p11 nvarchar(33),@p12 nvarchar(22),@p13 smallint,@p14 uniqueidentifier,@p15 varchar(7),@p16 int,@p17 int',@p0=1,@p1='A0D253AF-6261-49AE-8C11-BA6117EF35C7',@p2=2,@p3=1,@p4=$0.0000,@p5=0,@p6='2008-12-03 00:00:00',@p7='2008-12-31 00:00:00',@p8=2,@p9=N'Pariu 1',@p10=N'Descriere pariu 1 - text chior',@p11=N'Descriere pe larg 1 - html permis',@p12=N'descriere text chior 1',@p13=1,@p14='A0D253AF-6261-49AE-8C11-BA6117EF35C7',@p15='pariu-1',@p16=18,@p17=19

The problem with the T-SQL generated for the UPDATE is that although seems ok as thread-safety it will probably throw an error  in the second thread doing the update on the row instead of waiting for it to finish. Will it?
Here's why I think this.
1st thread does this :
insert the corresponding betMessage,
update the bet row to increment the MessagePosted from 0 to 1
the 2nd thread will do this:
insert it's corresponding betMessage,
update the bet row to increment the MessagePosted from 0 to 1 (it was 0 when it read it). However now it is 1 and the WHERE clause will make it not update since the wHERE clause will evaluate to false. 0 row(s) affected will be sent to the LINQ client and that in turn will throw an exception.
Therefore I will have to write my f*#$ing retry attempt code instead of relying on ROW LOCKs in the SQL Server.
Is there some decent approach that uses LINQ to SQL and NOT stored procedures, ad-hoc queries and so on?
Thank you for your patience of reading this long post..

A: EDIT: Actually after rereading your post, I think that the automatic transaction generated by SubmitChanges will already take care of making sure that all of the statements are completed or none are.  I was thinking that since you were using the automatically generated id, that you'd do a two-stage update in LINQ, but it seems that SubmitChanges handles it for you.
I'll leave the code below for reference, though I don't think that it's required.  The link at the bottom explains about the different ways of accomplishing the transaction.
What you need is a transaction scope to wrap the entire set of inserts/updates in.
using System.Transactions;

public void PostMessage(MyProject.Entities.BetMessage betMessageEntity)
{
    using (TransactionScope scope = new TransactionScope()) {
       DatabaseDataContext ctx = GetFreshContext();
       Bets_Message msg = new Bets_Message(betMessageEntity);
       ctx.Bets_Messages.InsertOnSubmit(msg);
       ctx.SubmitChanges();  // this is what I thought you did
       Bet bet = (from b in ctx.Bets
                  where b.Id == (long)betMessageEntity.BetId select b)
                 .Single();
       bet.MessagesPosted++;
       ctx.SubmitChanges();
       scope.Complete();
    }
}

I don't think this will cause automatic promotion to a distributed transaction since all of the commands reuse the same connection in the data context.  If it turns out that it does, you can create a transaction on the data context's connection and assign it to the data context's Transaction property.  If you do this, though, you'll need to manage and dispose of it yourself.
More info on LINQ2SQL and transactions at MSDN.


text:
Q: Defining field mapping for Service Area Calculation in ModelBuilder? I am building a model to generate service areas for health facilities and I'd like to have the facility ID instead of OID used in the Name field of the resulting service area layer. Outside of model builder I can accomplish this by defining the Name Property in the Location Analysis Properties dialog box.

In my model however, I can't enter a value for that property in the Add Locations tool. I have tried both doing it within the "Add locations" tool and defining a variable from the "Field Mapping" parameter neither approach lets me define the field for the Name Property.
Is there a way in model builder to define which field should be used for the Name in the resulting service area polygons?
I'm using ArcGIS 10.3

A: After much trial and error I solved my problem by creating a "Field Mappings" parameter for the "Add Locations" tool and then changing the properties from "A Single Value" to  "A List of Values". This made it possible to add the correct Field Name and send it to the tool.


text:
Q: vertically centering one and two line text buttons I think this is a simple one but I have a row of buttons: one that is just one short word and two that are 3 long words so they run to two lines.
How can I get them to vertically center in the button? I have tried some variations of display:table-cell etc but couldn't get it exactly right.
Some code:

FAQs

Interactive Property Map

Request a Presentation

Here's my jsfiddle
Thanks in advance!

A: #button_menu {
    font-family:"adelle", Georgia, Times, serif;
    font-size:12px;
    font-weight:700;
    float:right;

    position:relative;
}

#button_menu ul{
    list-style:none;
    margin:40px 10px 0px 0px;
    padding:0px;
    display:table;
    border-spacing:5px;
}

#button_menu ul li{
    display: table-cell;
    text-align:center;
    line-height:18px;
    height:45px;
    padding:0px;
    vertical-align:middle;

   -moz-border-radius: 4px;
   -webkit-border-radius: 4px;
   border-radius: 4px; /* future proofing */
}

JS FIDDLE: http://jsfiddle.net/MFMBR/1/  Important - you have to use border-spacing, instead of margin, because margin can't be applied to display:table-cell elements. More: Why is a div with "display: table-cell;" not affected by margin?


text:
Q: Ir para âncora antes do carregamento completo da página Possuo uma página que toda vez ao atualizar, retorna ao topo após o carregamento completo. Porém, possuo uma segunda página que tem um link da seguinte forma: index.html#empresa, gostaria que a mesma parasse,"independentemente" do seu carregamento, na âncora empresa.
→ Pastebin do index.html

A: O código abaixo deve funcionar ao seu propósito:
<script>
    curr_url = window.location.href; //pego a URL da página
    if(curr_url.indexOf("#") != -1){ // verifico se existe # na URL
       parametro = curr_url.substring(curr_url.indexOf("#"),curr_url.length); // extraio da URL a string com tudo que vier depois de "#" (inclusive o "#")
       $('html, body').animate({
           scrollTop: $(parametro).offset().top
       }, 10); // desço a janela até a div com o id extraido da string na URL
    }
</script>

Você pode usar o código sem esperar o carregamento da página ($(document).ready). Porém é preciso que o código esteja no final do <body>. Isso porque a página é carregada linha por linha, de cima para baixo e o elemento em questão (#empresa) já foi carregado.

Obs.: Isso não funciona no exatíssimo momento em que a página é chamada. Vai
  depender da velocidade do carregamento da página até chegar no script,
  pois não é possível executar um script antes do carregamento normal da página.

A: $(window).load(function(){
    if(window.location.hash) {
        $('html, body').animate({
            scrollTop: $(window.location.hash).offset().top + 'px'
        }, 1000, 'swing');
    }
});


text:
Q: How do I use Google Maps API in a Java code to fetch coordinates of specified location? In a BI project I'm currently working on, we are in need of geo-coordinates for a list of locations. With the address location (such as "New York, US") as input, the output should be the coordinates as a latitude-longitude pair (like {40.71435, -74.00597}). The behaviour is similar to what is seen on this page.
A similar question earlier on SO points to using the Google Maps API in JavaScript to achieve this, but I'm looking for a Java solution -- some function of the form getCoordinates(location), because this is a small requirement in a larger Java program already in existence.
Any pointers on how I may use the Google Maps API (or any other maps API) in Java to achieve this would be of great help!

A: You can use the Google Geocoding HTTP API (see here).
To connect to it and get the responses you can use a Java URLConnection (tutorial is here) and parse the response using your favourite Json library (I personally use Jackson)

A: So you'd like a way to perform Google Maps API Geocoding via Java - here's one that might work for you. The response might not be in the exact same format you need but should be pretty workable:
http://code.google.com/p/geocoder-java/
You can see the final format returned in LatLng.java - just trace the code through starting from GeocodeResponse.java and you'll see the final format - the classes are pretty simple.


text:
Q: problem get index datasource ej2-angular-list I use ej2-angular-list binding datasource but i can't get index of item in #template,I try research in homepage ej2 but it no benefit.
 <ejs-listview
    id="List"
    [dataSource]="data"
    [headerTitle]="title"
    cssClass="e-list-template"
    [showHeader]="title != ''"
    [fields]="fields"
  >
    <div class="list-item">
      <ng-template #template let-dataItem let-index="i">
        <div *ngIf="!dataItem.__loading">
          <div
            class="card-with-dropdown-item"
            [attr.data-id]="dataItem[groupBy]"
          >
            <ng-container
              *ngTemplateOutlet="
                itemTemplate;
                context: { $implicit: dataItem, index: index }
              "
            >
            </ng-container>
          </div>
        </div>

      </ng-template>
    </div>**strong text**
  </ejs-listview>


text:
Q: std::allocator not preserving old allocated items after reallocation I am trying to realize a Vector class that allocates a block of memory, and eventually re-allocate it if it needs to contain more items.
I am using std::allocator to do this:
#include <iostream>
#include <stdexcept>

using namespace std;

template <class T>
class Vector
{
private:
    T* data;
    allocator<T> data_all;
    int length;
    int _size;
    static const int block_size=10;
    void init()
    {
        length=0;
        _size=block_size;
        data=data_all.allocate(block_size,NULL);
    }
public:
    Vector()
    {
        init();
    }
    int size() const
    {
        return length;
    }
    void push_back(T item)
    {
        length++;
        if(length > _size)
        {
            _size+=block_size;
            data=data_all.allocate(_size,data);
        }
        data_all.construct(&data[length-1],item);
    }
    T& operator[] (int i)
    {
        if(i<0 || i>= length)
            throw out_of_range("The index is out of vector range");
        return data[i];
    }
};

int main(int argc, char** argv)
{
    Vector<int> v;
    for(int i=0; i<20; i++)
        v.push_back(i);
    for(int i=0; i<v.size(); i++)
        cout << v[i] << "\t";
    return 0;
}

The problem is that the item previously allocated are not preserved, it prints:
0   0   0   0   0   0   0   0   0   0   10  11  12  13  14  15  16  17  18  19

Instead of:
0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15  16  17  18  19

Why this behaviour? Isn't there a way in C++ to re-allocate contiguous items like in C with realloc?

A: The second argument to allocate is just a hint that the allocator could use to try and return new memory close to the old memory, but is ignored by std::allocator and fairly useless for vector-like containers because all the elements are close to each other anyway, as they're in a contiguous block.
You seem to be expecting it to copy the existing data. It won't. You have to do that, by copying from the old memory block to the new one.
You're also leaking the old memory.  You need to deallocate it.
You want something like:
void push_back(const T& item)
{
    if (length == _size)
    {
        T* new_data = data_all.allocate(_size+block_size);
        // N.B. if any of the following copies throws new_data will be leaked
        std::uninitialized_copy(data, data+length, new_data);
        std::destroy(data, data+length);
        data_all.deallocate(data, _size);
        data = new_data;
        _size+=block_size;
    }
    data_all.construct(&data[length++],item);
}


text:
Q: CodeIgniter flash data working locally but not on server Hello CodeIgniter users.
I have a problem with flash data and I would like some help. My CI version is 2.1.4.
I am using CI flash data to store data temporarily for a form that consists of multiple pages. Data entered on each page is stored so it can be accessed on the next pages and finally all data is entered int the database.
Now to keep data stored through multiple pages, instead of only one, I extended the Session class with the following function:
function keep_all_flashdata($prefix = '')
{
    $userdata = $this->all_userdata();
    foreach ($userdata as $key => $value)
    {
        if (strpos($key, ':old:' . $prefix))
        {
            $new_flashdata_key = str_replace(':old:', ':new:', $key);
            $this->set_userdata($new_flashdata_key, $value);
        }
    }
}

This function preserves all flash data (or optionally only flash data that starts with a certain string) for another redirect. It is similar to the keep_flashdata function except for the fact that it works for multiple items without requiring their exact name.
After calling this function, both :old: and :new: keys are stored in the session data. Then after a redirect, old keys are removed and new keys are set to old. Then, if there's another page, I call keep_all_flashdata() again and so on until the last page.
This works fine when I'm working on my local WAMP server, but on my actual server, all flashdata just gets removed after a redirect, even if it has :new: in the key. I confirmed my keep_all_flashdata() function works by checking the contents of session->all_userdata() and everything looks as expected.
I am using some AJAX calls, but they should not erase flash data (a known issue) as I've prevented this with $this->CI->input->is_ajax_request() before flashdata is cleared (in the sess_update() and _flashdata_sweep() functions).
Is this a bug in CodeIgniter or am I doing something wrong? Any help is appreciated.

A: I think your if statement is causing the problem. I'm assuming that ":old:" or ":new:" is used as prefix for every key you store in a session?
strpos() returns the position of where the needle exists so that would be 0 when checking a key with the prefix ':old:'. That's intended as old flashdata needs to be removed. I tested the following piece of code:
$flashDataKey = ':new:myKey';

die(var_dump(strpos($flashDataKey, ':old:')));

Which returns false as expected since the needle was not found. Resulting in not storing the flashdata as ':old:' and keeping it for the next request.
I'm not sure why this is working on your localhost. You should change your if statement to:
if( strstr($key, ':new:') !== false)

Now only keys containing the string ':new:' will pass and everything else will return false. Hope this helped!


text:
Q: Need Help regarding this Peak to Peak Detector Circuit
Hey guys need some help from you...
I have made a small circuit (Peak to Peak Detector Circuit).  but i am confused what should be the voltage ratings of the capacitors and wattage ratings of the resistors.  Maximum AC voltage will be 550V AC.
When i supply 550 V AC, the DC output is about 800V

A: All of the comments so far are on the money. With all due respect, you have too little knowledge to be fooling around with this level of possible damage. If you really do have a "client" who is presumably paying you money to do this, you are taking his money on false pretenses, and the results of your efforts are going to be passed along to somebody else who may be injured or killed. Just stop.
Also, of course, you have presented a wildly inaccurate schematic. Your D1 and C2 are most certainly not the components you're using, and if R1 and C1 are accurate they demonstrate that you are simply out of your depth. I will not go into more detail about why this is so, since I'm not going to encourage you.
Please. Just stop this and go do some studying about basic electronics, or at least more advanced than you already have.

A: In this application note there are some precaution advice and other information about what you are going to do. Be careful about what you are doing, the circuit is not isolated and can hurt you. You should be aware that even low voltage in micro's side can hurt you due to lack of isolation.

*

*AVR182: Zero Cross Detector


text:
Q: Using dynamic layouts from json response: angularJS In my web app, in a search result, each item can have a different look according to the type of item. To achieve this, I was thinking of including the layout with data placeholders for that particular item in the json response. How do I bind the scope data to the placeholders in the json response template?
for eg.
My search result would look something like :

And the JSON response would look like :
[{
"template_name":"One",
"template":"
{{subitem.name}}
",
"subitems":[{name:"John"},{name:"Jane"}]
},
{
"template_name":"Two",
"template":"
{{subitem.name}}
",
"subitems":[{name:"John"},{name:"Jane"}]
}
]

Like you can see, I need to bind the placeholders in the json response with the scope data. Is there any way to do it? If not, how do you suggest i should address this situation?
Thank You!

A: While this will obviously not work:

Since you are telling angular to display html that is inside item.template but what you really want is to tell it to treat item.template as it would be markup that should be parsed in a similar way to a template inside directive.
What you can do however is to define custom directive that will treat item.template in a desired manner. For instance:

Where dynamic-template is defined as follows:
 module.directive('dynamicTemplate', function($compile){
    return {
      scope: {
        dynamicTemplate:'='
      },
      replace:true,
      transclude: true,
      link: function($scope, $element, $attrs, _, $transcludeFn){
        // since we have isolate scope - transclude the element so it has access
        // to item and anything else available inside ng-repeat
        $transcludeFn(function($childElement, $childScope){
          var link = $compile($scope.dynamicTemplate);
          var bound = link($childScope);
          $element.append(bound);
        });
      }
    };
  });

Of course this is not ideal since changes to item.template wont be reflected but you can easily extend this by adding $watch.
You can find working example here.


text:
Q: Enabling Internet Proxy by FiddlerCore C# i am using Fiddler Core API to track the Web Traffic. I can trace all URLs but when I try to load a file (suppose http://url.com/path/xmlfilename.xml) from listed URL, then Its blocking Internet by making checkbox tick in Internet Explorer Proxy Setting. And its stops Internet Working. So please suggest what to do now?
Its happening always with me. I load full Web Traffic then I try to load .xml file from list, then suddenly it stops working. Because Internetexplorer Proxy will be enabled at this time.

A: FiddlerCore is a proxy; it works by pointing your browsers' proxy settings at itself. This is the default behavior, and this isn't what's causing the problem that you're encountering.
Please be more specific about what exactly it is that you're trying to do and what exactly is failing and how.

A: I have added code like this
--------
Fiddler.FiddlerApplication.AfterSessionComplete += FiddlerApplication_AfterSessionComplete;
Fiddler.FiddlerApplication.Startup(8764, Fiddler.FiddlerCoreStartupFlags.Default);
--------
void FiddlerApplication_AfterSessionComplete(Fiddler.Session oSession)
{
    setDataInTrackList(oSession);
}

In setDataInTrackList function i am reading session URL as below
oSession.fullUrl

and loading file manually to see the result. But I was not aware of this before that oSession has GetResponseBodyAsString() function, by which we can read the response from API itself.


text:
Q: how to add web view in tabbed activity android? I have seen lot of examples for  adding web view in Tabbed activity.but it's not fulfill my need.What I am trying is
Main Activity.java
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_statement);
      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      mSectionsPagerAdapter = new
      SectionsPagerAdapter(getSupportFragmentManager());
    // Set up the ViewPager with the sections adapter.
      mViewPager = (ViewPager) findViewById(R.id.container);
      mViewPager.setAdapter(mSectionsPagerAdapter);
      TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
      tabLayout.setupWithViewPager(mViewPager);
      name = getIntent().getStringExtra("Username");
  }
     public class SectionsPagerAdapter extends FragmentPagerAdapter {
       public SectionsPagerAdapter(FragmentManager fm) { super(fm) }
       @Override
       public Fragment getItem(int position) {
        switch(position){
            case 0 :
               TabFragment1 tab1=new TabFragment1(name);
                return tab1;
            case 1:
                TabFragment2 tab2 = new TabFragment2();
                return tab2;
            default:
                return null;
        } }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                 //new Daily().execute();
                return "Daily";
            case 1:
                //new Week().execute();
                return "Week";  }
        return null;
    }
 }

 @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            this.finish();
            return true;   }
    return super.onOptionsItemSelected(item);
}

TabFragment1.java
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroucontainer,
                         Bundle savedInstanceState) {
          tab1 = inflater.inflate(R.layout.tabfragment1, container, false);
          new Daily.execute();
          return tab1;
      }

        class Daily extends AsyncTask<String,Void,String> {
            String B = "";

            @Override
            protected String doInBackground(String... params) {
            RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(Sate_URL) //Setting the Root URL
                .build();
            DAPI api = adapter.create(DAPI.class);
            api.in(
                A,
                B,
                new Callback<Response>() {
                    @Override
                    public void success(Response result, Response response){
                        BufferedReader reader = null;
                        String output = "";
                        try {
                            //Initializing buffered reader
                            reader = new BufferedReader(new
                            InputStreamReader(result.getBody().in()))
                            output = reader.readLine();
                           } catch (IOException e) {
                            e.printStackTrace();
                        }
                        web = (WebView)tab1.findViewById(R.id.statement1);
                        web.setWebViewClient(new WebViewClient(){
                            ProgressDialog prDialog;

                            @Override
                            public void onPageStarted(WebView view, String
                              url, Bitmap favicon) {
                                prDialog =
                          ProgressDialog.show(getActivity(), null, "loading, please wait...");
                                super.onPageStarted(view, url, favicon);
                            }

                            @Override
                            public void onPageFinished(WebView view, String
                              url) {
                                prDialog.dismiss();
                                //
                            mySwipeRefreshLayout.setRefreshing(false);
                                super.onPageFinished(view, url);
                            }
                        });
                            web.loadUrl(URL);
                   }

                  @Override
                    public void failure(RetrofitError error) {
                        Toast.makeText(getActivity(), error.toString(),
                    Toast.LENGTH_LONG).show();  }
                });
                return null;
                }
            }

My tabfragment 2 is almost same like tabfragment 1.What i am trying to do is send two parameters to server and show the html content in webview.according to the parameter html table vary for both tab layout.i don't see operation in both layout.Any suggestions or guides will be appreciate.Thanks in advance.


text:
Q: Autocorrelation of 3D Points I'm trying to compute the autocorrelation of a list of points $(x,y,z)$ in 3D. Can the CorrelationFunction or maybe ListCorrelate be used to compute this?
rand = RandomReal[{0, 1}, {10, 3}];
CorrelationFunction[rand, 2]

I'm not sure what the output here means. Especially because I'm not sure what the hspec parameter is and what the documentation calls a lag. In my real data I suspect I have many roughly uniformly sized spherical regions with a higher density of points and was hoping an autocorrelation analysis could help find them and determine their size.
Since I'm interested in a spherically symmetric density I believe I can compute the autocorrelation like this
distmatrix2 =
  Compile[{{point, _Real, 1}, {tr, _Real, 2}}, Total@Abs[point - tr],
   CompilationTarget -> "C", RuntimeOptions -> "Speed",
   RuntimeAttributes -> {Listable}, Parallelization -> True];

pts = RandomReal[{0, 1}, {10000, 3}]; // AbsoluteTiming
distances = distmatrix2[pts, Transpose@pts]; // Timing
min = Min@Flatten@distances;
max = Max@Flatten@distances;

autocorrelation =
   Total@BinCounts[#, {min, max, (max - min)/100}] & /@
    distances; // AbsoluteTiming

However, I have 10^7 points in my real dataset and this is much too slow...


text:
Q: PHP - Unable to access certain elements with Simple XML Does SimpleXML only give access to elements with certain names? I've been trying to get the publish date from a few rss feeds which is possible when the date is contained inside of a pubDate tag, but I'm having trouble with feeds that hold their dates inside of a tag called "dc:date"
<dc:date>2013-12-12T22:30:46+00:00</dc:date>

When I print_r, the items looks like this
$rss = simplexml_load_file($source_url);

[0] => SimpleXMLElement Object
                    (
                        [title] => NEWS: Mayday Parade post 2014 Vans Warped Tour announcement video
                        [link] => http://www.altpress.com/news/entry/mayday_parade_post_2014_vans_warped_tour_announcement_video
                        [guid] => http://www.altpress.com/news/entry/mayday_parade_post_2014_vans_warped_tour_announcement_video
                    )

No sign of dc date. is this SimpleXML behaviour? How could I possibly access the date, the feed I'm accessing is this one: http://www.altpress.com/rss

A: As the SimpleXMLElement::children documentation states, you must explicitely provide namespace if you want to query any of the non-default (e.g. NULL) namespace children.
As an example consider:
$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<rss xmlns:dc="my.dc.urn">
    <channel>
        <item>
            <title>Tom And Jerry</title>
            <category>Comicbook</category>
            <dc:date>2013-12-12T22:30:46+00:00</dc:date>
        </item>
    </channel>
</rss>
';

$rss = simplexml_load_string($xml);

$item = $rss->channel[0]->item[0];

print_r($item->children());
//prints out "title" and "category"

print_r($item->children("dc", true));
//prints out "date" within the "dc" namespace (e.g. "dc:date")


text:
Q: fgetc gets invalid letters Im working on a encryption-decryption program, that uses a modified Vigenére cipher. Namely i switch out the Vigenere square after encrypting/decrypting 5 letters.
It works well if the text is short but with longer texts fgetc() starts returning invalid values, as if not the values that are actually present in the file im trying to decrypt.
At times it starts returning -1 and at times just invalid characters. Invalid being in the sense that if you check the file with a text editor there's something else there.
If you run the code the file creates 2 debug files in which you can compare what the one file outputted and what the other got from it.
This brakedown seems to usually happen around 250+ characters or so but it doesnt seem to happen at an exact same point. (ive had files where i get over 300 in and it still works). The password also seems to affect when it breaks down.
Code to encrypt:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>

main()
{
FILE* kuhu;
FILE* kust;
FILE* debug;

int i, pikktekst, sisse, o, u, passwpikk, passk, kus, valija, n;
char failinimi[100], passw[80];
char  matr2 [154][154], matr3[154][154];
int matr1[257][257];

debug = fopen("debugsisse.txt", "w");
//maatriks 1
//creates matrix for Vigenere Square
o = 0;
u=0;
for(i=0; o<=255; i++)
{
     matr1[o][i]= i+u;

     if(matr1[o][i]<0){matr1[o][i]= matr1[o][i]+255 ;
     }

           if(matr1[o][i]> 255)
                  {matr1[o][i]=matr1[o][i]-255;}
                  if(i==256)
               {o++; i=0; u++;}
}
   algusest:
   printf("Tere, Kui soovite teksti programmi sisestada vajutage s kui     failist\nsisestada vajutage f, juhul kui soovite v%cljuda vajutage x\n press f from file, s to enter here and x to quit\n", 132);
   sisse = getch();
   if(sisse == 'x'){exit(0);}
   if(sisse != 's' & sisse != 'f'){goto algusest;} //again if invalid input
   //juhul kui sisestatakse siia
   else if(sisse=='s'){kus =0;
        printf("Sisestage faili nimi kuhu soovite kr%cptida\n file where to encrypt:\n", 129); //file where to encrypt
        scanf("%s", &failinimi);
        kuhu = fopen(failinimi, "w");

                printf("Sisestage tekst mida soovite kr%cptida:\n text to encrypt\n", 129); //text to encrypt
                //is copied to file to get the length
                sisse=0;
                pikktekst = 0;
                for(i=0; sisse!=13; i++)
                                   {
                                   sisse=getch();
                                   printf("%c", sisse);
                                   pikktekst = i;
                                   fprintf(kuhu, "%c", sisse);
                                   }
                                fclose(kuhu);
            kuhu = fopen (failinimi, "r");

                                }

    //juhul kui failist if from wile
   else if(sisse == 'f'){
       kus=1;
        printf("\nPalun kontrollige et fail asub samas asukohas \nkus programm ja sisestage selle nimi:\n enter name of file:");
        scanf("%s", &failinimi);
        kuhu=fopen(failinimi, "r");
        i=0;

        sisse = fgetc(kuhu);
        for(pikktekst=0; sisse!=EOF ; pikktekst++) //checks the length of file to declare variables
        {sisse = fgetc(kuhu);
        }

        }

        //failist sisse
        int kryptikssisse[pikktekst+2], valjund[pikktekst+2]; //declares variables for input/output

                                   rewind(kuhu);

                                   for(i=0; i<pikktekst+1; i++)
                                   {
                                   kryptikssisse[i] = fgetc(kuhu);
                                   }
                                   fclose(kuhu);

   //prindib krüptitava asja ning pikkuse
   //prints the length of text to encrypt and what it is.
 // printf("\nkrüptikssisse on %s\n", kryptikssisse);
 // printf("pikkus on %d\n", pikktekst);

//kus toimub krüptimine
//encryption happens here

printf("%d  Palun sisestage oma v%chemalt viie t%chem%crgi pikkune salas%cna kr%cptimiseks:\n enter password (min 5)\n",kus, 132, 132, 132, 228, 129);
scanf("%s", passw);
passwpikk =  strlen(passw);
while(passwpikk<5)
{printf("Palun sisestage oma v%chemalt viie t%chem%crgi pikkune salas%cna kr%cptimiseks:\n", 132, 132, 132, 228, 129);
scanf("%s", passw);
passwpikk =  strlen(passw);
}
//if its from file the output file gets asked here
if(kus != 0){
printf("Sisestage faili nimi kuhu soovite kr%cptida\n", 129);
scanf("%s", &failinimi);}
kuhu = fopen(failinimi, "w");

//maatrikikirjutus
//prints out the matrix
/*
o=0; u=0;
for(i=0; o<=256; i++)
{        if( matr1[o][i] != 13 && matr1[o][i] != 10 ) { fprintf(kuhu, "%d ", matr1[o][i]); }
     else { fprintf(kuhu, "ENTER"); }
     if(i==257){fprintf(kuhu," %d \n", o); o++; u++; i=0;}
     }exit(0);

     */

n=0;
valija=0;
passk = 0;
for(o=0; o<pikktekst; o++)
{
n++;
if(n%5==0) //changes Square after 5 letters
{int x=0, y=0, z=0; // variables to make table
valija++;
if(valija > 255)
    {
    while(valija>255)
        {
        valija = valija - 255;
        }
    }
for(z=0; x<=255; z++) //creates new square, checks that nothing is higher or lower than 255
    {
    matr1[x][z]= z+y+valija;

    if(matr1[x][z]<0)
        {matr1[x][z]= matr1[x][z]+255 ;}

    if(matr1[x][z]> 255)
        {matr1[x][z]=matr1[x][z]-256;}
    if(z==256)
        {x++; z=0; y++;}
    }

}
//gives value to output
valjund[o]=matr1[passw[passk]][kryptikssisse[o]] /*+valija*/;
//checks that output isnt too little or large
while(valjund[o] < 0)
{valjund[o]= valjund[o]+256;
                 }
while(valjund[o] > 256)
{valjund[o]= valjund[o]-256; }
//prints output into debug file, with extra info AND the file the user specified
fprintf(kuhu, "%c", valjund[o]);
fprintf(debug, "%d :  %c (%d) --> %c (%d)\n",n, kryptikssisse[o], kryptikssisse[o], valjund[o], valjund[o]);
passk++;//checks password and resets if neccesary
if(passk>=passwpikk) {passk=0;}

}

fprintf(debug, "%s", kryptikssisse);
system("pause");

fclose(kuhu);
exit(0);
}

the code for the decryption is :
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <sys/stat.h>

main()
{ FILE* kust;
  FILE* kuhu;
  FILE* debug;
  debug = fopen("debug valja.txt", "w");
  fpos_t position;
int i, sisse, passwpikk, u, o, kord, nord, k;
char pw[50], sissef[80], valjaf[80];
int matr1[257][257];
printf("Mis failist soovite dekr%cptida?\n input file\n", 129);
scanf("%s", &sissef);
kust= fopen(sissef, "r");

struct stat st;
stat(sissef, &st);
int size = st.st_size;
printf("Size =%d", size);

printf("Kuhu soovite teksti panna?\n output file\n");
scanf("%s", &valjaf);
kuhu = fopen(valjaf, "wb");

//maatriks 1
//makes Vigenere Table
o = 0;
u=0;
for(i=0; o<=255; i++)
{
     matr1[o][i]= i+u;

     if(matr1[o][i]<0){matr1[o][i]= matr1[o][i]+255 ;
     }

           if(matr1[o][i]> 255)
                  {matr1[o][i]=matr1[o][i]-255;}
                  if(i==256)
               {o++; i=0; u++;}
}

//maatriksikirjutus
//prints Vigenere table
/*o=0; u=0;
for(i=0; o<=256; i++)
{if( matr1[o][i] != 13 && matr1[o][i] != 10 ) { fprintf(kuhu, "%d ", matr1[o][i]); }
     else { fprintf(kuhu, "ENTER"); }
     if(i==257){fprintf(kuhu," %d \n", o); o++; u++; i=0;}
     }exit(0);*/

printf("Palun sisestage oma salas%cna!\npassword\n", 228);
scanf("%s", &pw);
passwpikk =  strlen(pw);

//starts encrypting
int valjund=0;
sisse = 0;
sisse = fgetc(kust);

kord=0;
nord=1;
for(o=0; nord<size; nord++){

if(nord%5==0) //changes table
{int x=0, y=0, z=0;

kord++;
if(kord>255)
    {while(kord>255)
        {
        kord= kord - 255;
        }
    }

for(z=0; x<=255; z++)
    {
    matr1[x][z]= z+y/*+kord*/;

    if(matr1[x][z]<0)
        {matr1[x][z]= matr1[x][z]+255 ;}

    if(matr1[x][z]> 255)
        {matr1[x][z]=matr1[x][z]-256;}
    if(z==256)
        {x++; z=0; y++;}
    }
    //prints all matrixes that it uses; please not file can get very large and the programs uses A LOT of time.
    /*
    FILE* matr;
    matr = fopen("maatriksid", "a");
    fprintf(matr, "\n\n");
    z=0; x=0;
    for(i=0; z<=255; i++)
    {if( matr1[z][i] != 13 && matr1[z][i] != 10 ) { fprintf(matr, "%d ", matr1[z][i]); }
     else { fprintf(matr, "ENTER"); }
     if(i==256){fprintf(matr," %d \n", z); z++; x++; i=0;}
     }
    fclose(matr);
*/

}

i=pw[o];
for( u=0; sisse != matr1[i][u]; u++)
{
}
if(u==0)
{
 for( u=1; sisse != matr1[i][u]; u++)
 {
 }
}

//show when bad things happen
if(matr1[0][u]-kord<0)
{fprintf(debug, "shiiet");}

if(u>256){fprintf(debug, "  shit went to hell  ");}

valjund = matr1[0][u] - kord ;

/*
while(valjund < 0)
{
valjund= valjund+255;
}

while(valjund > 255)
{
valjund = valjund - 255;
}
*/

//prints stuff out

// note that the debug file prints the int sisse which shows exactly the letter that the program took from the file
fprintf(kuhu ,"%c", valjund);
fprintf(debug,"%d : %c (%d) --> %c (%d) u oli %d \n",nord, sisse, sisse, valjund, valjund, u);

//hoped reopening the file would help
//it didnt
fgetpos(kust, &position);
sisse = fgetc(kust);
if(sisse==-1)
{
fclose(kust);
kust = fopen(sissef, "r");
fsetpos(kust, &position);
sisse= fgetc(kust);
}

//checks password
o++;
if(o>=passwpikk){o=0;}

}
//prints the password at the end of debug file
fprintf(debug,"\n%s", pw);
printf("valmis\n done\n");
system("pause");
exit(0);
}


text:
Q: vscode python unresolved reference to module in subfolder when using venv and language server I've opted to use the Python Language Server instead of Jedi.
My project root folder has a subfolder named "cdk_app", and in that folder is file cdk_app_stack.py.  That file defines class "Lemoncello"
in the project root folder my file app.py has this line:
from cdk_app.cdk_app_stack import Lemoncello

"cdk_app.cdk_app_stack" is marked by vscode as an unresolved reference. (but it runs properly.)
if I change it to
cdk_app_stack import Lemoncello

(removed the folder qualifier) vscode resolves it ok (and it runs ok)
this is only an issue when I use the project venv.  When not, both syntax resolve and run.
Why is the reference unresolvable when I specify the subfolder name, when using a venv?
Thanks all.

A: The problem involved easy-install.pth in my python site-packages folder.  This file was created by the AWS CDK installer (I believe).  It had a reference to the venv subfolder. This is all quite proper, but the Python Language Server doesn't handle it well. If I removed this pth file, the problem went away.  Of course, that's just a workaround, and Python Language Server will presumably work better in this scenario, someday.
For some chatter about a different language server issue with pth files, see https://github.com/microsoft/python-language-server/issues/537
To turn off the language server, configure vscode as "python.jediEnabled": true (which is the default.)


text:
Q: Execute Powershell Script from C# with users input command line I created a website that does remotely execute powershell to specific server. I would like to know how it work to pass 2 user selected values to commandline from dropdownlist on asp.net website along with powershell script file?
I already have working code with powershell script file but now adding 2 arguments in script file.The powershell arguments is,
    [string]$ContainerIn=$args[0]
[int]$ips2get=$args[1]

Here a C# working codes,
//These 3 input varaibles will pass to powershell script to get specific results
        string env = "";
        string container = "";
        string numIPs = "";

        //assign dropdown selected value to variable to pass to script
        container = DropDownListContainer.SelectedValue;
        numIPs = DropDownListIP.SelectedValue;

        if (container == "H02" || container == "H07" || container == "H08")
        {
            env = "Prod";
        }
        else
        {
            env = "NonProd";
        }

        // Create a Powershell
        Runspace runSpace = RunspaceFactory.CreateRunspace();
        runSpace.Open();
        Pipeline pipeline = runSpace.CreatePipeline();

        Command invokeScript = new Command("Invoke-Command");

        RunspaceInvoke invoke = new RunspaceInvoke();

        //Add powershell command/script functions into scriptblock
        //Somewhere on this codes that it need to add command line to go with Get-FreeAddress.ps1 file script

        ScriptBlock sb = invoke.Invoke(@"{D:\Scripts\Get-FreeAddress.ps1}")[0].BaseObject as ScriptBlock;
        //ScriptBlock sb = invoke.Invoke("{" + PowerShellCodeBox.Text + "}")[0].BaseObject as ScriptBlock;

        invokeScript.Parameters.Add("scriptBlock", sb);
        invokeScript.Parameters.Add("computername", TextBoxServer.Text);

        pipeline.Commands.Add(invokeScript);

        Collection<PSObject> output = pipeline.Invoke();

        //splitting results in new lines
        foreach (PSObject psObject in output)
        {

            str = str + psObject + "\r\n";
            //str = psObject + "\r\n";
            //str += "\n" + psObject;
            //str = str + Environment.NewLine + psObject;

        }

        if (str == "")
        {
            str = "Error";

            ResultBox.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF0000");
        }

        //print out powershell output result
        ResultBox.Text = str;

    }

A: I finally made this work,
I just need to modify to
ScriptBlock sb = invoke.Invoke(@"{D:\Scripts\Get-FreeAddress.ps1 '"+container+"' "+numIPs+"}")[0].BaseObject as ScriptBlock;

The powershell script argument will get container and numIPs variables.


text:
Q: 'NoneType' object has no attribute 'remove_roles' Discord.py Keep getting an error for the reaction_remove, just copy-pasted my whole code(minus the client id) cause it might help, I have no idea what's wrong as the first half works perfectly fine.
Also, trying to add
"if member is not None:
await member.remove_roles(role)
else:
Print(error)"
at the very end and itgave me errors every time I tried removing roles, just in case it helps.
import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_raw_reaction_add(payload):
    message_id = payload.message_id

    if message_id == 806406876593127464:
        guild_id = payload.guild_id
        guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
        if payload.emoji.name == "049":
            role = discord.utils.get(guild.roles, name = 'SCP-049')
        elif payload.emoji.name == "0492":
            role = discord.utils.get(guild.roles, name = 'SCP-049-2')
        elif payload.emoji.name == "096":
            role = discord.utils.get(guild.roles, name = 'SCP-096')
        elif payload.emoji.name == "106":
            role = discord.utils.get(guild.roles, name = 'SCP-106')
        elif payload.emoji.name == "173":
            role = discord.utils.get(guild.roles, name = 'SCP-173')
        elif payload.emoji.name == "682":
            role = discord.utils.get(guild.roles, name = 'SCP-682')
        elif payload.emoji.name == "939":
            role = discord.utils.get(guild.roles, name = 'SCP-939')
        elif payload.emoji.name == "999":
            role = discord.utils.get(guild.roles, name = 'SCP-999')
        elif payload.emoji.name == "Chaos":
            role = discord.utils.get(guild.roles, name = 'Chaos Insurgency')
        elif payload.emoji.name == "DClass":
            role = discord.utils.get(guild.roles, name = 'D-Class')
        elif payload.emoji.name == "MTF":
            role = discord.utils.get(guild.roles, name = 'MTF')
        elif payload.emoji.name == "Scientist":
            role = discord.utils.get(guild.roles, name = 'Scientist')

        member = payload.member
        await member.add_roles(role)

@client.event
async def on_raw_reaction_remove(payload):
    message_id = payload.message_id

    if message_id == 806406876593127464:
        guild_id = payload.guild_id
        guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
        if payload.emoji.name == "049":
            role = discord.utils.get(guild.roles, name = 'SCP-049')
        elif payload.emoji.name == "0492":
            role = discord.utils.get(guild.roles, name = 'SCP-049-2')
        elif payload.emoji.name == "096":
            role = discord.utils.get(guild.roles, name = 'SCP-096')
        elif payload.emoji.name == "106":
            role = discord.utils.get(guild.roles, name = 'SCP-106')
        elif payload.emoji.name == "173":
            role = discord.utils.get(guild.roles, name = 'SCP-173')
        elif payload.emoji.name == "682":
            role = discord.utils.get(guild.roles, name = 'SCP-682')
        elif payload.emoji.name == "939":
            role = discord.utils.get(guild.roles, name = 'SCP-939')
        elif payload.emoji.name == "999":
            role = discord.utils.get(guild.roles, name = 'SCP-999')
        elif payload.emoji.name == "Chaos":
            role = discord.utils.get(guild.roles, name = 'Chaos Insurgency')
        elif payload.emoji.name == "DClass":
            role = discord.utils.get(guild.roles, name = 'D-Class')
        elif payload.emoji.name == "MTF":
            role = discord.utils.get(guild.roles, name = 'MTF')
        elif payload.emoji.name == "Scientist":
            role = discord.utils.get(guild.roles, name = 'Scientist')

        member = payload.member
        await member.remove_roles(role)
client.run()

It was able to give me a role after adding a reaction, but has not been able to remove the role after removing that reaction here

A: If you try printing the payload.member the output will be None  - it's because you didn't enable intents.members. To enable them:
intents = discord.Intents.default()
intents.members = True

client = discord.Client(intents=intents)

Also make sure to enable intents in the developer portal
How to enable privileged intents

A: The below answer is one part of the solution to make this code work so implement the provided answer. I found out in another issue that in the documentation payload.member is only available if the event_type is REACTION_ADD so i fixed it by adding:
intents = discord.Intents.default()
intents.members = True

client = discord.Client(intents=intents)

After you have added this, change the
member = payload.member

to
member = guild.get_member(payload.user_id)

That is what worked for me let me know if this helps.

A: I dont know if this is still an active problem, but I had the same problem and solved it right now after some time and wanted to share with you how I have done this.
I hope i could help other peoble with this.
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)

↑ Add this at the top of your code right under imports

@bot.event
async def on_raw_reaction_add(payload):
    guild = bot.get_guild(payload.guild_id)
    member = payload.member
    emoji = payload.emoji.name
    channel = discord.utils.get(guild.channels, name='regeln')
    channel_id = channel.id
    message_id = 874741218523873370

    if message_id == payload.message_id:
        if payload.channel_id == channel_id:
            if emoji == '1⃣':
                role = discord.utils.get(guild.roles, name='News1')
            if emoji == '2⃣':
                role = discord.utils.get(guild.roles, name='News2')
            if emoji == '3⃣':
                role = discord.utils.get(guild.roles, name='News3')
            if emoji == '4⃣':
                role = discord.utils.get(guild.roles, name='News4')
        await member.add_roles(role)

@bot.event
async def on_raw_reaction_remove(payload):
    guild = bot.get_guild(payload.guild_id)
    member = guild.get_member(payload.user_id)
    emoji = payload.emoji.name
    channel = discord.utils.get(guild.channels, name='regeln')
    channel_id = channel.id
    message_id = 874741218523873370

    if message_id == payload.message_id:
        if payload.channel_id == channel_id:
            if emoji == '1⃣':
                role = discord.utils.get(guild.roles, name='News1')
            if emoji == '2⃣':
                role = discord.utils.get(guild.roles, name='News2')
            if emoji == '3⃣':
                role = discord.utils.get(guild.roles, name='News3')
            if emoji == '4⃣':
                role = discord.utils.get(guild.roles, name='News4')
        await member.remove_roles(role)

A: payload.member will always be None when the event is on_raw_reaction_remove. As such, you will have to use guild.get_member() and the payload's user_id to obtain the member from cache, which also requires having the members intent enabled.


text:
Q: FluentValidation rules chaining not stopping at first failure I have a model:
public class DTO
{
    public int[] StatementItems { get; set; }
}

Which I want to validate that:

*

*StatementItems is not null

*StatementItems is not empty

*StatementItems does not contain any duplicate IDs

The validation rule chain I created is:
RuleFor(x => x.StatementItems).NotNull().NotEmpty().Must(x => x.Distinct().Count() == x.Count());

And I have a test as:
_validator.ShouldHaveValidationErrorFor(x => x.StatementItems, null as int[]);

When I run the test passing in a null value, I would expect it to fail on the first rule of the chain (NotNull()) and stop there. However, it complains that the lamda value used in the Must() is null.
Am I wrong in thinking that the Must() shouldn't be run if the NotNull() fails? If so, how should this rule be written?
Thanks

A: Check out FluentValidation's cascade mode. You can make it short-circuit on the first failure like this:
this.RuleFor(x => x.StatementItems)
   .Cascade(CascadeMode.Stop)
   .NotNull()
   .NotEmpty()
   .Must(x => x.Distinct().Count() == x.Count());

Also, you can configure this in your AbstractValidator subclass's constructor. Then you won't need to put it on every rule.
public MyInputValidator()
{
  this.CascadeMode = CascadeMode.Stop;
}

A: Although @NPras's answer did supply my with a solution, I didn't like the fact that I'm duplicating the NotNull rule. After a bit more research on FluentValidation I have implemented it using DependentRules:
RuleFor(x => x.StatementItems).NotNull().NotEmpty()
            .DependentRules(d =>
                d.RuleFor(x => x.StatementItems).Must(x => x.Distinct().Count() == x.Count())
            );

So now the Must condition is only fired when the previous two rules are valid.

A: I don't see in the FluentValidation documentation that it actually guarantees short-circuiting.
If you look in its source:
public virtual ValidationResult Validate(ValidationContext<T> context)
{
  ...
  var failures = nestedValidators.SelectMany(x => x.Validate(context));
  return new ValidationResult(failures);
}

It will run through *all* the validators (with the SelectMany()) and returns a list of errors.
Your only option seems to be to force a check on your Must rule.
.Must(x => x!= null && x.Distinct().Count() == x.Count())
//or, fluently:
.Must(x => x.Distinct().Count() == x.Count()).When(x => x! = null)

EDIT:
I was going to suggest that since Validate() is virtual, you could just override it in your validator to make it short-circuit. But then I realised that the nestedValidators list is private. So yeah, no..


text:
Q: piping multiple statements together only performs first command edit half of the problem has been fixed and the question has been edited to reflect that fixing. I still am only seeing this perform the first command in a series of pipes.
I am stuck on the very last thing in my shell that I am making from scratch. I want to be able to parse commands like "finger | tail -n +2 | cut -c1-8 | uniq | sort" and I think that I am close. What I have right now, when given that line as an array of strings, only executes the "finger" part.
Here is the part of code that isn't working as it needs to be, I've narrowed it down to just this for loop and the part after:
mypipe[2];
//start out with stdin
oldinfd = 0;

   //run the beginning commands. connect in/out of pipes to eachother.
   for(int i = 0; i < max; i++){

      pipe(mypipe);

      processline(commands[i], oldinfd, mypipe[1]); //doesn't wait on children

      close(mypipe[1]);

      oldinfd = mypipe[0];

   }

   //run the final command, put output into stdout
   processline(commands[max], oldinfd, 1);  //waits on children

   ...

This loop runs the program and should end up looking like this:
stdin -> [0]pipe[write] -> [read]pipe[write] -> ... ->[read]pipe[1] -> stdout
My processline function takes in a line ('finger') and execs it. for instance, processline("finger", 0, 1) run the finger command without flaws. For the purposes of this question assume that processline works perfectly, what I'm having troubles with is how I'm using the pipes and their write and read ends.
Also with print statements, I have confirmed that the correct words are being sent to the correct parts. (the for loop receives "finger", "tail -n +2", "cut -c1-8", and "uniq", while the commands[max] that the last line receives is "sort").


text:
Q: An error occured while executing doInBackground() Twitter4J I am using the Twitter4J Library and I am trying to implement some Async Tasks to make some calls to the service as follows.
public class TweetsActivity extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_post_tweet);
    new getFollowers().execute();

}
@SuppressWarnings("unused")
private class getFollowers extends AsyncTask<String,Void,List<String>>
{

    @Override
    protected List<String> doInBackground(String... arg0) {
        List<String> friends = null;
        Twitter t = ((TwitterApplication)getApplication()).getTwitter();
        try {
            IDs names  = t.getFollowersIDs("jd_biggestboss");
            for(int i:names.getIDs())
            {
                friends.add(t.showUser(i).getScreenName());

            }
            return friends;
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }// TODO Auto-generated method stub
        return null;
    }

    protected void onPostExecute(List<String> result) {
        for(String name:result)
            System.out.println(name);

     }

}

}

I am getting an error.This is the stack trace. I checked to ensure that I was not accessing any UI elements from my UI thread and so on. So what could be causing the problem? Could it be that each call that I make to the API needs to be in a separate Async task? Thanks in advance.
01-27 02:22:58.042: W/dalvikvm(30528): threadid=11: thread exiting with uncaught exception (group=0x40ab0a08)
01-27 02:22:58.052: E/AndroidRuntime(30528): FATAL EXCEPTION: AsyncTask #1
01-27 02:22:58.052: E/AndroidRuntime(30528): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 02:22:58.052: E/AndroidRuntime(30528):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at java.lang.Thread.run(Thread.java:864)
01-27 02:22:58.052: E/AndroidRuntime(30528): Caused by: java.lang.NullPointerException
01-27 02:22:58.052: E/AndroidRuntime(30528):    at com.tmm.android.twitter.TweetsActivity$getFollowers.doInBackground(TweetsActivity.java:40)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at com.tmm.android.twitter.TweetsActivity$getFollowers.doInBackground(TweetsActivity.java:1)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
01-27 02:22:58.052: E/AndroidRuntime(30528):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 02:22:58.052: E/AndroidRuntime(30528):    ... 5 more

A: you will need to initialize the friends ArrayList before adding elements to it inside doInBackground method :
List<String> friends = new ArrayList<String>();


text:
Q: A Generating Set and Its Image in the Frattini Quotient This is a homework question I am having some trouble with.
The claim I'm trying to prove is this: Let $\Phi$ be the Frattini subgroup of a finite group $G$. If $S$ is a subset of $G$, and $\bar{S}$ is the image of $S$ under $G\rightarrow G/\Phi$, then $S$ generates $G$ if and only if $\bar{S}$ generates $G/\Phi$.
I have already shown that $\Phi$ is the set of non-generators of $G$. My inclination is to proceed by cases involving whether or not $S$ is itself contained in a maximal subgroup. Any help would be appreciated.

A: Obviously if $S$ generates $G$ then $\overline{S}$ generates $G/\Phi$.  On the other hand, if $\overline{S}$ generates $G/\Phi$, then $S$ and $\Phi$ together generate $G$.  But $\Phi$ is the set of nongenerators, so ...


text:
Q: How to protect auto-generated sources during clean package in maven? I have a maven config file that triggers autogeneration of xsd and wsdl classes as follows:
    <plugin>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-xjc-plugin</artifactId>
        <version>${cxf-xjc-plugin}</version>
        <executions>
            <execution>
                <id>generate-sources</id>
                <phase>generate-sources</phase>

                <configuration>
                    <sourceRoot>${project.build.directory}/generated/src/main/java</sourceRoot>
                    <xsdOptions>
                        //xsds, wsdls etc
                    </xsdOptions>
                </configuration>
                <goals>
                    <goal>xsdtojava</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

The generated classes go to: target/generated/src/main/java.
Problem: running 'mvn clean package' will always remove those classes. How can I prevent it? Is it possible having clean remove the full content of the target directory apart from the generated/ one?

A: It is possible not to delete some directory using maven-clean-plugin but this is definitely not a good idea:

*

*it goes against Maven conventions

*it forces you to change your POM everytime you want those classes to be generated

Solution to your exact question (NOT RECOMMENDED)
You can exclude directories with the maven-clean-plugin using excludeDefaultDirectories and filesets parameters:
<plugin>
    <artifactId>maven-clean-plugin</artifactId>
    <version>2.6.1</version>
    <configuration>
        <excludeDefaultDirectories>true</excludeDefaultDirectories>
        <filesets>
            <fileset>
                <directory>${project.build.directory}</directory>
                <excludes>
                    <exclude>generated/*</exclude>
                </excludes>
            </fileset>
        </filesets>
    </configuration>
</plugin>

Note that I strongly urge you NOT to use this solution.
Proposed solution
Your actual problem is not to re-generate the classes everytime you build because it takes a lot of time. The goal is then to avoid generation by using a custom profile:
<profiles>
    <profile>
        <id>noGenerate</id>
        <properties>
            <xjc.generate>none</xjc.generate>
        </properties>
    </profile>
    <profile>
        <id>generate</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <xjc.generate>generate-sources</xjc.generate>
        </properties>
    </profile>
</profiles>

With the following plugin definition:
<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-xjc-plugin</artifactId>
    <version>${cxf-xjc-plugin}</version>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>${xjc.generate}</phase>
            <configuration>
                <sourceRoot>${project.build.directory}/generated/src/main/java</sourceRoot>
                <xsdOptions>
                    //xsds, wsdls etc
                </xsdOptions>
            </configuration>
            <goals>
                <goal>xsdtojava</goal>
            </goals>
        </execution>
    </executions>
</plugin>

It seems cxf-xjc-plugin does not have any skip parameter so we have to resort to setting the phase to none when we want to avoid execution (this is an undocumented feature but it works).
The trick is to define two profiles: one, activated by default, sets a property telling the cxf-xjc-plugin to execute in the generate-soures phase, while the other one sets a property telling the cxf-xjc-plugin not to execute.
As such, when you want to classes to be generated, you can invoke Maven with mvn clean install and when you want the classes not to be generated, you can invoke Maven with mvn clean install -PnoGenerate.
The real gain and advantage here is that you do not need to change your POM everytime you decide to generate or not the classes.

A: I would have another approach.
1st) Configure your xjc plug-in to not erase any files i.e.:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.2</version>
<executions>
    <execution>
        <goals>
            <goal>xjc</goal>
        </goals>
    </execution>
</executions>
<configuration>
    <clearOutputDir>false</clearOutputDir>
    <outputDirectory>${project.build.directory}</outputDirectory>
    <sources>
        <source>  [any xsd] </source>
    </sources>
</configuration>

2nd) Use maven-clean-plugin to clean jxc class generated dir in clean stage:
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
<configuration>
    <filesets>
        <fileset>
            <directory>${basedir}/generated/src/main/java/...where the generated classes are</directory>
            <includes>
                <include>**/*.java</include>
            </includes>
            <followSymlinks>false</followSymlinks>
        </fileset>
    </filesets>
</configuration>

This works for me and I hope would be useful.


text:
Q: Can a snowflake task trigger a python script? I need to perform series of action after the data load is completed from snowpipe to the landing area and want to make it run on its own. Please suggest if you see any other option here if not tasks.

A: You can, but not directly. You may want to look at external functions.
Snowflake supports  external functions which can call a cloud api and therefore run any code that you are able to expose via a supported API.
The hyperlinked article gives a walk-through of creating an external function that you can adapt to suit your needs:
This walk-through is specific to AWS, but there are options for Azure and GCP
Platforms that Support Calling an External Function
In general, an external function can be called from a Snowflake account on any cloud platform that Snowflake supports:

*

*Amazon Web Services (AWS)

*Microsoft Azure

*Google Cloud Platform (GCP)

The steps you have to take to ensure appropriate security won't fit here:
however in summary you do the following:

*

*Create an AWS IAM service role to execute all of the Lambda
functions

*Create AWS Lambda functions for our examples

*Create an AWS
API gateway to expose the Lambda functions to Snowflake

*Create an
AWS IAM role to access the API gateway and configure it to access
both the API gateway and a Snowflake API integration object

*Create
and test some external function objects in Snowflake

Sample Code
CREATE OR REPLACE external function external_functions.lambda.sum(filename varchar, rowcount number)
  returns variant
  api_integration = aws_lambda
  as '<https://xxxxxxxxxx.execute-api.eu-west-2.amazonaws.com/snowflake-external-function-stage/snowflake-sum>'

If you decide to leverage external functions:
You may create a task, which runs a stored procedure.
This stored procedure could for read from your load history:
SELECT
*
FROM
(
select * from table(information_schema.copy_history(table_name=>'abc.mytable', start_time=> dateadd(hours, -1, current_timestamp())))
) q
WHERE q.PIPE_NAME ilike 'mypipe'
;

And use the output from the copy history to call your external function.
This external function could trigger any action that you can program on your cloud provider. This would be a "serverless" option.
If you are running on-premise / on a cloud vm. You can write a python script that runs in airflow / cron, that processes your copy history and run the next set of actions.


text:
Q: jquery how can pass variable between two each Is it possible to pass variable between two each in jquery
this my code
    var gcolor;
    $('input[id^="cat-color"]').each(function() {
        function rgb2hex(rgb){
         rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
         return "#" +
          ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
          ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
          ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
        }
        var gcolor = rgb2hex($(this).css( "color" ));

    });
    $('a.wp-color-result').each(function() {
        //console.log(gcolor);
        $(this).css('background-color', gcolor);
    });

html just one category there is 14 category

Android

Color :

            <input type="text" value="" placeholder="" name="mwp_newsbt[cat-color20][color]" id="cat-color20" class="color regular-text wp-color-picker" style="display: none; color: rgb(153, 153, 153);"><input type="button" class="button button-small wp-picker-clear hidden" value="Clear">

Background :

            <input type="text" value="" placeholder="" name="mwp_newsbt[cat-color20][background]" id="cat-color20" class="color regular-text wp-color-picker" style="display: none; color: rgb(153, 153, 153);"><input type="button" class="button button-small hidden wp-picker-clear" value="Clear">

Border :

            <input type="text" value="" placeholder="" name="mwp_newsbt[cat-color20][border]" id="cat-color20" class="color regular-text wp-color-picker" style="display: none; color: rgb(153, 153, 153);"><input type="button" class="button button-small hidden wp-picker-clear" value="Clear">

html http://pastebin.com/XSAw9bY5
i see in console log undefined for gcolor
the problem with colorpicker when i save change (ajax) The colour of the toggle is updated as the cursor is moved but disappears when the page refreshes
when is choose color and save change
http://img11.hostingpics.net/pics/159977categorycolor2.png

A: try nesting those two for each functions like this:
$('input[id^="cat-color"]').each(function() {
        function rgb2hex(rgb){
         rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
         return "#" +
          ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
          ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
          ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
        }
        var gcolor = rgb2hex($(this).css( "color" ));
        $('a.wp-color-result').each(function(gcolor) {
        //console.log(gcolor);
        $(this).css('background-color', gcolor);
    });
});

A: This will set the color of the a.wp-color-result element in the same category as the cat-color element:
function rgb2hex(rgb){
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    return "#" +
        ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
        ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
        ("0" + parseInt(rgb[3],10).toString(16)).slice(-2);
}
$('input[id^="cat-color"]').each(function() {
    var gcolor = rgb2hex($(this).css( "color" ));
    $(this).closest(".color-category-wrap").find('a.wp-color-result').css('background-color', gcolor);
});