text:
Q: Attempting to send a combination keystroke (Shift RightArrow) or trigger an event JQ 2.0.3 I have an accepted answer but am open to better ones
Be gentle, this is my first question here
I am building a web browser plugin to automate a series of processes for my organization. I pretty much have everything handled but this one problem that I have been stuck on for two days... and its like really simple I think.
In a lookup field in our ERP, you must press Shift + Right to cycle through certain options.
I am attempting to trigger this or send this any kind of way that I can.
Jquery version 2.0.3

*

*The required event only fires on key up

*The required event is not firing when I simulate input

*I suspect it needs to be targeted at the input, or perhaps its related to not being trusted/being simulated

*It occurs to me, that as I am using a browser extension, perhaps it is something I can simulate from this? I dont know if thats a good way to put it... I wonder what the extension could do here that plain JS or JQ on a page could not.

*Update(Dec 11): So per above thought, I am looking into modifying the Jquery framework that is being used. I have saved a local copy as an local override and used these two resources to implement.

*Override Javascript file in chrome

*https://www.ghacks.net/2018/02/27/make-permanent-changes-to-web-pages-with-chromes-overrides-dev-tool/

*I am in process of determining if local overrides are persistent (Edit: they appear to be after restart of computer, lets see if its a long term solution) but I was able to console.log my code and see it in the console.

*Next steps will be modifying the handler to perform the actions I need. and/or feed the information I want fed to the system.

*Update(Dec 12): probably dont need to override the whole file with this answer how to override a javascript function
Here is my function that triggers the event handler (with no result) which was modified from here
function simulateKey (currentTarget, isTrusted, key, code, keyCode, type, modifiers) {
    var evtName = (typeof(type) === "string") ? "key" + type : "keydown";
    var modifier = (typeof(modifiers) === "object") ? modifier : {};
    console.log("In simulate key function");
    var event = document.createEvent("HTMLEvents");
    event.initEvent(evtName, true, false);
    event.keyCode = keyCode;
    event.key = key;
    event.code = code;
    event.isTrusted = isTrusted;
    event.Target = currentTarget;

    for (var i in modifiers) {
        event[i] = modifiers[i];
    }

    document.dispatchEvent(event);
}

Here is how I use it (a little hardcoded at the moment, just for testing purposes)
function changeLookup(Lookup) {
    console.log("Change Lookup");

    var event_object = Lookup;
    console.log("Key Event Firing");
    $("input[data-name='Entity.Customer.Key']").focus();
    simulateKey(Lookup, true, "ArrowRight", "ArrowRight", 39, "up", {shiftKey: true });
    console.log("Key Event Fired");
}

I have looked at or tried the following solutions

*

*Trigger a built in event in javascript?

*Arrow key pressed while shift key is held down

*Is it possible to simulate key press events programmatically?

*How to trigger event in JavaScript?

*Execute Key Press Event

*Firing a Keyboard Event in Safari, using JavaScript
I have reviewed the following documentation

*

*https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

*https://developer.mozilla.org/en-US/docs/Web/API/Event

*https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
I am at my wits end here...

A: The answer was found here Keydown Simulation in Chrome fires normally but not the correct key
I modified it to keyup and juggled some of the parameters so the shift key was pressed... Seems like OP in the other thread did some strange stuff with the parameters in such a way as to press ctrl and shift... So I fixed that for the initKeyboardEvent but not for initKeyEvent
keyUpEventSim = {};
    keyUpEventSim.keyup = function(target, k, ctrlKey, altKey, shiftKey, metaKey) {
        var oEvent = document.createEvent('KeyboardEvent');

        // Chromium Hack
        Object.defineProperty(oEvent, 'keyCode', {
                    get : function() {
                        return this.keyCodeVal;
                    }
        });
        Object.defineProperty(oEvent, 'which', {
                    get : function() {
                        return this.keyCodeVal;
                    }
        });

        if (oEvent.initKeyboardEvent) {
            oEvent.initKeyboardEvent("keyup", true, false, document.defaultView, false, false, ctrlKey, altKey, shiftKey, metaKey);
        } else {
            oEvent.initKeyEvent("keyup", true, false, document.defaultView, false, false, true, false, k, 0);
        }

        oEvent.keyCodeVal = k;

        if (oEvent.keyCode !== k) {
            alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
        }

        target.dispatchEvent(oEvent);
    }

called it as follows
function changeLookup(Lookup) {
    Lookup.focus();
    keyUpEventSim.keyup(Lookup,39, false, false, true, false);
}


text:
Q: Unsure of where to add certain piece of code I have written some code which allows me to get user input for games a user has played. I have done most of it, however I have come to a point where I do not know where to add this code totalScore = totalScore + score;. This code will get me the total score of the player each time they add a new game. As well as this I am also confused about how to get a total amount of invalid entries which a user has tried to enter, meaning for each invalid entry I need to keep count of it so I can later display the total amount of invalid entries.
import java.util.Scanner;
public class REQ3
{
    public static void main (String[] args)
    {

     String playername;
     String line;
     String[] list = new String[100];
     int count = 0;
     int score;
     int time;
     int gamesplayed =0;
     int totalScore =0;

     Scanner sc = new Scanner(System.in);

      System.out.println("Please enter your name");

      playername = sc.nextLine();

      if(playername.equals(""))
      {
          System.out.println("Player name was not entered please try again");
          System.exit(0);
      }

      System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");

      while (count < 100){

             line = sc.nextLine();

             if(line.equals("quit")){
                  break;
                  }
            if(line.equals("")){
                System.out.println("Nothing was entered please try again");
                  break;
                  }

            if(!(line.contains(":"))){
                System.out.println("Please enter achivements with the proper \":\" sepration\n");
                break;
            }

             list[count]=line;
            System.out.println("list[count]" + list[count]);

            count++;
            gamesplayed++;

        for (int i=0; i<count; i++){
          line=list[i];
          String[] elements =line.split(":");

          if (elements.length !=3){
                System.out.println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
                   break;
          }

          try {
                score = Integer.parseInt(elements[1].trim());
                                totalScore = totalScore + score; // added here
            } catch(NumberFormatException ex) {
                System.out.println("Incorrect score data, Please enter a valid integer");
            }
          try {
              time=Integer.parseInt(elements[2].trim());
            } catch(NumberFormatException ex) {
                System.out.println("Incorrect time data, Please enter a valid integer");
            }

        }
    }
      System.out.println("Player : " + playername);
      System.out.println("--------------------------------");
      System.out.println("Games Played: " +gamesplayed);
}

}

A: I dont know why you are using a for loop . You should remove the for loop and do totalScore after reading score
import java.util.Scanner;

public class REQ3 {
    public static void main(String[] args) {

        String playername;
        String line;
        String[] list = new String[100];
        int count = 0;

        int time;
        int gamesplayed = 0;
        int totalScore = 0;

        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter your name");

        playername = sc.nextLine();

        if (playername.equals("")) {
            System.out.println("Player name was not entered please try again");
            System.exit(0);
        }

        System.out.println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");

        while (count < 100) {

            line = sc.nextLine();

            if (line.equals("quit")) {
                break;
            }
            if (line.equals("")) {
                System.out.println("Nothing was entered please try again");
                break;
            }

            if (!(line.contains(":"))) {
                System.out.println("Please enter achivements with the proper \":\" sepration\n");
                break;
            }

            list[count] = line;
            System.out.println("list[count]" + list[count]);

            count++;
            gamesplayed++;

            String[] elements = line.split(":");

            if (elements.length != 3) {
                System.out.println(
                        "Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
                break;
            }

            try {
                int score = Integer.parseInt(elements[1].trim());
                totalScore += score;
            } catch (NumberFormatException ex) {
                System.out.println("Incorrect score data, Please enter a valid integer");
            }
            try {
                time = Integer.parseInt(elements[2].trim());
            } catch (NumberFormatException ex) {
                System.out.println("Incorrect time data, Please enter a valid integer");
            }

        }
        System.out.println("Player : " + playername);
        System.out.println("--------------------------------");
        System.out.println("Games Played: " + gamesplayed);
        System.out.println("total score: " + totalScore);
    }
}

A: Agree with awesome not sure why you need inner for loop. Below is the solution which work for both invalid entries and total score.
import java.util.Scanner;

public class REQ3 {

    public static void main(String[] args) {

        String playername;
        String line;
        String[] list = new String[100];
        int count = 0;
        int score = 0;
        int time;
        int gamesplayed = 0;
        int totalScore = 0;
        int invalidEntries = 0;

        Scanner sc = new Scanner(System.in);

        System.out.println("Please enter your name");

        playername = sc.nextLine();

        if (playername.equals("")) {
            System.out.println("Player name was not entered please try again");
            System.exit(0);
        }

        System.out
                .println("Please enter your game achivements (Game name:score:time played) E.g. Minecraft:14:2332");

        while (count < 100) {

            line = sc.nextLine();

            if (line.equals("quit")) {
                break;
            }
            if (line.equals("")) {
                System.out.println("Nothing was entered please try again");
                invalidEntries++;
                continue;
            }

            if (!(line.contains(":"))) {
                System.out
                        .println("Please enter achivements with the proper \":\" sepration\n");
                invalidEntries++;
                continue;
            }

            list[count] = line;
            System.out.println("list[count]" + list[count]);
            String[] elements = line.split(":");

            if (elements.length != 3) {
                System.out
                        .println("Error please try again, Please enter in the following format:\nGame name:score:timeplayed");
                invalidEntries++;
                continue;
            }

            try {
                score = Integer.parseInt(elements[1].trim());
            } catch (NumberFormatException ex) {
                System.out
                        .println("Incorrect score data, Please enter a valid integer");
                invalidEntries++;
                continue;
            }
            try {
                time = Integer.parseInt(elements[2].trim());
            } catch (NumberFormatException ex) {
                System.out
                        .println("Incorrect time data, Please enter a valid integer");
                invalidEntries++;
                continue;
            }
            count++;
            gamesplayed++;
            totalScore = totalScore + score;
        }
        System.out.println("Player : " + playername);
        System.out.println("--------------------------------");
        System.out.println("Games Played: " + gamesplayed);
        System.out.println("Total Score: " + totalScore);
        System.out.println("Invalid Entries: " + invalidEntries);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing the basis to non standard in a linear transformation Here is the given question:
Consider the linear transformation: $T:\mathbb{R}^2 \to \mathbb{R}^2$ by: $T(x; y) = (x-y; -x + y)$:
Write the matrix representation of $T$ with respect to the basis ${(1; 2);(-1; 1)}$ (use the same basis for domain and co-domain).
Now in the solution they did the following:

*

*Picked the transition matrix

\begin{equation*}
P=
\begin{pmatrix}
1 & -1  \\
2 & 1
\end{pmatrix}
\end{equation*}
2.Picked the matrix $A$ which is the matrix representation of the linear transformation with respect to the standard basis.
\begin{equation*}
A=
\begin{pmatrix}
1 & -1  \\
1 & 1
\end{pmatrix}
\end{equation*}
The found the matrix representation $B$ relative to the basis ${(1; 2);(-1; 1)}$ by solving $B=P^{-1}AP$
My question is the following: Why didn't we find $B$ by doing $B=PAP^{-1}$ since we are going from the standard basis to another one, the set-up is something I would do if I am going from ${(1; 2);(-1; 1)}$ to the standard basis.

A: $\newcommand{\B}{\mathcal{B}}\newcommand{\S}{\mathcal{S}}\newcommand{\x}{\mathbf{x}}$Let $\B$ be the basis in question. Note that $P$ is the transition matrix from $\B$ to the standard basis $\S$. That is, $[\x]_{\S} = P[\x]_{\B}$, or equivalently, $[\x]_{\B} = P^{-1}[\x]_{\S}$ for all $\x\in \Bbb{R}^2$.
The matrix of $T$ with respect to $\B$ in domain and codomain (which you are calling $B$) is defined as satisfying $[T(\x)]_{\B} = \color{blue}{B}[\x]_{\B}$ for all $\x\in \Bbb{R}^2$. But
$$\begin{align*}[T(\x)]_{\B} &= P^{-1}[T(\x)]_{\S} \\
&= P^{-1}A [\x]_{\S} \quad (\text{since }[T(\x)]_{\S}  = A [\x]_{\S} \text{ by definition of }A)\\
&= \color{blue}{P^{-1} AP}[\x]_{\B}.\end{align*}$$
So the matrix you want is $B =P^{-1} AP$.


text:
Q: Any actual applications based on "dirichlet distribution servers as a conjugate prior for multinomial distribution" Conjugate prior is useful and beautiful in theory, for instance, Dirichlet distribution can serves as the conjugate prior for multinomial distribution. But I don't find any actual applications based on that.
Can you provide some?

A: Thinking specifically of the Dirichlet-Multinomial conjugate pair, have a look at the popular latent Dirichlet allocation (LDA) topic model. LDA models topics as multinomial distributions over words with a Dirichlet prior, and models documents as multinomial distributions over topics with a Dirichlet prior. Due to conjugacy, we are able to build a collapsed Gibbs sampler for LDA (ie we integrate out the parameters we don't necessarily care about, keeping just the latent topic assignments for each word), making inference tractable. Without conjugacy, we could not collapse the model, much less make a Gibbs sampler (although we could do Metropolis-Hastings), so inference would be much more costly at run time.


text:
Q: How to show array columns in DataGridView I am selecting data from a Postgres database, and one of these columns is of type TEXT[]. I bind the data source to a DataGridView, but those array columns just don't show up (dgData is a DataGridView).
dgData.DataSource = getDataTable();

When I now inspect ((DataTable)dgData.DataSource).Columns[15].DataType, I get the value {Name = "String[]" FullName = "System.String[]"}, showing me that this is a string array. This column is just gone in the rendering of the DataGrid.
How can I show that data?

A: I don't think a DataGridView will accept a column of type string[].
If it did you could use the CellFormatting event to create a nicely formatted display version of your data, maybe like so:
private void DataGridView1_CellFormatting(object sender,
                                          DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == yourIndexOrName1 && e.Value != null)
    {
        var s = e.Value as string[];
        e.Value = String.Join(", ", s);
    }
}

But the Column neither gets created (when using AutoGenerateColumns) nor gets filled otherwise.
So you should create a readily formatted column. Either in SQL at the database level or later in a Linq line.
Example:
var dt_ = dt.Rows.Cast<DataRow>().Select(x => new {
    f1 = x.Field<string>(0),
    f2 = x.Field<string[]>(1).Aggregate((i, j) => i + ", " + j),
    f3 = x.Field<int>(2)
});

dataGridView1.DataSource = dt_.ToList();

Using my test data:
DataTable dt = new DataTable();
dt.Columns.Add("col1", typeof(string));
dt.Columns.Add("col2", typeof(string[]));
dt.Columns.Add("col3", typeof(int));

var row = dt.NewRow();
row.SetField<string>("col1",  "A");
row.SetField<string[]>("col2", new string[] { "abc", "xyz", "123" });
row.SetField<int>("col3", 23 );
dt.Rows.Add(row);
row = dt.NewRow();
row.SetField<string>("col1", "B");
row.SetField<string[]>("col2", new string[] { "a-b-c", "x+y+z", "1:2:3" });
row.SetField<int>("col3", 42);
dt.Rows.Add(row);

The result looks like this:

While this means indeed that you need to take care for each field, imo the autogeneration of columns is not as powerful and flexible as one would wish, when it gets down to production code..


text:
Q: guess the word game in python - how to mask a word (eg. ------) I'm writing a guess the word game in python. It's for my school project. I'm almost done, I just have a problem with one thing. I can't figure out how to mask a word. For example, if the word is monkey, the program should display ------ and as the user guess a letter, let's say k, the program should display ---k--
Unfortunately I have to write the code it certain way. I'm supposed to have a main function that will just call other functions that will do all the work (like functions that will ask user for a letter or check if the guessed word is correct). I have finished all the functions except for this masking function.
The function is called maskWord(state, word, guess). I have to keep those variables, but they will be passed to the function. state is the masked word (eg.------),word is the word to be guessed (eg. monkey) and guess is the letter guessed by the user. Once the function updates the masked word, it should return state. The other rule is I can't create global variables. The variables that are passed are the ones that have to be used.
Here's what I have:
def maskWord(state, word, guess)
  guessed = []
  guessed.append(guess)
  for guess in word:
    if guess in guessed:
      state += guess
    else: state += "-"
  return state

It doesn't really work. Because my main function that calls this function is a while loop, each time guessed becomes an empty string.
I would really appreciate it if someone could help me with this. I know that it has to be possible to write this function using only the variables, because my teacher only allowed to use those.

A: Fixed my answer to reflect comments, it's somewhat shorter then what kjtl's answer is. But it's based on the same concept, by using state as... well, current state :)
def maskWord(state, word, guess):
    state = list(state)
    for i in range(len(word)):
        if word[i] == guess:
             state[i] = guess
    return "".join(state)

# Lets test if it works..:
word = "electricity"
state = "-" * len(word)
tries = 0

play = True
while play:
    if tries == len(word)*2:
        print "Fail...";
        play = False
    guess = raw_input("Guess: ")
    tries +=1
    state = maskWord(state, word, guess)
    print state
    if maskWord(state, word, guess) == word:
        print "WIN, WIN!!";
        play = False

A: Expanded on SLACKY's answer by using state as the container for the valid guesses.
def maskWord(state, word, guess):

    result = ''
    guessed = []
    character = ''
    for character in state:
        if not character == '-':
            if not character in guessed:
                guessed.append(character)

    if not guess in guessed:
        guessed.append(guess)

    for guess in word:
        if guess in guessed:
            result += guess
        else:
            result += "-"

    # for debugging change to if True:
    if False:
        print 'state %s' % state
        print 'word %s' % word
        print 'guess %s' % guess
        print guessed

    return result

# Lets test if it works..:
import sys

word = "electricity"
state = ""
tries = 0

loop = True
while loop:
    if tries == len(word)*3:
        print "Fail..."
        loop = False
    else:
        guess = raw_input("Guess: ")
        tries +=1
        state = maskWord(state, word, guess)
        print state
        if maskWord(state, word, guess) == word:
            print "WIN, WIN!!"
            loop = False

A: Maybe this could help you:
import random
import string
VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2,
    'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10,
    'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 }

def load_words():

print ("Loading word list from file...")

# making the file

words_file= open("N:\Problem Set 1\words.txt", 'r', 0)

# making the wordlist

 words = []

 for line in words_file:

words.append(line.strip().lower())

print ("  ", len(words), "words loaded.")

return words

def get_frequency_dict(sequence):

# freqs: dictionary (element_type -> int)

frequencies = {}
    for x in sequence:
        frequencies[x] = frequencies.get(x,0) + 1
    return frequencies

# -----------------------------------

def get_word_score(word, n):
    output = 0
    # Checking whether the latter is in the list
    for letter in word:
        output = output + SCRABBLE_LETTER_VALUES.get(letter)
    output = output * len(word)
    if len(word) == n:
        output = output + 50
    if output < 0:
        print "That's is a negative value!"
    return output

def display_hand(hand):
    # Displaying the hand
    for letter, frequency in hand.items():
        for i in range(frequency):
            print letter,
    print '\n'

def deal_hand(n):
    hand={}
    number_vowels = n / 3

    for i in range(number_vowels):
        z = VOWELS[random.randrange(0,len(VOWELS))]
        hand[z] = hand.get(z, 0) + 1

    for i in range(number_vowels, n):
        z = CONSONANTS[random.randrange(0,len(CONSONANTS))]
        hand[z] = hand.get(z, 0) + 1

    return hand

# Updating the hand
def update_hand(hand, word):
    for letter in word:
        if hand[letter] != 0:
            hand[letter] = hand.get(letter, 0) - 1
    return hand

#If letter chosen is in hand then append
def is_valid_word(word, hand, words_file):
    handchosen = dict.copy(hand)
    first_hand =[]
    second_hand = []
    for letter in handchosen.keys():
        for f in range(handchosen[letter]):
            first_hand.append(letter)
    for letter in word:
        for s in handchosen:
            if s == letter and handchosen[letter] != 0:
                    handchosen[letter] = handchosen.get(letter, 0) - 1
    for letter in handchosen.keys():
        for f in range(handchosen[letter]):
            second_hand.append(letter)
    if words_file.count(word) > 0 and len(word) + len(second_hand) == len(first_hand):
        return True
    else:
        return False

# Play the hand
def play_hand(hand, words_file):
    print
    print
    print 'Hey welcome to the Wordgame!'
    print
    print "Press '.' when you want to end the game."
    print
    n = HAND_SIZE
    old_hand = hand.copy()
    print 'Initial hand:',
    display_hand(hand)
    print
    loop = 1
    while loop == 1:
        yourscore = 0
        numLetters = 1
        while numLetters > 0:
            quit = '.'
            word = raw_input('Please enter a valid word: ')
            if word != quit:
                if is_valid_word(word, hand, words_file) == False:
                    print 'Invalid word. Please enter a valid word:'
                else:
                    numLetters = 1
                    print 'You got points for:',word,'=',get_word_score(word, n)
                    yourscore = yourscore + get_word_score(word, n)
                    print 'The total score:', yourscore
                    updated_hand = update_hand(hand, word)
                    print 'Current Hand:',
                    display_hand(updated_hand)
                    print
                    hand = updated_hand
                    for num in dict.values(hand):
                        numLetters = num + numLetters
                    numLetters = numLetters - 1
                    print numLetters,'letters are still remaining.'
                    if numLetters == 0:
                        loop = 0
                    print
            else:
                numLetters,loop = 0,0
    print 'Lets see what the final score is: ', yourscore

#Play the game
def play_game(words_file):
    hand = deal_hand(HAND_SIZE) # random init
    while True:
        # Let the user make a choice
        A = raw_input('Enter n to deal a new hand, r to play the same hand or e to end game: ')
        if A == 'n':
            hand = deal_hand(HAND_SIZE)
            play_hand(hand.copy(), words_file)
            old_hand = hand.copy()
            print
        # User can take the same hand
        elif A == 'r':
            play_hand(old_hand, words_file)
        # Break
        elif A == 'e':
            break
        else:
            print "That is a invalid command."

if __name__ == '__main__':
    words_file = load_words()
    play_game(words_file)


text:
Q: What class to use for lookup value? I am building a C# windows form that displays a listbox with some items to select from to a user.  That selection will determine the criteria for a query.  The query will return 2 fields, an ID and a description.  I want to display the description in a second listbox on the form but use the ID for subsequent processing if that description is selected in the list box.
Here's some more details about what I am trying to do:
ListBox1
Accessories
Men's
Women's
Children

When the user selects 'Accesories' a query runs and returns:
1234   Belts
2345   Scarves
4566   Handbags

ListBox2 displays the descriptions
Belts
Scarves
Handbags

But when the user double clicks on Belts I want to add 1234 to a field in class instance.  What kind of list should I put the results of the query into so that I can use it to add Items to my list box and still be able to know the ID?
Thanks!
Leslie

A: Both WinForms and WPF are quite flexible. Just add the Accessory objects to the Items property. Or set DataSource to an existing list.
The default display is through ToString() but you can set DisplayMember to the name of a specific property.
You can get at the entire object through SelectedItem. And/or set ValueMember and read SelectedValue.

A: In the .NET list boxes, the item list is not just a list of strings, but objects.  The component will use the string value of the object for display, but you can reference the ID when you look at the selected value.
Define a class thusly
class Choices
{
   public string Name;
   public int ID;

   public override string ToString()
   {
      return name;
   }
}

Populate the list with instance of this class, and you should be good to go.


text:
Q: Change local date in PyQt application How to modify local date in PyQt application (i needed to change it on linux and win platform)? E.g.:
>>> date_now = QtCore.QDate.currentDate()
>>> print date_now
>>> PyQt4.QtCore.QDate(2014, 3, 3)

...some code for change current date

>>> date_now = QtCore.QDate.currentDate()
>>> print date_now
>>> PyQt4.QtCore.QDate(2012, 1, 1)

Notice: external system date must not change.

A: You can monkey-patch QDate:
QtCore.QDate.currentDate = lambda: QtCore.QDate(2012, 1, 1)

Which might lead to inconsistencies somewhere else.

Working example:
Python 3.3.2+ (default, Oct  9 2013, 14:50:09)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from PyQt4 import QtCore
>>> QtCore.QDate.currentDate()
PyQt4.QtCore.QDate(2014, 3, 3)
>>> QtCore.QDate.currentDate = lambda: QtCore.QDate(2012, 1, 1)
>>> QtCore.QDate.currentDate()
PyQt4.QtCore.QDate(2012, 1, 1)
>>>

For python2.7:
class PatchedQDate (QtCore.QDate):
    @classmethod
    def currentDate (cls):
        return QtCore.QDate (2012, 1, 1)

QtCore.QDate = PatchedQDate


text:
Q: UIBezierPath & CAShapeLayer initial animation jump I built this for my company: https://github.com/busycm/BZYStrokeTimer and during the course of building, I noticed an interesting "bug" that I can't seem to mitigate when using UIBezierPath. Right when the animation starts, the path jumps a certain number of pixels forward (or backwards depending if it's counterclockwise) instead of starting up with a smooth, incremental animation. And what I found that's really interesting is how much the path jumps forward is actually the value of the line width for the CAShaperLayer.
So for example, if my bezier path starts off at CGRectGetMidX(self.bounds) and the line with is 35, the animation actually starts from CGRectGetMidX(self.bounds)+35 and the larger the line width, the more noticeable the jump is. Is there any way to get rid of that so that path will smoothly animate out from the start point?
Here's a picture of the first frame. This is what it looks like immediately after the animation starts.
Then when I resume the animation and pause again, the distance moved is about 1/100th of the distance you see in the picture.
Here's my bezier path code:
- (UIBezierPath *)generatePathWithXInset:(CGFloat)dx withYInset:(CGFloat)dy clockWise:(BOOL)clockwise{
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(CGRectGetMidX(self.bounds)+dx/2, dy/2)];
    [path addLineToPoint:CGPointMake(CGRectGetMaxX(self.bounds)-dx/2, dy/2)];
    [path addLineToPoint:CGPointMake(CGRectGetMaxX(self.bounds)-dx/2, CGRectGetMaxY(self.bounds)-dy/2)];
    [path addLineToPoint:CGPointMake(dx/2, CGRectGetMaxY(self.bounds)-dy/2)];
    [path addLineToPoint:CGPointMake(dx/2, dy/2)];
    [path closePath];
    return clockwise ? path : [path bezierPathByReversingPath];
}

Here's the animation code:
CABasicAnimation *wind = [self generateAnimationWithDuration:self.duration == 0 ? kDefaultDuration : self.duration fromValue:@(self.shapeLayer.strokeStart) toValue:@(self.shapeLayer.strokeEnd) withKeypath:keypath withFillMode:kCAFillModeForwards];
wind.timingFunction = [CAMediaTimingFunction functionWithName:self.timingFunction];
wind.removedOnCompletion = NO;
self.shapeLayer.path = [self generatePathWithXInset:self.lineWidth withYInset:self.lineWidth clockWise:self.clockwise].CGPath;
[self.shapeLayer addAnimation:wind forKey:@"strokeEndAnimation"];

And here's how I construct the CAShapeLayer.
- (CAShapeLayer *)shapeLayer {
    return !_shapeLayer ? _shapeLayer = ({
        CAShapeLayer *layer = [CAShapeLayer layer];
        layer.lineWidth = kDefaultLineWidth;
        layer.fillColor = UIColor.clearColor.CGColor;
        layer.strokeColor = [UIColor blackColor].CGColor;
        layer.lineCap = kCALineCapSquare;
        layer.frame = self.bounds;
        layer.strokeStart = 0;
        layer.strokeEnd = 1;
        layer;
    }) : _shapeLayer;
}

A: I think what's happening here is that, in this frame of the animation, you are drawing a line that consists of a single point. Since the line has a thickness associated with it, and the line cap type is kCALineCapSquare, that'll get rendered as a square with height and width equal to the line width.
You can think of it as if you are drawing a line with a square marker, and you are going to drag the midpoint of the marker so that it goes through every point in the curve you specified. For the first point in the line, it's as if the marker touches down at that point, leaving a square behind.
Here's a visual representation the different line cap types that will hopefully make it more intuitive. You should probably change the line cap style to kCALineCapButt.
Sidenote:
After you make that change, in this line of code
[path moveToPoint:CGPointMake(CGRectGetMidX(self.bounds)+dx/2, dy/2)];
you probably don't have to offset the x coordinate by dx/2 anymore.


text:
Q: Hidden form submit is not working in Ios Hi I am developing a application using javascript, html, css. it will run as a application and web application. I am creating a hidden form submit like below.
hiddenFormSubmit:function(path, params, method) {
    var form;
    form = document.forms.namedItem('myForm');
    if(form === null){
        method = method || 'post';
        form = document.createElement('form');
        form.setAttribute('name', 'servicesForm');
        form.setAttribute('method', method);
        form.setAttribute('action', path);
        form.setAttribute('target', 'report');
        document.body.appendChild(form);
    }
    else{
        form.innerHTML = '';
    }
    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement('input');
            hiddenField.setAttribute('type', 'hidden');
            hiddenField.setAttribute('name', params[key].id);
            hiddenField.setAttribute('value', params[key].value);
            form.appendChild(hiddenField);
         }
    }

        window.open('','report');

    form.submit();
    },

This one is working perfectly in desktop browsers and mobile browsers. But not working from iOs app.In desktop browsers and mobile browsers it is opening a new window as expected. But in iOs app it is opening a new window with some errors. Do I need to add anything to make work in iOs app. Please suggest.


text:
Q: Angular2 Download Excel File from Asp.Net Core Corrupted So I am using ASP.Net Core as the backend and Angular as my front end. I am trying to download a an excel file created in a controller:
  public IActionResult DownloadServerList()
    {
        byte[] fileContents;

        string fileName = @"servers.xlsx";

        if (System.IO.File.Exists(Path.Combine(@"C:\Users\EC64473\source\repos\ServerInventoryCore", fileName)))
            System.IO.File.Delete(Path.Combine(@"C:\Users\EC64473\source\repos\ServerInventoryCore", fileName));

        FileInfo file = new FileInfo(Path.Combine(@"C:\Users\EC64473\source\repos\ServerInventoryCore", fileName));

        using (ExcelPackage package = new ExcelPackage(file))
        {
            List<Server> serverList = context.Servers.ToList();

            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Servers");
            int totalRows = serverList.Count();

            worksheet.Cells[1, 1].Value = "Server ID";
            worksheet.Cells[1, 2].Value = "Server Name";
            worksheet.Cells[1, 3].Value = "Exists";
            worksheet.Cells[1, 4].Value = "UUID";
            int i = 0;
            for (int row = 2; row <= totalRows + 1; row++)
            {
                worksheet.Cells[row, 1].Value = serverList[i].ID;
                worksheet.Cells[row, 2].Value = serverList[i].ServerName;
                worksheet.Cells[row, 3].Value = serverList[i].ServerExists;
                worksheet.Cells[row, 4].Value = serverList[i].ServerUUID;
                i++;
            }
            package.Save();

            fileContents = package.GetAsByteArray();
        }

        //if (fileContents == null || fileContents.Length == 0)
        //    return NotFound();

        return File(
            fileContents: fileContents,
            contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            fileDownloadName: "servers.xlsx"
            );
    }

I can verify the excel file created is not corrupt while sending it as a file and the total size is: around 96 kb.
My Service is:
 getServerListAsExcel(): Observable<any> {
return this.http.get('Servers/DownloadServerList', { responseType: ResponseContentType.Blob  });

}
My Component.ts is:
 buttonPress() {
this.serverService.getServerListAsExcel()
  .subscribe(data => {
    console.log(data);
    saveAs(data._body, 'test.xlsx');
  });

When log the data the result is:
Response {_body: Blob(195104), status: 200, ok: true, statusText: "OK",
headers: Headers, …}
headers: Headers
_headers: Map(8) {"date" => Array(1), "server" => Array(1), "x-powered-by" =>
Array(1), "content-type" => Array(1), "status" => Array(1), …}
_normalizedNames: Map(8) {"date" => "date", "server" => "server", "x-powered-
by" => "x-powered-by", "content-type" => "content-type", "status" => "status", …}
__proto__: Object
ok: true
status: 200
statusText: "OK"
type: 2
url: "https://localhost:44312/Servers/DownloadServerList"
_body: Blob(195104)
size: 195104
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

The file downloads, however is twice the size of the original i saved locally on my system when creating the file ion the controller. I noticed the size seemed to double on the "getAsByteArray" function of ExcelPackage. the message that comes up when trying to open is "We found a problem with some of the content in '.....xlsx'.Do you want to recover?" at which point I click yes and Excel hangs. Is there anyone who can point me in the right direction?

A: I don't think that leaving plain item of ResponseContentType enum will be enough in request options.
Check this:
getServerListAsExcel(): Observable<any> {
        return this.http.get('Servers/DownloadServerList', {responseType: ResponseContentType.Blob});
    }

A: So I now realize the issue was on my controller side:
I was attempting to pass the excel package as a byte array which is supposed to be fine.
Instead I had to return it as a MemoryStream:
    public IActionResult DownloadServerList()
    {
        byte[] fileContents;

        string fileName = @"servers.xlsx";

        if (System.IO.File.Exists(Path.Combine(@"C:\Users\EC64473\source\repos\ServerInventoryCore", fileName)))
            System.IO.File.Delete(Path.Combine(@"C:\Users\EC64473\source\repos\ServerInventoryCore", fileName));

        FileInfo file = new FileInfo(Path.Combine(@"C:\Users\EC64473\source\repos\ServerInventoryCore", fileName));
        var stream = new MemoryStream();
        using (ExcelPackage package = new ExcelPackage(file))
        {
            List<Server> serverList = context.Servers.ToList();

            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Servers");
            int totalRows = serverList.Count();

            worksheet.Cells[1, 1].Value = "Server ID";
            worksheet.Cells[1, 2].Value = "Server Name";
            worksheet.Cells[1, 3].Value = "Exists";
            worksheet.Cells[1, 4].Value = "UUID";
            int i = 0;
            for (int row = 2; row <= totalRows + 1; row++)
            {
                worksheet.Cells[row, 1].Value = serverList[i].ID;
                worksheet.Cells[row, 2].Value = serverList[i].ServerName;
                worksheet.Cells[row, 3].Value = serverList[i].ServerExists;
                worksheet.Cells[row, 4].Value = serverList[i].ServerUUID;
                i++;
            }

            //package.Save();
            package.SaveAs(stream);
            stream.Position = 0;
            fileContents = package.GetAsByteArray();
        }

        if (fileContents == null || fileContents.Length == 0)
            return NotFound();

        return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "servers.xlsx");
    }


text:
Q: is there a pattern here showing up or it's simply a coincidence? It seems to me that the degree three equations have a special place among algebraic equations. Let me clarify what I have in mind.

*

*Degree 3 curves: The only curves that hold a group structure.

*Degree 3 surfaces in $\mathbb P^3$: The only surfaces whose curves are not covered by the Noether-Lefchetz Theorem and therefore they are not complete intersection.

*Threefold. Here, one can find examples (the only ones?) of unirrational varieties which are not rational. (can be done by looking at the intermediate jacobian).

Here is my question. Is there a phenomena like this in some other degrees?
In other words, now I'm inclined to think that there is something very special about degree three equations, could this be true? or I'm just happen to be missing other equally important examples in other degrees?
Any answers/comments/examples will be appreciated.
Edit: sure, I deliberately didn't say anything about smoothness and very general surfaces. In order to keep the question simple, please put the sentence in context.

A: There are certainly some very nice properties of degree $3$ objects, but I agree with Chuck and Scott, that what you are observing is that this is the first non-trivial case of anything. On one hand that means that you will observe interesting behavior, on the other that there might be a larger literature dealing with this case.
Also, I can't help but comment on some of what you say in the question:
You say:

"Degree $3$ surfaces in $\mathbb P^3$: The only surfaces whose curves are not covered by the Noether-Lefchetz Theorem and therefore they are not complete intersection."

First of all the correct statement is the opposite: curves on cubic surfaces are not complete intersections and therefore the Noether-Lefschetz Theorem cannot be true. But this is an insignificant detail. Here $3$ is not that important. The main reason this happens is that all smooth cubics famously contain lines (27) and a curve of degree $c$ on a surface of degree $d>c$ cannot be a complete intersection. Also, the Noether-Lefschetz Theorem also fails for quadrics, that is degree $2$ surfaces: Their Picard group is rank $2$, so $\mathrm{Pic}(\mathbb P^3)\simeq \mathbb Z$ cannot surject onto it. So this isn't a real #$3$ mystery unless you count that $3$ is the largest degree where it fails, but then one could say that $4$ is the smallest where it holds, so $4$ is special.
Then again, you could add to your list: by the Lefschetz hyperplane theorem, the restriction of the Picard group to a hyperplane section is an isomorphism if the dimension is larger than $3$! So you could say dimension $3$ is the largest dimension where this fails. But this is really the same thing as the the Noether-Lefschetz thing.
And then you say:

"Threefold. Here, one can find examples (the only ones?) of unirrational varieties which are not rational. (can be done by looking at the intermediate jacobian)."

There are at least two things wrong with this:

*

*Those threefolds could be cubic (great!) but also quartic (that darn $4$ again).

*This does not only happen in dimension three.

However, there is an interesting detail about cubic equations: It is expected that a very general cubic fourfold is unirational but not rational, but I believe this has not been proven yet.
In arbitrary dimension and degree we have some general results.
János Kollár proved in this paper that

Theorem (Kollár): Let $X_d\subset \mathbb P^{n+1}$ be a very general hypersurface over $\mathbb C$ of degree $d\geq \frac 23(n + 3)$.
  Assume in addition that $n$ and $d$ are both even. Then $X_d$ is not (birationally) ruled.

Remark Obviously then $X_d$ is not rational.
On the other hand, Morin proved in
Morin, Ugo
Sull'unirazionalità dell'ipersuperficie algebrica di qualunque ordine e dimensione sufficientemente alta. (Italian) Atti Secondo Congresso Un. Mat. Ital., Bologna, 1940, pp. 298–302 Edizioni Cremonense, Rome, 1942.
that a general hypersurface is unirational if its dimension is sufficiently large with respect to the degree. (There is an explicit formula for this). Since then there has been generalizations of this by Harris-Mazur-Pandharipande and Xi Chen.
It is also interesting to compare these to rational connectivity. Every Fano manifold is rationally connected, so Kollár's theorem implies that there are plenty of examples of rationally connected but not rational varieties.
The most interesting open problem in the area is that everyone expects that there are many  rationally connected but not unirational varieties, but nobody knows an example.
Finally, let me finish with the
Group Law
This is indeed remarkably unique. As Scott pointed out we need to restrict to smooth cubic plane curves, but that is what you meant.
I'd like to remark that this is indeed about the number $3$ being special.
Consider curves of degree $d$ in $\mathbb P^2$. These are parametrized by a projective space $\mathbb P^N$ where $N= {d+2\choose 2}-1= \frac 12 d(d+3)$.  Containing a fixed point of $\mathbb P^2$ imposes a linear condition on this space, so specifying $N$ points in general position determines a unique degree $d$ curve.
Generally two curves of degree $d$ will intersect in $d^2$ points.
It turns out that  $N=d^2$  for $d=3$ and this is why the group law defined by drawing lines is associative. Of course, there are more places where $3$ is needed, but those are sort of obvious reasons that one needs to even define the group law and this is a little bit more hidden.
Anyway, I should quit, but I want to say that my goal was not to take apart your question just to show that most of the nice properties you listed actually appear in more places.

A: The philosophical reasons why degree three equations share unique properties could be so wide-ranging as to make the question essentially self-fulfilling: if you look for an answer you will find it. For instance, it might be because we perceive space three-dimensionally or because 3 is the first odd prime - in my mind both these explanations are irrelevant but they go to show that if you're looking for heuristics on very wide-ranging phenomena, then pretty much anything you say makes sense.
If I were you, I would instead ask the following: To what extent are the pathological properties of degree-three algebraic equations more numerous and pervasive than those of algebraic equations in other degrees because of reasons other than the fact that degree 3 is the first 'interesting' case of several curves and surfaces on which generalizations will be based? That is to say: is the difficulty of proving 3-dimensional Poincare an indication that there is something pathological about the 3-sphere or that 3 dimensional beings are the only ones who would find the Poincare conjecture interesting and pursue a proof?
My (underdeveloped) philosophical intuitions veer towards the latter...


text:
Q: Regex double forward slash in Google Analytics I would like to regex the one or more // after https:// in https://website.com.au//my-account// in Google Analytics Custom reports filters.
I have found that this regex should work normally but not in GA.
Regex: (?<!:)\/\/
Required solution:
What I need to find are the // after .com.au and  my-account and not the one after https:.
Thank you!

A: One option is to match any char except a : using a negated character class and then use a capturing group to match the //
[^:](\/\/)

Regex demo
To not find the match after https:// you could use an alternation matching what you want and capture in a group what you don't want
https?:\/\/|(\/\/)

Regex demo


text:
Q: How to call function with generic params in typescript I am trying to create something like this as below
export function f1(param1: string, param2: string) {
    console.log('Hello', param1, param2);
}

export function f2(param3: string) {
    console.log('world', param3);
}

interface Metadata {
    functionName: string;
    functionParams: any;
}

const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', {functionName: 'f1', functionParams: {param1: 'any', param2:'any1'}}],
    ['action2', {functionName: 'f2', functionParams: {param3: 'any2'}}]
])

So basically I want to call f1 or f2 function after reading it through a testMap. The idea is to store all action and their mappings against a function and execute actions in one go instead of creating multiple if and else statements.
Can somebody help I can achieve this ?

A: You can't reference and call a function by passing its name as a string (without doing some eval black magic that I cannot in good conscience recommend). Instead, you should pass the function itself:
export function f1(param1: string, param2: string) { }

export function f2(param3: string) { }

// Change your interface to accept a function instead of a string:
interface Metadata {
    invoke: (...args: any[]) => any;
    functionParams: any[];
}

// Pass f1 or f2 (the function references) instead of 'f1' or 'f2':
const testMap: Map<string, Metadata> = new Map<string, Metadata>([
    ['action1', { invoke: f1, functionParams: ['any', 'any1'] }],
    ['action2', { invoke: f2, functionParams: ['any2'] }]
])

Playground example


text:
Q: Find the value of the real part of (z+w)/(z-w) when |z| = |w| It's an IBDP question.
When I try to solve it, I end up with a fraction with many variables.
I was thinking maybe I should rationalize the fraction...

A: We have that
$$\frac{z+w}{z-w}=\frac{z+w}{z-w}\frac{\bar z-\bar w}{\bar z-\bar w}=\frac{\bar zw-z\bar w}{|z-w|^2}$$
and
$$\bar zw-z\bar w=\bar zw-\overline{ \bar zw}=2i \Im(\bar zw)$$
therefore
$$\frac{z+w}{z-w} =2i \frac{\Im(\bar zw)}{|z-w|^2}$$

A: Write $z=re^{it}$ and $w=re^{iu}$. Then
$$\frac{z+w}{z-w}=\frac{e^{it}+e^{iu}}{e^{it}-e^{iu}}
=\frac{e^{i(t-u)/2}+e^{-i(t-u)/2}}{e^{i(t-u)/2}-e^{-i(t-u)/2}}
=\frac{2\cos\frac12(t-u)}{2i\sin\frac12(t-u)}=i\cot\theta$$
where $\theta=\frac12(u-t)$ is half the angle between $z$ and $w$ in the
Argand diagram. So zero real part, but the imaginary part is interesting.

A: Geometrically, if we assume $z$ and $w$ are the edges of a quadrilateral with $O$ as a common vertex, then $z+w $ and $z-w$ are the two diagonals of that quadrilateral. Because $|z|=|w|$ the quadrilateral is a losenge. The diagonals of a losenge are orthogonal and therefore ${z+w\over z-w}$ is a pure imaginary number. Its real part is $0$


text:
Q: Setting value in variable provided while creating paypal buy button I have this paypal buttom generated to buy.The scripts contains some variable whose values are already provided but i want to provide the value to variables dynamically.
This is the buy button generated.
    <script
data-callback="http://sajilobazar.com"
data-tax="3"
data-shipping="1"
data-currency="USD"
data-amount="45"
data-quantity="1"
data-name="helo"
data-button="buynow" src="https://www.paypalobjects.com/js/external/paypal-button.min.js?merchant=*****@yahoo.com" async="async">
</script>

As seen in the above code the variables like data-tax are pre populated.I want to provide my own value.
This is what i tried
var x= "3";
data-tax=x

But it won't work.Please help!!!

A: You can use data-tax-editable which makes tax editable and enter a value to pass the dynamic tax variable.
Eg:
<script
data-callback="http://sajilobazar.com"
data-tax-editable="3"
data-shipping="1"
data-currency="USD"
data-amount="45"
data-quantity="1"
data-name="helo"
data-button="buynow" src="https://www.paypalobjects.com/js/external/paypal-button.min.js?merchant=*****@yahoo.com" async="async">
</script>

But, alternatively you to use Button manager API to create dynamic buttons via BMCreateButton API call.


text:
Q: Best Practice for temporary query result storage in Google App Engine I have a query that takes a bit of time (it involves some computations and accessing a third-party).  Currently, the user makes an HTTP request to initiate the query (it returns immediately).  GAE puts the task in a queue and executes it.  After execution, the task stores the results in a static object.  The user makes another HTTP request later to retrieve the results.
Is there a best practice way to implement something like this?  Would the results be better stored in the DataStore?

A:
the task stores the results in a static object

How are you making sure that the subsequent request from same user hits the same instance so that it can access the static object?
A better way to do it would certainly be either storing it in memcache (prone to hit or miss) and/or datastore. Keep in mind, with the new pricing model, datastore operations are going to cost more.


text:
Q: Why an XML Create Schema Error in Visual Studio 2013? A little off course from the norm, but a coworker is having issues generating an xsd from a simple xml model and I really don't know much about why they would be getting an error. I loaded the same xml document and didn't get the error. We are both using VS2013.
Here's the XML
<CustomerCreditCheckResponse>
    <Result>0</Result>
    <CreditStatus>0</CreditStatus>
    <AvailableCredit>50000.00</AvailableCredit>
    <StatedCreditLimit>100000.00</StatedCreditLimit>
    <HoldCreditLimit>100000.00</HoldCreditLimit>
    <AccountStatus>0</AccountStatus>
</CustomerCreditCheckResponse>

The error received is

'Create Schema Error' --> startIndex cannot be larger than length of
  string. Parameter name: startIndex

A: I had the same issue after generating the XML with the select * from MyView for XML AUTO, Elements query. This occurred after attempting to 'Create Schema' from VS 2013 when opening the XML file directly from the SQLQuery Results tab. Saving the document to another location with a short name 'TestXML' or whatever allowed the tool to create the appropriate schema without error.


text:
Q: Python, pygame: Unable to open .wav file I am trying to play a simple beat with the pygame.mixer.
import os
import pygame
import pygame.mixer

# Initialize the game
pygame.init()
pygame.mixer.init() # frequency, size, channels, buffersize
print(os.listdir())

# ... some other stuff....

try:
    sound = pygame.mixer.Sound("low_click.wav")
    print('low_click.wav')
    sound.play()
except pygame.error:
    pass

The program just prints
['metronom_quintenzirkel.py', 'low_click.wav', 'data']

, so an exception occured.
What has gone wrong?


text:
Q: Perl Script – Look at the first number of each line and alert if 0 exists Currently the script only looks at the first character of a txt file and emails if that value =0 using regex. I'm trying to update the script so it looks at each line until the end of the file and alert of any of the lines have the number 0. If all lines have 1 then do nothing. Any help would be greatly appreciated.
Example of an alert
1
1
1
0 -since there is a 0 an email alert would be generated
1
1

code below:
use warnings;
use strict;

my $file = '/users/tneal01/SPOOL/output.txt';
my $mark = 0;

my $cont = do {
    open my $fh, '<', $file  or die "Can't open $file -- $!";
    local $/;
    <$fh>;
};

# Pull the first number
my ($num) = $cont =~ /^(\d+)/;

if ($num == $mark)
{
    my $body = "status $num has been recorded ";
    my $cmd_email = "echo $body | " .
        "mailx -s \"error occurring\" tneal01\@gmail.com";
    system($cmd_email) == 0  or die "Error sending email -- $!";
}

A: I'd probably go with something like:
#!/usr/bin/env perl
use strict;
use warnings;

my $file   = '/users/tneal01/SPOOL/output.txt';
my $mark   = '0';
my $search = qr/^$mark\b/;

open my $fh, '<', $file or die "Can't open $file -- $!";

while (<$fh>) {

   #line starts with 0. Or check other regex.
   if (m/$search/) {
      my $body = "status $mark has been recorded ";
      my $cmd_email =
        "echo $body | " . "mailx -s \"error occurring\" tneal01\@gmail.com";
      system($cmd_email) == 0 or die "Error sending email -- $!";

     #bail out the loop - assume you don't want more than one email per thing.
      last;
   }
}

close ( $fh );

A: This solution only reads one line at a time... there are simple solutions, but would need to load the entire file into memory...
I'm also assuming you want to know how many occurencies of $mark there are in the file.
#!/usr/bin/perl
use strict;

my $file = 'file.txt';
my $mark = '0';

open my $f, "<$file" or die "Error open file: $!\n";
my $counter=0;
while(my $line = <$f>) {
  if($line =~ /$mark/) {
    $counter++;
  }
}
if($counter) {
    my $body = "status $mark has been recorded $counter times";
    my $cmd_email = "echo $body | mailx -s \"error occurring\" tneal01\@gmail.com";
    system($cmd_email) == 0  or die "Error sending email -- $!";
}

A: This does a couple of things differently to other solutions here.

*

*It reads from whatever filename is given on the command line

*It stops checking once the first error is found

I don't know how useful those improvements are to you.
use warnings;
use strict;

my $mark = 0;

while (<>) {
  my ($num) = /^(\d)/;
  if ($num == $mark) {
    my $body = "status $num has been recorded ";
    my $cmd_email = "echo $body | " .
        'mailx -s "error occurring" tneal01\@gmail.com';
    system($cmd_email) == 0  or die "Error sending email -- $!";
    last; # stop checking after the first error
  }
}

(Oh, and I switched some double-quotes to single-quotes so you don't have to escape embedded double quotes.)

A: This version uses minimal changes to your existing script. I've commented the changes.
use warnings;
use strict;

my $file = '/users/tneal01/SPOOL/output.txt';
my $mark = 0;

my $cont = do {
    open my $fh, '<', $file  or die "Can't open $file -- $!";
    local $/;
    <$fh>;
};

# Pull the first number            <-- comment not needed
# my ($num) = $cont =~ /^(\d+)/; # <-- delete this line

if ($cont =~ /^$mark/m)     # <-- change the condition to this regex
{
    my $body = "status $mark has been recorded "; # replace $num with $mark
    my $cmd_email = "echo $body | " .
        "mailx -s \"error occurring\" tneal01\@gmail.com";
    system($cmd_email) == 0  or die "Error sending email -- $!";
}

What the change does is use a regular expression to check if any lines begin with the value defined in $mark.
I deleted the $num variable, but its contents was the same as $mark so we can just use $mark instead.
A breakdown of $cont =~ /^$mark/m:

*

*$cont =~ Apply the following regex to the string contained in $cont

*/ Start the regular expression

*^ Match the beginning of a line

*$mark Match the string specified in the $mark variable

*/ End regular expression

*m Flag to tell the regex to treat $cont as a multiple-line string (which it is)


text:
Q: SQL isn't updating when I give them ID Can someone tell me why this isn't updating? The id exists in the table but it wont update.
    let sql = `UPDATE Users
                SET MMR = MMR-30, Lose = Lose+1
                WHERE Nameid = ${data[0].Team1id}`;
   db.run(sql, data, function(err) {
      if (err) {
        return console.error(err.message);
        }
        console.log(`Row(s) updated: ${this.changes}`);
        });

But it updates when I edit to this, but I need it to work with Nameid. Because if the team1 changes its name it wont find itself in the table! Meanwhile you cant change your id.
    let sql = `UPDATE Users
                SET MMR = MMR-30, Lose = Lose+1
                WHERE Name = "${data[0].Team1name}"`;  // this was changed
   db.run(sql, data, function(err) {
      if (err) {
        return console.error(err.message);
        }
        console.log(`Row(s) updated: ${this.changes}`);
        });

Got it! Im gonna leave it here if someone stumbles with the same problem someday!
     let sql1 = `UPDATE Users
                SET MMR = MMR+25, Win= Win+1
                WHERE Nameid = ?`;
    db.run(sql1, data[0].Team1id, function(err) {
      if (err) {
        return console.error(err.message);
      }
      console.log(`Row(s) updated: ${this.changes}`);
    });

A: Try to console.log() the data[0].Team1id and see what it gives,
I really can't see any problem in the code, just that team1id could be incorrect.

Another thing...
You need to secure the SQL, it's vulnerable for SQL Injection. Search for "node.js secure for MySQL injection".


text:
Q: Is it possible to construct a link, navigate to it and print the response in C# programmatically? How? I have a webpage written in C#/Razor. I am printing all the values from a database on this page like so :

                    Name
                    Branch
                    Phone No.
                    Extension
                    Email

                @foreach (var prod in Model)
                {

                        @prod.FullName
                        @prod.Branch
                        @prod.PhoneNo
                        @prod.Extension
                        @prod.Email
                        @if (User.IsInRole(@"Admins") || User.Identity.Name == prod.DomainAC)
                        {
                            edit
                        }
                        else
                        {
                            User => @User.ToString()
                        }

                            <input type="checkbox" name="message" value="@prod.PhoneNo">Message

                }

This works fine to display their info. What I would like to do now is a small bit more difficult.
Below this, I have a form with a username, password and message. Using this form, I would like to have the behaviour that on submit, it will take the values in the input boxes of the form and the above C#, construct a link, navigate to the link and print the response of the server
So I have :
@{if (IsPost)
  {
     //handle and print response
  }
  else
  {
    <form method="post" action="">
        Username:

        <input type="text" name="u" />

        Password

        <input type="text" name="p" />

        Password

        <textarea name="m" cols="25" rows="5">
        Enter your comments here...
        </textarea>

        <input type="submit" value="Submit" class="submit" />//when this is clicked, construct url and navigate to it.
    </form>
   }
}

The URL I want to construct from this form is :
http://webaddress.com/web/d.php?u=<Username entered by user>&p=<Password entered by user>&s=<List of Phone Numbers from the C# above where the checkbox is selected, comma separated>&m=<Comment submitted by user>

So, if my name is "John", Password is "Password1", Comment is "Test" and I have selected one checkbox for a user with the phone number "12345678", the URL I will navigate to is :
http://webaddress.com/web/d.php?u=John&p=Password1&s=12345678&m=Test

Ideally I would like to print the response of the webpage in a
 while still on the same parent web page rather than going to a new one if this is possible.
I have no idea where to begin with this, how to do it or even if this is possible. Can anyone help me please ?
UPDATE  :
Trying this JQuery which does not alert me so I cannot debug :

A: $("#SubmitButtonID").click(function() {
    var form = $(document.getElementById('FormID');
    var urlToConstruct = 'http://webaddress.com/web/d.php';
    urlToConstruct += '?u=' + form.find('#iDoFInputControl1').val();
    urlToConstruct += '&p=' + form.find('#iDoFInputControl2').val();
    form.submit();
});

this example uses jQuery, a javascript library (jquery.com), i'm using getElementById to find your form, faster then the native jQuery() selector. This example assumes all your controls are inside your form (but if they are not it wouldn't be a train smash, just cant use (jQuery obj).find).
.val() gets the value, and it should work for checkboxes too, but if it doesn't, a quick google search for getting values from checkboxes using jquery will return loads of results.
p.s. I've written that code mostly freehand, not checked it in a browser to make sure that it is completely correct.
Update... to answer your follow up question...
If you are using mvc (assumed as you using razor), inside your controller you can use Request.Params["urlParameter"] or Request.Form["controlID"] to access what you've received from the browser. Then once you've got those values, you should place them inside the 'ViewBag' (ViewBag.yourVariableHere="val") for them to be accessible in your view via @ViewBag.yourVariableHere, or you can include the required data in your model which can also be accessed in your view


text:
Q: How to connect to Trustwallet with web3dart package in Flutter and do transaction? I want to connect to trustwallet or metamask with web3dart package and do the transaction for example send USDT. I am using this library because it supports all platforms, but it lacks documentation and good example. The problem is there is no working example for what I want to do. I could call rpcUrl for binance smart chain as bellow but I still stuck in how to call wallet for connection, get wallet address and amounts, do the transaction and sign the transaction as well.
import 'package:flutter/material.dart';
import 'package:http/http.dart';

import 'package:web3dart/web3dart.dart';

void main() {
  runApp(const MaterialApp(
    debugShowCheckedModeBanner: false,
    home: MyHomePage(),
  ));
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Test'),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () async {
              var rpcUrl = 'https://bsc-dataseed1.binance.org:443';

              var httpClient = Client();
              var ethClient = Web3Client(rpcUrl, httpClient);

              var chainId = await ethClient.getChainId();
              var networkId = await ethClient.getNetworkId();

              print(chainId);
              print(networkId);
            },
          ),
        ],
      ),
    );
  }
}


text:
Q: Mixing c++ and assembly language I'm trying to matrix multiplication with 2d "int" arrays. I ask the users to insert the matrix via c++. Then, I use that data to do matrix multiplication in assembly. I got a runtime error when I tried moving an element of my "int" array into the 'ax' register. I'm not sure what's wrong.
void Matrix::Calculate()
{
signed short i =0, j=0, k=0 ;

__asm{

    xor eax,eax
    xor ebx,ebx
    xor edx,edx

    mov ecx, 3

    L1:
        push ecx
        mov ecx, 3
    L2 :
        push ecx
        mov ecx, 3
    L3 :
        mov ax, p[i][k]             //runtime error
        mov bx, q[k][j]
        imul bx
        add r[i][j], bx

        inc k
        loop L3

        pop ecx
        inc j
        loop L2

        pop ecx
        inc k
        loop L1
};

}


text:
Q: Questions about the Twilio Authy API We currently have a solution where we implement 2FA ourselves over Twilio Programmable SMS.
We're also using Twilio Verify for Payment PSD2 authorization.
We're now looking to migrate everything to Authy to make use of the Authy app and I have the following questions that I'm hoping you can help me with.

*

*User Migration. I understand in authy, users need to be registered to our application. How can I register all our current users? Is there any way to bulk upload them, or do I have to write a script that calls the API to register them one by one?

*User Number phone update. Sometimes our users will update their phone or email in our system. If that happens, how do I update that info in Authy? I couldn't find anything in the docs about that. Do I need to call the api to remove the user and readd with the new info?

*Migrating from Verify PSD2 to Authy PSD2. Is the implementation very different? Is there any sample I can look through, as the documentation seems to mainly be talking about QR codes, while what we want to do, is to send it over SMS or Authy depending on the user's choice.
Thanks for your help
Sam

A: Twilio developer evangelist here.

*

*You will need to write a script to register your users. When you have registered a user, you will receive an authy_id for the user, which you will need to store with your user record.

*If a user updates their phone number then you should update the Authy user. To do so, you will want to delete the old user and re-register with the new phone number. You will then receive a new authy_id and you should re-confirm the user can authenticate by challenging them for a new code before you complete the update. If the user updates their email then you can do the same process of deleting and creating a new user though you should receive the same authy_id back if the phone number hasn't changed (though this will add the email address to Authy's representation of the user).

*Check the documentation on PSD2 compliant authentication with Authy here. If you are sending SMS messages, then you should set the action and action_message parameters, which tie the message to the authentication. For the app based authentications you can do it via Push Notifications (in which you can include transaction details in the push). If you don't want to implement push, then you do need to get your user to scan a QR code in order to tie the transaction to the authentication (the regular code generated by the app is not connected to a transaction, so is ineligible for PSD2 authentication).
Let me know if this helps at all.


text:
Q: SQL Injection issue. Using SQLParser for executing the query Recently we did Vulnerability scan to our project and we found SQL Injection issue.
In my project we are using code like:
SQLParser x = new SQLParser(query);
SelectStatement y = x.parseQuery();
List<ParseNode> groupByNode = y.getGroupBy();

For the above code it saying like SQL Injection as we are passing the query directly, but we are executing the query via SQLParser and doing operation using  org.apache.phoenix.parse.SelectStatement.
Kindly give a suggestion to this.


text:
Q: ¿Como cambio a través de un ComboBox, el estilo de fuente de las cosas que escribo en un cuadro de texto automáticamente? <ComboBox Width="120" SelectionChanged="ComboBox_SelectionChanged" x:Name="combosize"  ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}"/>

<TextBox Grid.Row="1" TextWrapping="Wrap"   AcceptsReturn="True" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible"  SpellCheck.IsEnabled="True"  Name="myTextBox" KeyUp="myTextBox_KeyUp" TextChanged="myTextBox_TextChanged></TextBox>

PD: Recien empiezo con WPF

A: Para que se cambie el tipo de letra del TextBox cuando seleccionas la fuente en el ComboBox, debes hacer lo siguiente:
<Window x:Class="WpfApp7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp7"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <ComboBox x:Name="combo" ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}" />
        <TextBox FontFamily="{Binding ElementName=combo, Path=SelectedValue}" />
    </StackPanel>
</Window>

Un saludo.


text:
Q: Character vector using tidyr I have a dataframe:
free_text
"Lead Software Engineer Who We Are: CareerBuilder is the global leader in human capital solutions as we help people target and attract their most important asset - their people. From candidate sourcing solutions, to comprehensive workforce data, to software that streamlines your recruiting process, our focus is always about making your recruitment strategy simple, fast and effective. Are you an experienced software engineer looking to take the next step to leadership? Would you like to lead a team of agile software developers? If so, then we have an immediate need for a self-motivated software engineering lead to join the Candidate Data Processing team in our Norcross, Georgia office. The Candidate Data Processing team is responsible for processing and enriching millions of candidate profiles. We use the Amazon AWS ecosystem as well as our own in-house platform to enhance, normalize, and index candidate profiles from a variety of sources. Our projects require scalable solutions with continuous availability. CareerBuilder engineers participate in every phase of the software development lifecycle and are encouraged to have vision beyond the technical aspects of a project. This position requires knowledge in the theory and practical application of object-oriented design and programming. Prior leadership experience and experience with databases and cloud-computing technologies are desired. Your primary responsibilities as an Engineering Lead will be split between management and technical contributions. You will work with an agile project manager and a product owner to establish objectives and results, and you will lead a team of 3 to 5 software engineers to meet those objectives in a sustainable process. Some of the technologies your team will be using include: AWS (Lambda, SNS, S3, EC2, SQS, DynamoDB, etc.) Java or .net (Java, C#, VB.Net) Unit testing (Junit, MSTest, Moq) Relational databases (SQL) Web services (REST APIs, JSON, RestSharp) Git/github Linux (bash, cron) Job Requirements What we need from you: A passion for technology and bringing your visions to reality through code and leveraging state of the art technologies As a lead, you will take ownership of issues and challenges and will also be a proactive and effective communicator; this role requires successful verbal and written communication to many different audiences inside and outside of Careerbuilder Demonstrated ability to earn your teammates' trust and respect through clear, honest, and helpful communication We prefer you to have proven leadership experience, but also be a hands on, passionate coder BS in Computer Science or related field (preferred but not required) What you will receive: When you're focused on the goal, not the path - you can be more flexible, and that translates into more productive and satisfied employees. From flexible hours to volunteering during work hours to diverse education opportunities, CareerBuilder.com is committed to helping employees strike a balance. Training that positions you to continuously grow with ongoing learning and development courses; we never stop investing in our people. Summer Hours! Enjoy 1/2 day paid Fridays during Summer Hours Quarterly 24 hour Hackathons and bi-weekly personal development time to learn new skills Paid volunteer time and coordinated opportunities to give back to the community Bagel Fridays! Casual Dress Code and laid back environment; don't worry about buying new suits and dry cleaning bills! Comprehensive Medical, Dental & Vision Programs Education Reimbursement Program allowing up to $5k per year towards completion of a Bachelor's and non-MBA graduate degree, and up to $10K per year towards completion of an MBA! No strings attached! $400 Annual Reimbursement for Wellness Activities, including your gym membership! 401(k) Program with Strong Employer Match and 2 year vesting schedule! Five Star Company Paid Trips for top performers, pack your bags and get ready to experience luxury! CareerBuilder, LLC is proud to be an Equal Opportunity Employer. Applicants are considered for all positions without regard to race, color, religion, sex, national origin, age, disability, sexual orientation, ancestry, marital or veteran status."
"Quality Engineer TSS is currently seeking Quality Engineer for Industrial Manufacturer in the London, KY area. Qualified candidates must have experience in Quality Engineering or related degree. Job Requirements Directs sampling inspection, and testing of produced/received parts, components and materials to determine conformance to standards. Host customers for audits, react to customer complaints, follow through on all sorting and rework of suspect parts. Control of the product sorting/hold areas of the facility. Responsible for directing, instructing and organizing the work of parts sort area. Must follow-up with efficiency, effectiveness and safety of those assigned to work the area. Provides training and completes documentation of all quality training provided to Company employees and forwarding that paperwork to the appropriate individuals (Supervisors, Engineering, Human Resources, etc.). Develop PPAP documentation for specific products; including Quality Control Plans, Flowcharts, FMEA's, Inspection Reports, measurement/calculations coordination and PSW. Acts as Internal Auditor Coordinator and oversees the maintenance of all TS 16949 documentation. Applies statistical process control (SPC) methods for analyzing data to evaluate the current process and process changes. Works with supervisors and other responsible persons on determining root cause and developing corrective actions for all internal quality concerns. Participate in APQP for specific programs. Communicate with the customer as necessary to ensure all issues around assigned programs are resolved in a timely manner. Respond to customer corrective Action Requests. Develop gauging requirements for assigned programs. Monitor process capability to ensure required standards are maintained. Participate in Continuous Improvement programs. Perform workstation audits on assigned programs. Perform vendor quality audits as required. Prepares and presents technical and program information to team members and management. Accepts responsibility for subordinates?activities; Solicits and applies customer feedback (internal and external); Fosters quality focus in others. Provides computerized status report describing progress and concerns related to inspection activities, nonconforming items, and/or other items related to the quality of the process, material, or product. Reviews quality trends, tracks the root cause of problems, and coordinates correction actions. Provides input and recommendations to management on process of procedural system improvements, such as configuration management and operations functions. Work with technicians to ensure products are measured correctly and all data is compiled for on-time PPAP submissions. Will document and review supplier quality issues to the quality files daily, and communicate any needed Corrective Actions or plans from the suppliers. Formulates contingency plans, reviews control plans and FMEAs and makes necessary updates to the database as needed. Responsibilities include training; assigning and directing work of temporary re-work employees. All other duties as assigned. Training: TS 16949 Documentation:  APQP, PPAP, FMEA, MSA Internal Auditing Education Requirements: College degree or equivalent experience as determined by the Quality Manager. Skills: To perform this job successfully, an individual must be able to perform each essential job functions satisfactory. The duties and responsibilities listed above are representative of the knowledge, skill and/or ability required for the position. Excellent verbal and written skills: Proficient in computer software including Word, Excel, Access: Strong leadership skills: Good problem solving skills; Communicate well with others at all levels. Experience: To perform this position successfully, an individual should have a minimum of three (3) years in related field.  "

An I try to test this code:
library(tidytext)
library(stringr)

reg <- "([^A-Za-z_\\d#@']|'(?![A-Za-z_\\d#@]))"
tidy_df <- df %>%
  filter(!str_detect(text, "^RT")) %>%
  mutate(text = str_replace_all(text,
                                "https://t.co/[A-Za-z\\d]+|http://[A-Za-z\\d]+|&|<|>|RT|https",
                                "")) %>%
  unnest_tokens(word, text, token = "regex", pattern = reg) %>%
  filter(!word %in% stop_words$word,
         str_detect(word, "[a-z]"))

But I receive this error:
Error in stri_detect_regex(string, pattern, opts_regex = opts(pattern)) :
  argument `str` should be a character vector (or an object coercible to)

Is there any problem with the input data and this error happens? What can I do to fix it?

A: You forgot to load dplyr (library(dplyr)). This causes R to use stats::filter() rather than dplyr::filter(). The former function has a different signature and does not expose free_text to the inner str_detect().


text:
Q: Owl carousel 2: Lazy load for videos I have a carousel powered by Owl carousel v2 with lazy load enabled:
JS:
$('.owl-carousel').owlCarousel({
  lazyLoad: true
});

HTML:

which works OK. Then I tried to apply the same code to the HTML5 video tags I have:

   <video>
     <source class="owl-lazy" data-src="..." type="video/mp4">
   </video>

which didn't work. Any ideas how to enable it for videos too?

A: If anybody came accross the same issue, the solution I came up with is below:
// Lazy load for videos
var modalSlider = $('.owl-carousel');

modalSlider.on('changed.owl.carousel', function(event) {
  var current = event.item.index;
  var currentVideo = $(event.target).find('.owl-item').eq(current).find('video');
  var currentVideoSource = currentVideo.find('source');

  // Pause all videos
  var videos = modalSlider.find('video');

  if ( videos.length ) {
    videos.each(function() {
      $(this)[0].pause();
    });
  }

  // Play if video found
  if ( currentVideo.length ) {
    var currentVideoSrc = currentVideoSource.attr('data-src');
    currentVideoSource.attr('src', currentVideoSrc);
    currentVideo[0].load();
    currentVideo[0].play();
  }
});


text:
Q: How to rotate the map while changing direction I have integrated Google map in my application. I am able to find my current location.
I want map to auto rotate when i change the direction. How can i achieve this.
Thanks

A: Caveat: Not an expert
Based on Google API docs, sounds like you need to adjust the bearing, such as described in GroundOverlay#setBearing.

public final class GroundOverlay
A ground overlay is an image that is fixed to a map. A ground overlay
  has the following properties:
...
Bearing
The amount that the image should be rotated in a clockwise direction. The center of the rotation will be the image's anchor. This
  is optional and the default bearing is 0, i.e., the image is aligned
  so that up is north.

Example:
GoogleMap map = ...; // get a map.
BitmapDescriptor image = ...; // get an image.
LatLngBounds bounds = ...; // get a bounds
// Adds a ground overlay with 50% transparency.
GroundOverlay groundOverlay = map.addGroundOverlay(new GroundOverlayOptions()
   .image(image)
   .positionFromBounds(bounds)
   .transparency(0.5));


text:
Q: Call Toolbox operators of ENVI from IDL code Is it possible to call the clustering/classification algorithms included in the toolbox of ENVI (gui) from IDL (source code) and how?

A: I came across this example in ENVI's documentation which does exactly what I was looking for in IDL: http://www.exelisvis.com/docs/enviclassificationaggregationtask.html.


text:
Q: Accessing phonegap camera inside of child browser Im using childbrowser plugin for phone gap in my android application to view my external site. Is there a way to activate camera on a button tap on that external site ? I tried adding code bellow to my on button tap function but it doesnt work.
    pictureSource=navigator.camera.PictureSourceType;
    destinationType=navigator.camera.DestinationType;
    navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
    destinationType: destinationType.DATA_URL });
    function onFail(message) {
        alert('Failed because: ' + message);
    }
    function onSuccess(message) {
        alert('Success because: ' + message);
    }

And to run childbrowser(which works fine) I use:
window.plugins.childBrowser.showWebPage(_url, { showLocationBar: false });

A: The ChildBrowser is not supposed to expose the native functionality.
Is there a reason why you don't load directly the content from your remote site into the PhoneGap view?


text:
Q: .Net form controls drop by one "line" after selection Yes, I realize that's a bit of a vague title but I'm having a hard time stating the problem.  I have a .Net .aspx page that has a Master page, some Ajax, and an updatepanel.  My problem occurs on 2 different pages but in both cases I'm either selecting a radio button or a checkbox when the behavior occurs.  Immediately after selection the entire page moves down.  It does not scroll but instead it is like an extra  tag was inserted into the source.  I have done HTML source comparisons before and after this change and nothing is different.  I can only assume it is related to the updatepanel but I cannot determine where this may be happening.
I'd be happy to provide more information if you can direct me towards a solution.
Thanks!

A: I am not entirely sure if this will do it and there is not enough detail here to be sure, but have you tried setting RenderMode to inline on the UpdatePanel? Maybe that will do the trick. Otherwise go take a look at Fiddler and see what is coming back from the server. Alternate recommendation (if none of the above work) is to just get your result in Json and change the markup yourself with jQuery or something like it.

A: Incredible.  This was exactly the problem.  I've modified my code as follows and form stays in place after selection.  This was a simple case of selecting a radio button and having it auto-populate a dropdownlist.

[asp:UpdatePanel ID="panelValidation" runat="server" ChildrenAsTriggers="true" UpdateMode="Always" RenderMode="Inline"]
  [ContentTemplate]
      [asp:ValidationSummary ID="ValidationSummary1" runat="server"]
  [ContentTemplate]
[asp:UpdatePanel]

Thanks!


text:
Q: query as string type in controller class Can any one explain me...what is the meaning of below lines. I get it from This link.
String qryString = 'SELECT Id, title, UrlName, LastPublishedDate,LastModifiedById FROM KnowledgeArticleVersion WHERE (PublishStatus = \'online\' and Language = \'en_US\')';

A: I believe this is a type error. They would certainly somehow highlight the code  but that's gone wrong :)
Generally it is a string with a SOQL query to be used by the Database Class query() method.
It should be like this:
String qryString = 'SELECT Id, title, UrlName, LastPublishedDate,LastModifiedById FROM KnowledgeArticleVersion WHERE (PublishStatus = \'online\' and Language = \'en_US\')';

A: The link you refer is something more advanced about Knowledge development tutorial (and as @mast0r answered, there is a code formatting error), but the basic meaning of that query regards the "dynamic query" concept.
This approach is useful when using Database.query() method to perform a query.
It's a useful way when we want to have a dynamic query, instead of a "classic" one.
So, you can build a dynamic string that is the same "list of chars" that composes a query.
For example, you can query an Account in the classic way, by doing:
  Account a =  [SELECT ID, Name FROM ACCCOUNT WHERE Name = 'yourName'];

You can reach the same result by doing:
String myQuery = 'SELECT ID, Name FROM ACCCOUNT WHERE Name = 'yourName';
Account a = Database.query(myQuery);


text:
Q: How to use for loop for varying ul & li both? It may be already asked question,but I am unable to find it.
Below is the code I am using:
List<WebElement> allElementswithLetter = Driver.driver.findElements(By.xpath("//div[contains(@class,'page-bg clearfix search-locality')]/ul[i]/li"));

here ul is varying in every iteration in for loop, but my script is unable to identify it.
How to solve this issue?

A: Do a nested loop like the following then. First find the ul and then find the li under ul
List<WebElement> uls = driver.findElements(By.xpath("//div[contains(@class,'page-bg clearfix search-locality')]/ul[" + i + "]"));
for (WebElement element: uls){
   List<WebElement> lis = element.findElements(By.xpath("//li"));
   for (int j=0;j<lis.size();j++){
      //do some operation
   }
}

A: This part of your xpath "ul[i]" will try to find <ul> element having child element <i>. Instead of that, I believe you want the value of variable named i to be concatenated into your xpath.
You could try to achieve the latter via string concatenation like so :
String xpath = "//div[contains(@class,'page-bg clearfix search-locality')]/ul[" + i + "]/li"
List<WebElement> allElementswithLetter = Driver.driver.findElements(By.xpath(xpath));


text:
Q: wifi stops working after sometime while being connected in ubuntu 18.04 I noticed this problem now while using live connections that my internet is fine wifi is connected but the internet is not working.
Here is the output of lshw -C network:
  *-network
       description: Wireless interface
       product: Intel Corporation
       vendor: Intel Corporation
       physical id: 14.3
       bus info: pci@0000:00:14.3
       logical name: wlo1
       version: 30
       serial: 1c:1b:b5:ac:17:0a
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwlwifi driverversion=5.3.0-53-generic firmware=46.6bf1df06.0 ip=192.168.1.201 latency=0 link=yes multicast=yes wireless=IEEE 802.11
       resources: irq:16 memory:a531c000-a531ffff
  *-network
       description: Ethernet interface
       product: RTL810xE PCI Express Fast Ethernet controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: enp3s0
       version: 0a
       serial: 54:48:10:e7:31:14
       capacity: 100Mbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 firmware=rtl8107e-2_0.0.2 02/26/15 latency=0 link=no multicast=yes port=MII
       resources: irq:16 ioport:3000(size=256) memory:a5204000-a5204fff memory:a5200000-a5203fff

I've not changed any drivers.
Thanks in advance

A: Your wireless may be dropping because of power management; that is, the feature where the card partially powers down to save battery power during periods of inactivity and then, ideally, powers back up seamlessly when activity resumes. Let's disable power saving to see if it helps. From the terminal:
sudo sed -i 's/3/2/' /etc/NetworkManager/conf.d/*

Your wireless may be dropping because the channel to which it was connected has suddenly changed because of autoselection.
Please check the settings in the router. WPA2-AES is preferred; not any WPA and WPA2 mixed mode and certainly not TKIP. Second, if your router is capable of N speeds, you may have better connectivity with a channel width of 20 MHz in the 2.4 GHz band instead of automatic 20/40 MHz, although it is likely to affect N speeds. I recommend a fixed channel, either 1, 6 or 11, rather than automatic channel selection. Also, be certain the router is not set to use N speeds only; auto B, G and N is preferred.
Your wireless may be dropping because there are two wireless access points with the same name and password. This is typical when you have a 2.4 gHz segment and a 5 gHz segment of the same router. Your wireless may be roaming, looking for a better connection. If this is the case, I suggest that you rename the access points; something like myrouter2.4 and myrouter5.
After making these changes, reboot the router.
Next, I recommend that your regulatory domain be set explicitly. Check yours:
sudo iw reg get

If you get 00, that is a one-size-maybe-fits-all setting. Find yours here: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Then set it temporarily:
sudo iw reg set IS

Of course, substitute your country code if not Iceland. Set it permanently:
sudo nano /etc/default/crda

Change the last line to read:
REGDOMAIN=IS

Proofread carefully, save and close the text editor.
Is there any improvement?


text:
Q: Use fwrite() at a certain position without overwriting content EDIT: For anyone else looking for an answer, I used this. Probably the fastest solution to the problem.

Suppose I have a very large test.txt file containing:
line1
line4
line5
line6

I wish to add line2 and line3 after line1. I use the following code to achieve this:
$file = fopen('test.txt', 'r+');
fseek($file, 5);
fwrite($file, "\r\nline2\r\nline3\r\n");

However, the txt file now becomes, with line4 and line5 being overwritten:
line1
line2
line3
line6

I get the same result with c+ mode in fopen. I can't use a or a+ as they just append content to the end of the file. I also can't read the whole file into a string and analyse it to make changes, as this file is really huge.
Any way to fix this problem?
Note: Any solutions that involve reading the whole file as a string and then making changes from there will not be feasible due to the large amount of content in the file. If there are any cheeky workarounds to add content to a few lines between the first and second line, it will be good enough. :D

A: Sadly, fopen and friends do not allow inserts, only appends. From their perspective, the file is a large, growable array. Therefore, there is no call to insert data, only to overwrite.
However, you can get around this in several ways. One easy way is to make a temporary file opened with a, fwrite line 1 into it from the original file, append lines 2 and 3, then write the rest of the original file into the temporary file, in chunks. Once you've transferred the whole file (without loading the whole thing into memory at once, notice), then you can move the temporary file on top of the original one.

A: You can do this by creating an array from each line. Then replace searched line with whatever you want.
$searchLine = 'line1';
$file = getcwd()."test.txt";
$lineArray = file( $file , FILE_IGNORE_NEW_LINES );
$lineArray[$searchLine] =  $searchLine."\r\nline2\r\nline3\r\n"; // Replace the line with new ones
file_put_contents( $filename , implode( PHP_EOL, $lineArray) ); // Put the content


text:
Q: How do I alter an HTML page that is currently visited so that the user sees it? I'm working on a small project at the momment, using an ESP32, and the Arduino IDE.
I set up a basic server interface via multiple client.println commands.
Basically there is one button, that lets me start a stepper motor. There's also an IR sensor hooked up. I would like to give the user a notification on the open page, as soon as the IR sensor gives a signal.
I tried with printing to the serial monitor in Arduino IDE to check the functionality of the sensor and it works there. Now, my thought was that I could just do
if(detection == LOW) {
   // Serial.print("obstacle detected\n");
   client.println("SOME KIND OF MESSAGE");
}
else{
   // Serial.print("no obstacle!\n");
}

But unfortunately it doesn't do the trick.
Could somebody please guide me in the right direction?

A: After the webside is loaded on the client side, it is static. You delivered the HTML once, and the Client/Server Connection is closed afterwards. Rewriting does not deliver your new HTML Code to the Client.
What you could do:
Use some sort of polling with AJAX and JavaScript. Let your webside check for updates every 60 Seconds for example.

A: another option is add:

in your html.
Advice
The best solution should be a static html index page
with javascript that performs requests to an API and changes the page consequently.
in this way you need to download only changes and you the whole page (a really bad thing if you have images on it)


text:
Q: Почему парсится только первый матч Выводит в консоль только первый матч, а хотелось бы побольше. Подскажите как исправить, только начал изучать данную библиотеку.
import requests
from bs4 import BeautifulSoup

def main():

    url = 'https://www.gosugamers.net/dota2/matches'
    page = requests.get(url)
    soup = BeautifulSoup(page.text, "html.parser")

    results = soup.find_all('div', attrs={'class':'cell', 'id': 'matches'})

    for result in results:
        team1 = result.find('span', attrs={'class':'team-1'}).text
        team2 = result.find('span', attrs={'class':'team-2'}).text
        print(team1 +  'vs' + team2)

main()

A: Не работает, потому что в переменной results у вас находится объект ResultSet с всего одним элементом (т.к элементов с id=="matches" на странице больше нет), и поэтому проход в цикле for по нему происходил в одну итерацию, из-за чего метод find возвращал только лишь первое совпадение из целого div.
Я заменил метод find на метод find_all и немного "причесал" вывод, всё получилось.
Код:
import requests
from bs4 import BeautifulSoup

def main():
    url = 'https://www.gosugamers.net/dota2/matches'
    page = requests.get(url)
    soup = BeautifulSoup(page.text, "html.parser")

    results = soup.find('div', attrs={'class': 'cell', 'id': 'matches'})
    teams1 = [team.text.strip() for team in results.find_all('span', attrs={'class': 'team-1'})]
    teams2 = [team.text.strip() for team in results.find_all('span', attrs={'class': 'team-2'})]
    for teams in zip(teams1, teams2):
        print(f'{teams[0]} vs {teams[1]}')

main()

Вывод:
LBZS vs XERXIA
HR vs Nemiga
VP vs Entity
Keeper vs ALPHA
GG vs TSpirit
5RFS vs Dreamers
Balrogs vs CDUB
Saiyan vs TF
M11 vs Tsunami
iG.V vs PP
Balrogs vs Keeper
5RFS vs Qhali
ETERNITY vs ALPHA
Knights vs Mystique
ETERNITY vs 5RFS
PRX vs AnotherNA
Balrogs vs Dreamers
M11 vs Virgo