text:
Q: File Handling Alternative in Java I was wondering does java provides any way to implement programs stated below without file handling.
Lets say I want to make a program for hospital patients record or a phonebook in which I can add, delete and edit patient name, NIC number and phone number.. Making such a program with file handling will be difficult.
I know its a stupid question but I am new to Java..
Regards

A: What you describe sounds like a database. A database helps you store, retrieve and modify data. It usually does a better job than you (or me) ever will implementing this with files. A database is not strictly for use online, you can just install one on your local machine.
JBDC is a term you should use for googling

A: You should definitely use a data base management system. One simple approach is to use SQLite with the SQLiteJDBC JDBC driver. SQLite is a popular DBMS for embedded systems and SQLiteJDBC makes it easy to use in Java. This configuration is easy to set up and does not require any data base server to be running; your program will be entirely self-contained.

A: If you're describing a database from first principles I'd say you're probably far better off learning to do it the 'file' way first.
Once you've learned how to read and write files if you want (very) simple key/value storage you could use java.util.Properties which provides very simple file read/write operations.
BDB is another "pure java" option that will give you straightforward in-jvm key/value storage without the overhead of learning how to setup/run an external DMBS.


text:
Q: Multiplication application, visual basic. invalid cast exception Public Class Form1
Dim randomNumberOne As New Random
Dim randomNumberTwo As New Random

Dim ChildGrade As Integer
Dim strChildGrade As Integer
Dim strcorrectCounter As Integer
Dim Correctcounter As Integer = 0
Dim WrongCounter As Integer = 0
Dim totalQuestions As Integer = 0
Dim percent As Integer = 0

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    ChildGrade = InputBox("Enter your age ", "age")
    grade()

    FirstNumberlbl.Text = randomNumberOne.Next(0, 12)
    SecondNumberlbl.Text = randomNumberOne.Next(0, 12)

End Sub

Private Sub grade()
    If ChildGrade <= 4 Then
        Gradelbl.Text = "Preschool"
    ElseIf ChildGrade = 5 Then
        Gradelbl.Text = "Kindergarden"
    ElseIf ChildGrade <= 10 Then
        Gradelbl.Text = "Elementary"
    ElseIf ChildGrade <= 13 Then
        Gradelbl.Text = "Middle School"
    ElseIf ChildGrade <= 18 Then
        Gradelbl.Text = "High School"
    ElseIf ChildGrade > 18 Then
        Gradelbl.Text = "NA"
    End If
End Sub

Private Sub RandomNumberToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RandomNumberToolStripMenuItem.Click
    NumbersGroupBox.Enabled = False
    FirstNumberlbl.Text = randomNumberOne.Next(0, 12)
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
End Sub

Private Sub SingleTableToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SingleTableToolStripMenuItem.Click
    NumbersGroupBox.Enabled = True
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    FirstNumberlbl.Text = "1"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    FirstNumberlbl.Text = "2"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    FirstNumberlbl.Text = "3"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    FirstNumberlbl.Text = "4"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    FirstNumberlbl.Text = "5"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
    FirstNumberlbl.Text = "6"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
    FirstNumberlbl.Text = "7"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
    FirstNumberlbl.Text = "8"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
    FirstNumberlbl.Text = "9"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
    FirstNumberlbl.Text = "10"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
    FirstNumberlbl.Text = "11"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
    FirstNumberlbl.Text = "12"
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Private Sub CheckAnswer()
    If TextBox1.Text <> (FirstNumberlbl.Text * SecondNumberlbl.Text) Then
        MsgBox("Please try again", MsgBoxStyle.Information, "Answer")
        WrongCounter = WrongCounter + 1
        If WrongCounter = 2 Then
            MsgBox("The correct answer is " & FirstNumberlbl.Text * SecondNumberlbl.Text, MsgBoxStyle.Information, "Correct answer")
            WrongCounter = 0
            FirstNumberlbl.Text = randomNumberOne.Next(0, 12)
            SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
        End If
        TextBox1.Text = ""
    End If
End Sub

Private Sub rightAnswer()

    If FirstNumberlbl.Text * SecondNumberlbl.Text = TextBox1.Text Then
        Correctcounter = Correctcounter + 1
        NumberCorrectlbl.Text = Correctcounter
        TextBox1.Text = ""
        FirstNumberlbl.Text = randomNumberOne.Next(0, 12)
        SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    End If
    totalQuestions = totalQuestions + 1

End Sub

Private Sub Enterbtn_Click(sender As Object, e As EventArgs) Handles Enterbtn.Click
    CheckAnswer()
    rightAnswer()
    TotalCountlbl.Text = totalQuestions
    PercentCorrectlbl.Text = ((Correctcounter * 100) / (totalQuestions * 100)) * 100
End Sub

End Class
I'm creating a multiplication application in VB that keeps count of how many questions the user gets right and how many they get wrong. When I run the program, it works fine in counting the amount right and totaling up the percentage, but when I test for when they get it wrong I get this error. enter image description here
if the image isn't visible, the error says,
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "" to type 'Double' is not valid
The program points to the problem being in the if statement in the rightAnswer() sub class but i'm not exactly sure what is wrong with it.

A: The problem is you are trying to do calculations with strings. Strings are text, not numbers.
This is not a full answer but enough to get you to understand the problem and change your code to fix it.
Don't do any calculations on the contents of text boxes and/or labels. Use the correct variables for such tasks. Use the controls for simply retrieving and displaying. This will save you a lot of heart-ache in the long run.
So for example, don't do:
If TextBox1.Text <> (FirstNumberlbl.Text * SecondNumberlbl.Text) Then

You're checking a number in the TextBox to a calculation based on two labels, they are all text!
So think along the lines of doing calculations on a variable fit for purpose, an integer for example:
Example:
Dim FirstNumber As Integer
Dim SecondNumber As Integer

Use these for the calculations, then, display the result as text.
If you are expecting a floating point number, a decimal, change the variable type as needed.
In your 'CheckAnswer' subroutine you should starting thinking along the lines of:
    If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
        'We have something in the TextBox (you can check to allow only numbers to be entered in the TextBox.KeyDown/Press event)
        If Not Integer.Parse(TextBox1.Text) = (FirstNumber * SecondNumber) Then
            'Do what you need ...
        End If
    End If

There's a couple of other things too that could simplify your code.
You don't need 12 button events all doing the same thing.
In you Form1_Load Event put this:
    Dim bTags() As Button = {Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, Button9, Button10, Button11, Button12}
    For t As Integer = 0 To bTags.Count - 1
        bTags(t).Tag = t + 1
    Next

Then delete all your 12 Button Click events and replace them with:
Private Sub Buttons_Click(sender As Object, e As EventArgs) Handles Button9.Click, Button8.Click, Button7.Click, Button6.Click, Button5.Click, Button4.Click, Button3.Click, Button2.Click, Button12.Click, Button11.Click, Button10.Click, Button1.Click
    Dim selectedButton As Button = CType(sender, Button)
    FirstNumberlbl.Text = selectedButton.Tag.ToString
    SecondNumberlbl.Text = randomNumberTwo.Next(0, 12)
    TextBox1.Focus()
End Sub

Job done...
Also, you grade subroutine would be better of as a Select Case function:
In your Form1_Load replace:  grade() with Gradelbl.Text = Grade() and your grade() subroutine replaced with:
Private Function Grade() As String
    Select Case ChildGrade
        Case < 5 : Return "Preschool"
        Case = 5 : Return "Kindergarden"
        Case < 11 : Return "Elementary"
        Case < 14 : Return "Middle School"
        Case < 19 : Return "High School"
        Case Else : Return "N/A"
    End Select
End Function

I hope some of the advice will be of help.

A: What you need to do is cast the values of the textbox. For example:
Convert.toInt32(FirstNumberlbl.Text)

or
Dim firstNumber as Integer
Integer.TryParse(FirstNumberlbl.Text, firstNumber)

Or assign a variable to the textbox and cast the variable instead of the textbox.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sequential reading from a textfile Javafx Trying to read sequentially from a textfile. However, currently, only the last line is read when the button is clicked. I want to read all questions from the textfile one after the other. Here's my code:
   buttonNext.setOnAction(new EventHandler<ActionEvent>(){
    public void handle(ActionEvent E){

       java.io.File inFile = new java.io.File("QuestionSheet.txt");

       try {
           java.util.Scanner input = new java.util.Scanner(inFile);

            while (input.hasNext()){
                String[] lineOfCsv = input.nextLine().split(",");
                questionLabel.setText(lineOfCsv[0]);
                aRadio.setText(lineOfCsv[1]);
                bRadio.setText(lineOfCsv[2]);
                cRadio.setText(lineOfCsv[3]);
                dRadio.setText(lineOfCsv[4]);

            }

        } catch (java.io.IOException ex){
        System.out.println("Error reading file " + ex.toString());
        }

       buttonNext.setText("Next Question");

    }
    });

A: To read each line seperatly keep a reference to the Scanner and call nextLine only once per button click. However this makes it difficult to make sure the Scanner is always properly closed. It would probably be simpler to read the lines to a List<String> and iterating through it instead:
Path filePath = Paths.get("QuestionSheet.txt");
List<String> lines = Files.readAllLines(filePath); // using nio for simplicity here

buttonNext.setOnAction(new EventHandler<ActionEvent>(){

    // iterator for stepwise iterating through the list
    private final Iterator<String> iterator = lines.iterator();

    @Override
    public void handle(ActionEvent event){
        if (iterator.hasNext()) {
            String[] lineOfCsv = iterator.next().split(",");
            questionLabel.setText(lineOfCsv[0]);
            aRadio.setText(lineOfCsv[1]);
            bRadio.setText(lineOfCsv[2]);
            cRadio.setText(lineOfCsv[3]);
            dRadio.setText(lineOfCsv[4]);
            buttonNext.setDisable(!iterator.hasNext());
        }

    }
});

A: Use buffer reader and input stream to read line by line, The reason is buffer reader contains a default read line function. which helps a lot.
buttonNext.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent E){
try{
FileInputStream fstream = new FileInputStream("QuestionSheet.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)   {
  System.out.println (strLine);
  String[] lineOfCsv = strLine.split(",");
  questionLabel.setText(lineOfCsv[0]);
  aRadio.setText(lineOfCsv[1]);
  bRadio.setText(lineOfCsv[2]);
  cRadio.setText(lineOfCsv[3]);
  dRadio.setText(lineOfCsv[4]);
}
in.close();
}catch (Exception e){
  System.err.println("Error: " + e.getMessage());
}


text:
Q: Как вставить DIV рядом с input Есть код:
<input type='text' value='1'/>

При выполнении данного кода получается отображение поля input и ВНИЗУ картинка. Как её установить рядом? Оборачивать в div ее обязательно, т.к. исначально картинки там нет, а появляется рядом она при нажатии ENTER по полю input.
A: Попробуй так! Вот демо

<input type='text' value='1'/>

A:
 - блочный элемент, поэтому всегда переносится на новую строку и занимает всю доступную ширину.
Вам необходимо либо добавить к диву стиль display: inline-block, либо добавить к обоим диву и инпуту float: left, либо заключить все в таблицу (в левом td инпут, в правом див).
Вообще варианты могут быть разные.
Еще в вашем коротком примере большое количество огрехов:
 1. Не закрыт тег , кстати, вообще откажитесь от его использования в пользу стилей.
 2. Атрибуты width, height задавайте опять же через стили.
 3. Заключайте параметры атрибутов в двойные кавычки.
 4.  не требует закрывающего тега, то есть пишется так же, как <input>, в вашем случае.
Советую вам пройти какой-нибудь курс html, css.


text:
Q: How to insert an array into a hidden input in jquery I have a table that contains rows. each rows have their own attribute called as data. I want to put all tr into a hidden input type. how can I do that?
I want to get the $('#valuePermission').val() in the server-side.
<form >
   <input type="hidden" name="valuePermission[]" id="valuePermission" value=""/>

name:1	type:a

name:2	type:b

name:3	type:c

 <button type="submit" id="btn">submit</button>
</form>

in server-side I want to have sth like this:
<?php $var=$_POST['valuePermission'];
if(isset($var && !empty($var))

    $var=json_decode($var);
foreach($var as $v=>$k)
    echo $v;
?>

the results is like this:
*5+sport+500001+soccer,*5+sport+500002+vollyball,*5+sport+500003+swimming,*5+sport+500004+running,*5+sport+500006+tenis,*5+sport+500007+table tenis
I want to have sth like this:
array[0]='5+sport+500001+soccer'
 array[1]='5+sport+500001+vollyball and ....

A: Pass it as json string JSON.stringify() can be used for that, then from server side decode it and use . Also prevent the default click event action(here form submission) otherwise form get submitted before hidden field value is updating, use event.preventDefault() for that. At last submit form using code.
<form >
   <input type="hidden" name="valuePermission" id="valuePermission" value=""/>

name:1	type:a

name:2	type:b

name:3	type:c

 <button type="submit" id="btn">submit</button>
</form>

Server side use json_decode() to decode the json string
<?php $var = json_decode($_POST['valuePermission']);
foreach($var as $v=>$k)
    echo $v;
?>

UPDATE :
The another method that you can try is create multiple hidden input
<form>
  <input type="hidden" name="valuePermission[]" value="" />
  <input type="hidden" name="valuePermission[]" value="" />
  <input type="hidden" name="valuePermission[]" value="" />

      name:1
      type:a

      name:2
      type:b

      name:3
      type:c

  <button type="button" id="btn">submit</button>
</form>

A: You can simply use input name valuePermission instead of valuePermission[], also use form action and method
<form id="myform" action="target.php" method="post" >
<input type="hidden" name="valuePermission" id="valuePermission" value=""/>

name:1	type:a

name:2	type:b

name:3	type:c

<button type="submit" id="btn">submit</button>
</form>

In target file
<?php
if(isset($_POST['valuePermission']))
{
    $var = explode('*',$_POST['valuePermission']);
    foreach($var as $k => $v)
    {
        echo $v;
        echo "
";
    }
}
?>

Modified for explode
$str = '*5+sport+500001+soccer,*5+sport+500002+vollyball,*5+sport+500003+swimming,*5+sport+500004+running,*5+sport+500006+tenis,*5+sport+500007+table tenis';
$str = explode('*',$str);

$newArray =array();
foreach(array_filter($str) as $val)
{
    $newArray[] = trim($val,',');
}
echo "
"; print_r($newArray);

This will give you:
Array
(
    [0] => 5+sport+500001+soccer
    [1] => 5+sport+500002+vollyball
    [2] => 5+sport+500003+swimming
    [3] => 5+sport+500004+running
    [4] => 5+sport+500006+tenis
    [5] => 5+sport+500007+table tenis
)


text:
Q: Microsoft WorkFlow tracking long running process on other computers I have read a great many posts about WF and am very impressed by what it claims to do.  I've been reading documentation and white papers and am also intimidated by the learning curve.  I have a rather different requirement than most developers who have been asking the "Will WF work for me" question though.  Most of the posts focus on human speed tasks: get an email, put together an order, send information to warehouse and billing and wait for their responses and so forth down the workflow persisting information when waiting for choices and taking the event from a person to continue the processing.
However, in my case humans are observers only.  We have a lot of developers running VERY long running tasks on number crunching computers (somewhere between 36 and 48 hour long number crunches).  The human interaction would be setting up the parameters for an execution, hitting a button to queue it up (if the crunching machines are busy) and then observing the resources used by the process and wait for it to complete.  Users aren't going to keep their application open for days, so persisting the information when they close or requesting it when they open the client is important.
I like the idea of WF taking care of the persisting information and being able to take care of the queue (though when we move to a priority queue, I'm sure I'll have to write the priority metric), but I don't know how it would work with holding onto a System.Diagnostic.Process object to track a running process on a remote machine.  And if it did, could I get the state information of the process (memory, CPU demand, time running) when needed?


text:
Q: Empty string ends for loop What's wrong in the below program (What's happening here)? It should break the for loop after the user inserts empty string (presses only ENTER), but in my case it ends in endless for loop. I tried what is in the comments with no success.
#include <stdio.h>
#include <string.h>

struct S {
  char str [10];
};

int main(void)
{
  int n;
  struct S strings [10];
  for (n = 0; n < 10; n++) {
    # fflush(stdout);
    scanf("%s", strings[n].str);
    if (strlen(strings[n].str) == 0)
      break;
    # getchar();
  }
  printf("done");
  return 0;
}

When I replace scanf with gets(strings[n].str); done is never printed. How would you fix it?
This sample solution works. Is there a difference in comparison to my code?

A: The enter key is not empty string, it is an ascii character or rather two characters a CR and LF (on Windows).

A: You shouldn't use strlen to find out if the input is empty.  As others have said, when you press ENTER you get one or two characters sent to you.
You could instead check the first character in the string and see if it is '\n' or '\r'

A: scanf returns exactly what you've input... i.e. a crlf pair I'd imagine!

A: The problem with using scanf is that it expects something, not an empty string. You solve this by using e.g. fgets instead of scanf:
if (fgets(strings[n].str, sizeof(strings[n].str), stdin))
{
    /* You got a string, it will contain the newline! */
}


text:
Q: Perl Regex on a mechanize->content page I am fiddling around in perl and I managed to retrieve a HTML page from a source. However I just want to retrieve 1 particulair line. The line starts with a date formatted as follow: dd/mm/YYYY.
The HTML is in displayed with print $resp->content(); $resp being a response from a $mechanice->submit_form();
This is where the resp is made:
my $resp = $m->submit_form(
//bunch of data
},
);

How do I achieve this? I am familiar with PHP but I just started with Perl.
Thanks

A: Here's an example from some Mechanize code that I have.
my $mech = WWW::Mechanize->new();
$mech->get("url that takes you to the page with the form");
$mech->submit_form(form_name => 'someform',
                   fields    => {'user_name' => 'user's
                                 'password'  => 'password'},
                   button    => 'submit');

return if not $mech->success();

my $content = $mech->content();
if ($content =~ m|(\d{2,2}/\d{2,2}/\d{4,4}.*)|g) {
  print "My line: $1\n";
}


text:
Q: Why can't a template that takes a value not accept an integral_constant and uses ()() to extract value? Here's a simple example:
#include <type_traits>

using test = std::bool_constant<std::bool_constant<true>()()>;

I would have thought that since std::integral_constant::operator() is a const expression, that this should work.
Repacing ()() with ::value does work,  but the question isn't regarding that.


text:
Q: Getting a type error saying my websocket variable is undefined I'm having a video playing in my page and I'm trying to capture the frames and send them to a server through a websocket.
I have established a connection with the server successfully having also done the websocket handshake.
However I get the following error in my postVideoToServer() function:

"TypeError: clientSocket is undefined" index.html:60:5

The clientsocket is actually the socket the client uses to communicate with the server. I have used this variable already in clientSocket.onopen to send data to the server successfully.
I did some research and found out that it means that a value is not of the expected type. It still doesn't make sense to me. Any explanation will be appreciated.
Here is part of my js code. If more is needed let me know.
  var bStop = true;
  var bOldBrowser = false;
  var video;
  var streamRecorder;
  var webcamstream;
  var clientSocket;

 function postVideoToServer(clientSocket,frame)
 {
      clientSocket.send(frame);
 }

 function draw(v, cc, w, h, c, clientSocket)
 {
       cc.drawImage(v, 0, 0, w, h);  //draw video frame on canvas
       var frameData =c.toDataURL(); //turn canvas to raw png format
       postVideoToServer(clientSocket,frameData);

       if(!bStop)
           setTimeout( function() { draw(v, cc, w, h, c, clientSocket) }, 40);   //40 * 25 = 1000 ==> draw canvas every 40 ms to have 25FPS
  }

  function startRecording(video, clientSocket)
  {
       video = document.querySelector('video');
       var canvas = document.getElementById('canvas');
       var canvasContext = canvas.getContext('2d');
       var width = video.videoWidth;
       var height = video.videoHeight;

       canvas.width = width;
       canvas.height = height;

       bStop = false;

      //establish connection with server
      establishSocketConnection(clientSocket,"ws://localhost:3000/web/project/Server.php");
      draw(video, canvasContext, width, height, canvas, clientSocket)
   }

    function establishSocketConnection(clientSocket,URL)
    {
        clientSocket = new WebSocket(URL); //create socket to server
        clientSocket.onopen = function (e)
        {
            console.log("socket open");
        }

        clientSocket.onclose = function (e)
        {
            console.log("Socket connection closed : "+e);
        }

        clientSocket.onerror = function(error)
        {
            alert("Failed to connect to server...Please try again later.");
        };

   }

The startRecording function is triggered when I click the button below
<button onclick="startRecording(video)" class="recordbutton">Turn camera on</button>

A: You neeed remove the clientSocket parameter from all functions and just use global variable. because even when you call:
 onclick="startRecording(video, clientSocket)"

clientSocket will be undefined (you didn't assing it any value) and you can't change it from inside function.


text:
Q: Are Python variables pointers? Or else, what are they? Variables in Python are just pointers, as far as I know.
Based on this rule, I can assume that the result for this code snippet:
i = 5
j = i
j = 3
print(i)

would be 3.
But I got an unexpected result for me, and it was 5.
Moreover, my Python book does cover this example:
i = [1,2,3]
j = i
i[0] = 5
print(j)

The result would be [5,2,3].
What am I understanding wrong?

A: They are not quite pointers; they are references to objects. Objects can be either mutable, or immutable. An immutable object is copied when it is modified. A mutable object is altered in-place. An integer is an immutable object, that you reference by your i and j variables. A list is a mutable object.
In your first example
i = 5
# The label i now references 5

j = i
# The label j now references what i references

j = 3
# The label j now references 3

print i
# i still references 5

In your second example:
i = [1, 2, 3]
# 'i' references a list object (a mutable object)
j = i
# 'j' now references the same object as 'i' (they reference the same mutable object)

i[0] = 5
# Sets first element of references object to 5

print j
# Prints the list object that 'j' references. It's the same one as 'i'.

A: Variables are not pointers. When you assign to a variable you are binding the name to an object. From that point onwards you can refer to the object by using the name, until that name is rebound.
In your first example the name i is bound to the value 5. Binding different values to the name j does not have any effect on i, so when you later print the value of i the value is still 5.
In your second example you bind both i and j to the same list object. When you modify the contents of the list, you can see the change regardless of which name you use to refer to the list.
Note that it would be incorrect if you said "both lists have changed". There is only one list but it has two names (i and j) that refer to it.
Related documentation

*

*Execution Model - Naming and Binding

A: Assignment doesn't modify objects; all it does is change where the variable points.  Changing where one variable points won't change where another one points.
You are probably thinking of the fact that lists and dictionaries are mutable types.  There are operators to modify the actual objects in-place, and if you use one of those, you will see the change in all variables pointing to the same object:
x = []
y = x
x.append(1)
# x and y both are now [1]

But assignment still just moves the pointer around:
x = [2]
# x now points to new list [2]; y still points to old list [1]

Numbers, unlike dictionaries and lists, are immutable. If you do x = 3; x += 2, you aren't transforming the number 3 into the number 5; you're just making the variable x point to 5 instead. The 3 is still out there unchanged, and any variables pointing to it will still see 3 as their value.
(In the actual implementation, numbers are probably not reference types at all; it's more likely that the variables actually contain a representation of the value directly rather than pointing to it. But that implementation detail doesn't change the semantics where immutable types are concerned.)

A: TLDR: Python names work like pointers with automatic de/referencing but do not allow explicit pointer operations. Other targets represent indirections, which behave similar to pointers.

The Python language spec does not define what names and such actually are, only how they behave. However, the behaviour can be explained with pointers.
The CPython implementation uses pointers of type PyObject* under the hood. As such, it is possible to translate name semantics to pointer operations. The key is to separate names from actual objects.
The example Python code includes both names (i) and objects (5).
i = 5  # name `i` refers to object `5`
j = i  # ???
j = 3  # name `j` refers to object `3`

This can be roughly translated to C code with separate names and objects.
int three=3, five=5;  // objects
int *i, *j;           // names
i = &five;   // name `i` refers to position of object `5`
j = i;       // name `j` refers to referent of `i`
j = &three;  // name `j` refers to position of object `3`

The important part is that "names-as-pointers" do not store objects! We did not define *i = five, but i = &five . The names and objects exist independent from each other.
Names only point to existing objects in memory.
When assigning from name to name, no objects are exchanged! When we define j = i, this is equivalent to j = &five. Neither i nor j are connected to the other.
+- name i -+ -\
               \
                --> + <five> -+
               /    |        5 |
+- name j -+ -/     +----------+

As a result, changing the target of one name does not affect the other. It only updates what that specific name points to.

Python also has other kinds of name-like elements: attribute references (i.j), subscriptions (i[j]) and slicing (i[:j]). Unlike names, which refer directly to objects, all three indirectly refer to elements of objects.
The example code includes both names (i) and a subscription (i[0]).
i = [1,2,3]  # name `i` refers to object `[1, 2, 3]`
j = i        # name `j` refers to referent of `i`
i[0] = 5     # ???

A CPython list uses a C array of PyObject* pointers under the hood. This can again be roughly translated to C code with separate names and objects.
typedef struct{
    int *elements[3];
} list;  // length 3 `list` type

int one = 1, two = 2, three = 3, five = 5;
list values = {&one, &two, &three};  // objects
list *i, *j;                         // names
i = &values;             // name `i` refers to object `[1, 2, 3]`
j = i;                   // name `j` refers to referent of `i`
i->elements[0] = &five;  // leading element of `i` refers to object `5`

The important part is that we did not change any names! We did change i->elements[0], the element of an object both our names point to.
Values of existing compound objects may be changed.
When changing the value of an object through a name, names are not changed. Both i and j still refer to the same object, whose value we can change.
+- name i -+ -\
               \
                --> + <values> -+
               /    |  elements | --> [1, 2, 3]
+- name j -+ -/     +-----------+

The intermediate object behaves similar to a pointer in that we can directly change what it points to and reference it from multiple names.

A: Python variables are names bound to objects
From the docs:

Names refer to objects. Names are introduced by name binding operations. Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use.

When you do
i = 5
j = i

that's the same as doing:
i = 5
j = 5

j doesn't point to i, and after the assignment, j doesn't know that i exists. j is simply bound to whatever i was pointing to at the time of assignment.
If you did the assignments on the same line, it would look like this:
i = j = 5

And the result would be exactly the same.
Thus, later doing
i = 3

doesn't change what j is pointing to - and you can swap it - j = 3 would not change what i is pointing to.
Your example doesn't remove the reference to the list
So when you do this:
i = [1,2,3]
j = i

It's the same as doing this:
i = j = [1,2,3]

so i and j both point to the same list. Then your example mutates the list:
i[0] = 5

Python lists are mutable objects, so when you change the list from one reference, and you look at it from another reference, you'll see the same result because it's the same list.
What you do probably want is a copy of the list, like this perhaps:
i = [1,2,3]
j = i.copy()

Note that both lists contain the same objects and if they are mutable they will be in the same mutated state when accessed from both lists because they are the same objects.

A: We call them references. They work like this
i = 5     # create int(5) instance, bind it to i
j = i     # bind j to the same int as i
j = 3     # create int(3) instance, bind it to j
print i   # i still bound to the int(5), j bound to the int(3)

Small ints are interned, but that isn't important to this explanation
i = [1,2,3]   # create the list instance, and bind it to i
j = i         # bind j to the same list as i
i[0] = 5      # change the first item of i
print j       # j is still bound to the same list as i

A: When you set j=3 the label j no longer applies (points) to i, it starts to point to the integer 3. The name i is still referring to the value you set originally, 5.

A: Whatever variable is on the left side of '=' sign is assigned with the value on the right side of '='
i = 5
j = i  --- j has 5
j = 3  --- j has 3 (overwrites the value of 5) but nothing has been changed regarding i
print(i)-- so this prints 5

A: In Python, everything is object including the memory pieces themselves that you are returned. That means, when new memory chunk is created (irrespective of what've you created: int, str, custom object etc.), you have a new memory object. In your case this is the assignment to 3 which creates a new (memory) object and thus has a new address.
If you run the following, you see what I mean easily.
i = 5
j = i
print("id of j: {}", id(j))
j = 3
print("id of j: {}", id(j))

IMO, memory wise, this is the key understanding/difference between C and Python. In C/C++, you're returned a memory pointer (if you use pointer syntax of course) instead of a memory object which gives you more flexibility in terms of changing the referred address.


text:
Q: Tanuki service wrapper logging I have a question about the Tanuki service wrapper:
My Java application is wrapped in it and I am missing some logging
when running it with the wrapper.

*

*Tanuki wrapper version: 3.2.3 (old, I know but it's due to practical reasons)

*Loglevels set to INFO:

wrapper.console.loglevel=INFO
wrapper.logfile.loglevel=INFO

The lines that are missing start with:
[main] INFO
[Thread-7] INFO
[main] WARN

For example this line:
[main] INFO org.eclipse.jetty.server.AbstractConnector - ...
They are also not logged in the logfile specified by wrapper.logfile
What can I do to display such lines in the wrapper?


text:
Q: Pass data from a component to a modal dialog in angular 4 I have an angular 4 application and I have 2 components a timeline and a modal dialog. When I double click on the timeline I want to open the modal dialog with the datas passed into the double click function.
So, in the timeline.component.ts, I have :
        Timeline.prototype.onTaskDoubleClick = function(task){
            console.log("Double click on task" + task.id);
            console.log(task);
            $('#addProjectForm').click();
        }

How can I do to pass the object 'task' from this function to the modal component ?

A: Use @Input and @Output for the flow.
Create a component container, and two other containers timeline and modal
inject both timeline and modal in the container component.
Now on click in Timeline component use the following
clickEmitter = new EventEmitter<task: any>()

doubleClick(task: any) {
  this.clickEmitter.emit(task);
}

Now bind this output to the container component as follows
<timeline  (clickEmitter)="clickHandler($event)"></timeline>
<modal [task]="modalInput"></modal>

Now the task container can get this from the conatiner as follows.
In Container Component
modalInput: any;

clickHandler(task) {
  this.modalInput = task;
}

Now, this can be recieved by Modal component as follows,
@Input
task


text:
Q: Проблема правильного позиционирования точек прямоугольника при его повороте Ссылка: jsfiddle
Используемая библиотека Raphael.js и плагин Raphael.FreeTransform.
Используемые технологии: SVG, JavaScript.
Строки:
инициализация холста: 125;
функция для перемещения точек:  260.
Проблема: Если повернуть прямоугольник на определенный угол поворота и после попробовать передвинуть точки для изменения его размера, то точки будут неправильно себя вести при перемещении.
Помогите, пожалуйста, исправить данную проблему..

(function(win, Raphael) {
    'use strict';

    function Paper() {
        var self = this;

        self.elementId = 'paper';
        self.width     = win.innerWidth;
        self.height    = win.innerHeight;
        self.paper     = {};
    }

    Paper.prototype.Init = function(args) {
        var self = this;
        var elementId;
        var width;
        var height;

        try {
            args = args || {};

            elementId = args.id || self.elementId;
            width     = args.width || self.width;
            height    = args.height || self.height;

            self.paper = Raphael(elementId, width, height);
        }
        catch(error) {
            console.error(error);
        }

        return self;
    };

    Paper.prototype.get = function() {
        var paper = {};

        try {
            paper = this.paper;
        }
        catch(error) {
            console.error(error);
        }

        return paper;
    };

    win.Paper = win.Paper || new Paper;
})(typeof window !== 'undefined' ? window : this, Raphael);

(function(win) {
    'use strict';

    if(typeof win.Paper !== 'object') {
        return false;
    }

    function Shape() {
        var self = this;

        self.properties = {
            circleOptions : {
                fill            : '#FFD100',
                fillOpacity     : 1,
                stroke          : '#FFD100',
                strokeOpacity   : 1,
                strokeWidth     : 3,
                strokeLinecap   : 'round',
                strokeLinejoin  : 'round',
                strokeDasharray : 0
            },
            rectOptions   : {
                fill            : '#FFF20F',
                fillOpacity     : 1,
                stroke          : '#FFD103',
                strokeOpacity   : 1,
                strokeWidth     : 3,
                strokeLinecap   : 'round',
                strokeLinejoin  : 'round',
                strokeDasharray : 0
            }
        };
    }

    Shape.prototype.addPoint = function(x, y, r, properties) {
        var self    = this;
        var element = {};

        try {
            x          = x || 0;
            y          = y || 0;
            r          = r || 5;
            properties = properties || {};

            element = win.Paper.get().circle(x, y, r).attr({
                'fill'             : properties.fill || self.properties.circleOptions.fill,
                'fill-opacity'     : properties.fillOpacity || self.properties.circleOptions.fillOpacity,
                'stroke'           : properties.stroke || self.properties.circleOptions.stroke,
                'stroke-opacity'   : properties.strokeOpacity || self.properties.circleOptions.strokeOpacity,
                'stroke-width'     : properties.strokeWidth || self.properties.circleOptions.strokeWidth,
                'stroke-linecap'   : properties.strokeLinecap || self.properties.circleOptions.strokeLinecap,
                'stroke-linejoin'  : properties.strokeLinejoin || self.properties.circleOptions.strokeLinejoin,
                'stroke-dasharray' : properties.strokeDasharray || self.properties.circleOptions.strokeDasharray
            });

            element[0].setAttributeNS(null, 'id', element.id);
        }
        catch(error) {
            console.error(error);
        }

        return {
            'element' : element,
            'coords'  : {
                'x' : x,
                'y' : y,
                'r' : r
            }
        };
    };

    win.Paper.Shape = new Shape();
})(typeof window !== 'undefined' ? window : this);

(function(win) {
  var groupElements;
  var radius = 10;
  var pathData;
  var rectangle;
  var point1;
  var point2;
  var point3;
  var point4;
  var _objects = {
    'paths'  : {},
    'points' : {}
  };
  var path = {};
  var pointElements = {};
  var customizationOptions = {
    fill           : '#FFFFFF',
    fillOpacity    : 1,
    stroke         : '#000000',
    strokeOpacity  : 0.5,
    strokeWidth    : 1,
    strokeLinecap  : 'round',
    strokeLinejoin : 'round'
  };
  var freeTransformOptions          = {
    attrs     : {
      'fill'            : customizationOptions.fill,
      'fill-opacity'    : customizationOptions.fillOpacity,
      'stroke'          : customizationOptions.stroke,
      'stroke-opacity'  : customizationOptions.strokeOpacity,
      'stroke-width'    : customizationOptions.strokeWidth,
      'stroke-linecap'  : customizationOptions.strokeLinecap,
      'stroke-linejoin' : customizationOptions.strokeLinejoin
    },
    draw      : [],
    distance  : 0,
    drag      : [],
    keepRatio : [],
    range     : {
      rotate : [-180, 180],
      scale  : [-99999, 99999]
    },
    rotate    : [],
    scale     : [],
    size      : 0,
    snap      : {
      drag   : 0,
      rotate : 0,
      scale  : 0
    },
    snapDist  : {
      drag   : 0,
      rotate : 0,
      scale  : 0
    }
  };
  var freeTransformObj;
  var resizeModule;

  // style options
  win.Paper.Shape.properties.rectOptions.strokeOpacity                = 0.5;
  win.Paper.Shape.properties.rectOptions.fillOpacity                  = 0.2;
  win.Paper.Shape.properties.circleOptions.radius                     = 10;
  win.Paper.Shape.properties.circleOptions.strokeWidth                = 0;
  win.Paper.Shape.properties.circleOptions.fillOpacity                = 0.7;

  // rotate options
  freeTransformOptions.distance = 1.3;
  freeTransformOptions.size     = 5;
  freeTransformOptions.rotate   = ['axisX', 'axisY'];

  win.Paper.Init({
    id     : 'paper',
    width  : 1024,
    height : 1024
  });

  pathData = [['M', 105, 105], ['L', 250, 105], ['L', 250, 150], ['L', 105, 150], ['Z']];
  rectangle = win.Paper.get().path(pathData).attr({
    'fill'             : win.Paper.Shape.properties.rectOptions.fill,
    'fill-opacity'     : win.Paper.Shape.properties.rectOptions.fillOpacity,
    'stroke'           : win.Paper.Shape.properties.rectOptions.stroke,
    'stroke-opacity'   : win.Paper.Shape.properties.rectOptions.strokeOpacity,
    'stroke-width'     : win.Paper.Shape.properties.rectOptions.strokeWidth,
    'stroke-linecap'   : win.Paper.Shape.properties.rectOptions.strokeLinecap,
    'stroke-linejoin'  : win.Paper.Shape.properties.rectOptions.strokeLinejoin,
    'stroke-dasharray' : win.Paper.Shape.properties.rectOptions.strokeDasharray
 });
  point1 = win.Paper.Shape.addPoint(pathData[0][1], pathData[0][2], radius).element;
  point2 = win.Paper.Shape.addPoint(pathData[1][1], pathData[1][2], radius).element;
  point3 = win.Paper.Shape.addPoint(pathData[2][1], pathData[2][2], radius).element;
  point4 = win.Paper.Shape.addPoint(pathData[3][1], pathData[3][2], radius).element;

  groupElements = win.Paper.get().set();
  groupElements.push(rectangle);
  groupElements.push(point1);
  groupElements.push(point2);
  groupElements.push(point3);
  groupElements.push(point4);

  for(var key in groupElements) {
    if(groupElements.hasOwnProperty(key)) {
      if(groupElements[key].type === 'path') {
        path['element'] = groupElements[key];

        _objects.paths[groupElements[key].id] = {
          path          : path,
          pointElements : pointElements
        };
      }
      else {
        if(groupElements[key].type === 'circle') {
          pointElements[groupElements[key].id] = {
            path         : path,
            pointElement : groupElements[key],
            index        : key - 1
          };

          _objects.points[groupElements[key].id] = pointElements[groupElements[key].id];
        }
      }
    }
  }

  freeTransformObj =  win.Paper.get().freeTransform(groupElements, freeTransformOptions);
  resizeModule = new resize();

  groupElements.drag(function onmove(dx, dy, x, y, event) {
    resizeModule.move(dx, dy);
  }, function onstart(x, y, event) {
    resizeModule.start(x, y, event);
  }, function onend(event) {
    resizeModule.end(event);
  });

  function resize() {
   var pathElement  = {};
    var currentElement;
    var path         = [];
    var index        = 0;
    var pointElement = {};
    var posX         = 0;
    var posY         = 0;

    this.start = function(x, y, event) {
      if(currentElement = event.target || event.srcElement) {
        if(_objects.points[currentElement.id]) {
          pointElement = _objects.points[currentElement.id].pointElement;
          pathElement  = _objects.points[pointElement.id].path.element;
          index        = _objects.points[pointElement.id].index;

          posX = pointElement.attrs.cx;
          posY = pointElement.attrs.cy;

          path   = pathElement.getPath();
        }
      }
    };

    this.move = function(dx, dy) {
      var x           = 0;
      var y           = 0;
      var pointElements;
      var bbox;
      var middlePoint = {};
      var point;

      if(currentElement.nodeName === 'circle' && path.length) {
        x = posX + dx;
        y = posY + dy;

        pointElement.attr({cx : x});
        path[index][1] = x;

        pointElement.attr({cy : y});
        path[index][2] = y;

        pathElement.attr({
          path : path
        });
      }
    };

    this.end = function(event) {};
  }
})(typeof window !== 'undefined' ? window : this);
#paper {
  min-height : 768px;
}

A: В случае с поворотом координата при перемещении мышью зависит от обоих смещений(по X и по Y), необходимо учесть угол поворота, как то так:
this.move = function(dx, dy) {
    ...
    let angle = groupElements.freeTransform.attrs.rotate/180*Math.PI;
    y = posY + dy*Math.cos(angle) - dx*Math.sin(angle);
    x = posX + dy*Math.sin(angle) + dx*Math.cos(angle);
    ...
}

(function(win, Raphael) {
    'use strict';

    function Paper() {
        var self = this;

        self.elementId = 'paper';
        self.width     = win.innerWidth;
        self.height    = win.innerHeight;
        self.paper     = {};
    }

    Paper.prototype.Init = function(args) {
        var self = this;
        var elementId;
        var width;
        var height;

        try {
            args = args || {};

            elementId = args.id || self.elementId;
            width     = args.width || self.width;
            height    = args.height || self.height;

            self.paper = Raphael(elementId, width, height);
        }
        catch(error) {
            console.error(error);
        }

        return self;
    };

    Paper.prototype.get = function() {
        var paper = {};

        try {
            paper = this.paper;
        }
        catch(error) {
            console.error(error);
        }

        return paper;
    };

    win.Paper = win.Paper || new Paper;
})(typeof window !== 'undefined' ? window : this, Raphael);

(function(win) {
    'use strict';

    if(typeof win.Paper !== 'object') {
        return false;
    }

    function Shape() {
        var self = this;

        self.properties = {
            circleOptions : {
                fill            : '#FFD100',
                fillOpacity     : 1,
                stroke          : '#FFD100',
                strokeOpacity   : 1,
                strokeWidth     : 3,
                strokeLinecap   : 'round',
                strokeLinejoin  : 'round',
                strokeDasharray : 0
            },
            rectOptions   : {
                fill            : '#FFF20F',
                fillOpacity     : 1,
                stroke          : '#FFD103',
                strokeOpacity   : 1,
                strokeWidth     : 3,
                strokeLinecap   : 'round',
                strokeLinejoin  : 'round',
                strokeDasharray : 0
            }
        };
    }

    Shape.prototype.addPoint = function(x, y, r, properties) {
        var self    = this;
        var element = {};

        try {
            x          = x || 0;
            y          = y || 0;
            r          = r || 5;
            properties = properties || {};

            element = win.Paper.get().circle(x, y, r).attr({
                'fill'             : properties.fill || self.properties.circleOptions.fill,
                'fill-opacity'     : properties.fillOpacity || self.properties.circleOptions.fillOpacity,
                'stroke'           : properties.stroke || self.properties.circleOptions.stroke,
                'stroke-opacity'   : properties.strokeOpacity || self.properties.circleOptions.strokeOpacity,
                'stroke-width'     : properties.strokeWidth || self.properties.circleOptions.strokeWidth,
                'stroke-linecap'   : properties.strokeLinecap || self.properties.circleOptions.strokeLinecap,
                'stroke-linejoin'  : properties.strokeLinejoin || self.properties.circleOptions.strokeLinejoin,
                'stroke-dasharray' : properties.strokeDasharray || self.properties.circleOptions.strokeDasharray
            });

            element[0].setAttributeNS(null, 'id', element.id);
        }
        catch(error) {
            console.error(error);
        }

        return {
            'element' : element,
            'coords'  : {
                'x' : x,
                'y' : y,
                'r' : r
            }
        };
    };

    win.Paper.Shape = new Shape();
})(typeof window !== 'undefined' ? window : this);

(function(win) {
  var groupElements;
  var radius = 10;
  var pathData;
  var rectangle;
  var point1;
  var point2;
  var point3;
  var point4;
  var _objects = {
    'paths'  : {},
    'points' : {}
  };
  var path = {};
  var pointElements = {};
  var customizationOptions = {
    fill           : '#FFFFFF',
    fillOpacity    : 1,
    stroke         : '#000000',
    strokeOpacity  : 0.5,
    strokeWidth    : 1,
    strokeLinecap  : 'round',
    strokeLinejoin : 'round'
  };
  var freeTransformOptions          = {
    attrs     : {
      'fill'            : customizationOptions.fill,
      'fill-opacity'    : customizationOptions.fillOpacity,
      'stroke'          : customizationOptions.stroke,
      'stroke-opacity'  : customizationOptions.strokeOpacity,
      'stroke-width'    : customizationOptions.strokeWidth,
      'stroke-linecap'  : customizationOptions.strokeLinecap,
      'stroke-linejoin' : customizationOptions.strokeLinejoin
    },
    draw      : [],
    distance  : 0,
    drag      : [],
    keepRatio : [],
    range     : {
      rotate : [-180, 180],
      scale  : [-99999, 99999]
    },
    rotate    : [],
    scale     : [],
    size      : 0,
    snap      : {
      drag   : 0,
      rotate : 0,
      scale  : 0
    },
    snapDist  : {
      drag   : 0,
      rotate : 0,
      scale  : 0
    }
  };
  var freeTransformObj;
  var resizeModule;

  // style options
  win.Paper.Shape.properties.rectOptions.strokeOpacity                = 0.5;
  win.Paper.Shape.properties.rectOptions.fillOpacity                  = 0.2;
  win.Paper.Shape.properties.circleOptions.radius                     = 10;
  win.Paper.Shape.properties.circleOptions.strokeWidth                = 0;
  win.Paper.Shape.properties.circleOptions.fillOpacity                = 0.7;

  // rotate options
  freeTransformOptions.distance = 1.3;
  freeTransformOptions.size     = 5;
  freeTransformOptions.rotate   = ['axisX', 'axisY'];

  win.Paper.Init({
    id     : 'paper',
    width  : 1024,
    height : 1024
  });

  pathData = [['M', 105, 105], ['L', 250, 105], ['L', 250, 150], ['L', 105, 150], ['Z']];
  rectangle = win.Paper.get().path(pathData).attr({
    'fill'             : win.Paper.Shape.properties.rectOptions.fill,
    'fill-opacity'     : win.Paper.Shape.properties.rectOptions.fillOpacity,
    'stroke'           : win.Paper.Shape.properties.rectOptions.stroke,
    'stroke-opacity'   : win.Paper.Shape.properties.rectOptions.strokeOpacity,
    'stroke-width'     : win.Paper.Shape.properties.rectOptions.strokeWidth,
    'stroke-linecap'   : win.Paper.Shape.properties.rectOptions.strokeLinecap,
    'stroke-linejoin'  : win.Paper.Shape.properties.rectOptions.strokeLinejoin,
    'stroke-dasharray' : win.Paper.Shape.properties.rectOptions.strokeDasharray
 });
  point1 = win.Paper.Shape.addPoint(pathData[0][1], pathData[0][2], radius).element;
  point2 = win.Paper.Shape.addPoint(pathData[1][1], pathData[1][2], radius).element;
  point3 = win.Paper.Shape.addPoint(pathData[2][1], pathData[2][2], radius).element;
  point4 = win.Paper.Shape.addPoint(pathData[3][1], pathData[3][2], radius).element;

  groupElements = win.Paper.get().set();
  groupElements.push(rectangle);
  groupElements.push(point1);
  groupElements.push(point2);
  groupElements.push(point3);
  groupElements.push(point4);

  for(var key in groupElements) {
    if(groupElements.hasOwnProperty(key)) {
      if(groupElements[key].type === 'path') {
        path['element'] = groupElements[key];

        _objects.paths[groupElements[key].id] = {
          path          : path,
          pointElements : pointElements
        };
      }
      else {
        if(groupElements[key].type === 'circle') {
          pointElements[groupElements[key].id] = {
            path         : path,
            pointElement : groupElements[key],
            index        : key - 1
          };

          _objects.points[groupElements[key].id] = pointElements[groupElements[key].id];
        }
      }
    }
  }

  freeTransformObj =  win.Paper.get().freeTransform(groupElements, freeTransformOptions);
  resizeModule = new resize();

  groupElements.drag(function onmove(dx, dy, x, y, event) {
    resizeModule.move(dx, dy);
  }, function onstart(x, y, event) {
    resizeModule.start(x, y, event);
  }, function onend(event) {
    resizeModule.end(event);
  });

  function resize() {
   var pathElement  = {};
    var currentElement;
    var path         = [];
    var index        = 0;
    var pointElement = {};
    var posX         = 0;
    var posY         = 0;

    this.start = function(x, y, event) {
      if(currentElement = event.target || event.srcElement) {
        if(_objects.points[currentElement.id]) {
          pointElement = _objects.points[currentElement.id].pointElement;
          pathElement  = _objects.points[pointElement.id].path.element;
          index        = _objects.points[pointElement.id].index;

          posX = pointElement.attrs.cx;
          posY = pointElement.attrs.cy;

          path   = pathElement.getPath();
        }
      }
    };

    this.move = function(dx, dy) {
      var x           = 0;
      var y           = 0;
      var pointElements;
      var bbox;
      var middlePoint = {};
      var point;

      if(currentElement.nodeName === 'circle' && path.length) {
        let angle = groupElements.freeTransform.attrs.rotate/180*Math.PI;

        y = posY + dy*Math.cos(angle) - dx*Math.sin(angle);
        x = posX + dy*Math.sin(angle) + dx*Math.cos(angle);

        pointElement.attr({cx : x});
        path[index][1] = x;

        pointElement.attr({cy : y});
        path[index][2] = y;

        pathElement.attr({
          path : path
        });
      }
    };

    this.end = function(event) {};
  }
})(typeof window !== 'undefined' ? window : this);
#paper {
  min-height : 768px;
}


text:
Q: How to sign a PDF document in the right place (C# , ITextSharp)
There are a lot of posts regarding how to sign a pdf document from c#, none of them seems to answer my question: how to sign a PDF document in the signature field.
So far I've tried something along the line of :
        PdfReader inputPdf = new PdfReader(this.localFap);
        FileStream signedPdf = new FileStream(this.outputFap, FileMode.Create);
        PdfStamper pdfStamper = PdfStamper.CreateSignature(inputPdf, signedPdf, '\0');

        IExternalSignature externalSignature = new X509Certificate2Signature(certClient, "SHA-1");
        PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
        signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(350, 48, 550, 73), inputPdf.NumberOfPages, "Signature");

But this seem to actually create a new field names "Signature" instead of putting the signature in the field that is visible bellow the label "Semnatura".
Note that I do not know what's the name/if if that field I need to fill in, nor does it appear as field when I scan the document.
Original document not signed


text:
Q: Parse String and Replace Letters Java At input i have some string : "today snowing know " , here i have 3 words , so i must to parse them is such way : every character i must compare with all other characters , and to sum how many same characters these words have , like exemple for "o" letter will be 2 (from "today" and "snowing")  or "w" letter will be 2 (from "know" and "snowing"). After that i must to replace these characters with number(transformed in char format) of letters. The result should be "13111 133211 1332".
What i did ?
First i tape some words and
    public void inputStringsForThreads () {

       boolean flag;

            do {

    // will invite to input
                stringToParse = Input.value();

                try {

                flag = true;

    // in case that found nothing , space , number and other special character , throws an exception
                if (stringToParse.equals("") | stringToParse.startsWith(" ") | stringToParse.matches(".*[0-9].*") | stringToParse.matches(".*[~`!@#$%^&*()-+={};:',.<>?/'_].*"))

                    throw new MyStringException(stringToParse);

                else  analizeString(stringToParse);
            }

            catch (MyStringException exception) {

                stringToParse = null;
                flag = false;
                exception.AnalizeException();
            }
          }
            while (!flag);
}

I eliminate spaces between words , and from those words make just one
   static void analizeString (String someString) {

// + sign treat many spaces as one
      String delimitator = " +";

// words is a String Array
      words = someString.split(delimitator);

// temp is a string , will contain a single word
      temp = someString.replaceAll("[^a-z^A-Z]","");

         System.out.println("=============== Words are : ===============");
      for (int i=0;i<words.length;i++)
          System.out.println((i+1)+")"+words[i]);
    }

So i try to compare for every word in part (every word is split in letters) with all letter from all words , But i don know how to count number of same letter and after replace letters with correct number of each letter??? Any ideas ?
// this will containt characters for every word in part
         char[] motot  =   words[id].toCharArray();

// this will containt all characters from all words
         char[] notot = temp.toCharArray();

   for (int i =0;i<words[i].length();i++)

               for (int j=0;j<temp.length ;j++)

               {
                   if (i == j) {

                       System.out.println("Same word");

                   }

                   else   if (motot[i] == notot[j] ) {

                       System.out.println("Found equal :"+lol[i]+" "+lol1[j]);

                   }}

A: For counting you might want to use a Map<Character, Integer> counter like java.util.HashMap. If getting a Value(Integer) using a specific key (Character) from counter is 'not null', then your value++ (leverage autoboxing). Otherwise put a new entry (char, 1) in the counter.
Replacing the letters with the numbers should be fairly easy then.

A: It is better to use Pattern Matching like this:
initially..
private Matcher matcher;
Pattern regexPattern = Pattern.compile( pattern );
matcher = regexPattern.matcher("");

for multiple patterns to match.
private final String[] patterns = new String [] {/* instantiate patterns here..*/}
private Matcher matchers[];
for ( int i = 0; i < patterns.length; i++) {
Pattern regexPattern = Pattern.compile( pattern[i] );
matchers[i] = regexPattern.matcher("");

}

and then for matching pattern.. you do this..
if(matcher.reset(charBuffer).find() ) {//matching pattern.}

for multiple matcher check.
for ( int i = 0; i < matchers.length; i++ ) if(matchers[i].reset(charBuffer).find() ) {//matching pattern.}

Don't use string matching, not efficient.
Always use CharBuffer instead of String.

A: Here is some C# code (which is reasonably similar to Java):
void replace(string s){

    Dictionary<char, int> counts = new Dictionary<char, int>();

    foreach(char c in s){
        // skip spaces
        if(c == ' ') continue;

        // update count for char c
        if(!counts.ContainsKey(c)) counts.Add(c, 1);
        else counts[c]++;
    }

    // replace characters in s
    for(int i = 0; i < s.Length; i++)
        if(s[i] != ' ')
            s[i] = counts[s[i]];
}

Pay attention to immutable strings in the second loop. Might want to use a StringBuilder of some sort.

A: Here is a solution that works for lower case strings only.  Horrible horrible code, but I was trying to see how few lines I could write a solution in.
public static String letterCount(String in) {
  StringBuilder out = new StringBuilder(in.length() * 2);
  int[] count = new int[26];
  for (int t = 1; t >= 0; t--)
    for (int i = 0; i < in.length(); i++) {
      if (in.charAt(i) != ' ') count[in.charAt(i) - 'a'] += t;
      out.append((in.charAt(i) != ' ') ? "" + count[in.charAt(i) - 'a'] : " ");
    }
  return out.substring(in.length());
}


text:
Q: AutoComplete Text Box in WPF I want to read the data through the auto complete text box through code behind. but i dont know how to get this.
here is the code.
List<string> suggestions=new List<string>();
suggestions.Add("First");
suggestions.Add("2nd");
suggestions.Add("3rd");
auto1.ItemSource=suggestions;

auto1 is the name of AutoComplete TextBox. but it shows the suggestions. but when i read data from auto1 through
auto1.Text.ToString();

it shows null.how to get data.


text:
Q: Scraping json webpage I am very new to web scraping and am having some trouble with scraping some NBA player data from nba.com. I first tried to scrape the page using bs4 but ran into an issue which after some research I believe is due to "XHR" from the articles I read. I was able to find a web address to the json formatted data, but my python program seems to bog down, and never load the data. Again I am very new at web scraping, but thought I'd see if I was way off track here... Any suggestions? Thanks! (Code Below)
import requests
import json

url = "http://stats.nba.com/stats/leaguedashplayerstats?College=&Conference=&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=&Height=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2017-18&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight="

resp = requests.get(url=url)
data = json.loads(resp.text)
print(data)

A: Give this a shot. It will produce all the categories from that page according to the title I've defined. Btw, you didn't get response in the first place with your initial try cause the webpage was expecting a User-Agent within your request to make sure that the request is not coming from a bot rather from any real browser. However, I faked it and found the response.
import requests

url = "http://stats.nba.com/stats/leaguedashplayerstats?College=&Conference=&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=&Height=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2017-18&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight="
resp = requests.get(url,headers={'User-Agent':'Mozilla/5.0'})
data = resp.json()

storage = data['resultSets']
for elem in storage:
    all_list = elem['rowSet']

    for item in all_list:
        Player_Id = item[0]
        Player_name = item[1]
        Team_Id = item[2]
        Team_abbr = item[3]
        print("Player_Id: {} Player_name: {} Team_Id: {} Team_abbr: {}".format(
            Player_Id,Player_name,Team_Id,Team_abbr))

A: Just realized that it is because the user agent headers are different... Once those are added it works


text:
Q: C++ Get File Name and Line Number of "Segmentation Fault" Linux x64 Without running GDB, but only the program itself.
edit: i've already seen such program but i can't figure how to do that myself :(

A: Tommie deserves credit for solving this.
I've detached his answer from GDB by using the somewhat standard backtrace utility from <execinfo.h>.
static void dumpstack(void){
    static void *backbuf[ 50 ];
    int levels;

    levels = backtrace( backbuf, 50 );
    backtrace_symbols_fd( backbuf, levels, STDERR_FILENO );

    return;
}

You can try opening a file and writing instead of STDERR_FILENO, but I'd avoid such heavy lifting in a crashed process.
On my system, the output looks like this:
Shadow:code dkrauss$ ./dumpy
0   dumpy                               0x0000000100000d81 dumpstack + 25
1   dumpy                               0x0000000100000d18 signal_handler + 47
2   libSystem.B.dylib                   0x00007fff86b1766a _sigtramp + 26
3   ???                                 0x0000000000000000 0x0 + 0
4   dumpy                               0x0000000100000a18 start + 52
FATAL: Segmentation Fault

So, it doesn't give file name + line number, but it does give function name + code offset, which you can translate easily enough.

A: Hmmm... you could try doing it this way...
struct sigaction g_sigact;

void panic(const char *fmt, ...){
    char buf[PANICBUF_LEN];
    va_list argptr;
    va_start(argptr, fmt);
    vsprintf(buf, fmt, argptr);
    va_end(argptr);
    fprintf(stderr, "%s\n", buf);
    exit(-1);
}
void init_signals(void){
    g_sigact.sa_handler = signal_handler;
    sigemptyset(&g_sigact.sa_mask);
    g_sigact.sa_flags = 0;
    sigaction(SIGINT, &g_sigact, (struct sigaction *)NULL);

    sigaddset(&g_sigact.sa_mask, SIGSEGV);
    sigaction(SIGSEGV, &g_sigact, (struct sigaction *)NULL);

    sigaddset(&g_sigact.sa_mask, SIGBUS);
    sigaction(SIGBUS, &g_sigact, (struct sigaction *)NULL);

    sigaddset(&g_sigact.sa_mask, SIGQUIT);
    sigaction(SIGQUIT, &g_sigact, (struct sigaction *)NULL);

    sigaddset(&g_sigact.sa_mask, SIGHUP);
    sigaction(SIGHUP, &g_sigact, (struct sigaction *)NULL);

    sigaddset(&g_sigact.sa_mask, SIGKILL);
    sigaction(SIGKILL, &g_sigact, (struct sigaction *)NULL);
}

static void signal_handler(int sig){
    if (sig == SIGHUP) g_keepRunning = 0;
    if (sig == SIGSEGV || sig == SIGBUS){
        dumpstack();
        panic("FATAL: %s Fault\n", (sig == SIGSEGV) ? "Segmentation" : ((sig == SIGBUS) ? "Bus" : "Unknown"));
    }
    if ((sig == SIGQUIT || (sig == SIGKILL) || (sig == SIGINT)) ;
}

static void dumpstack(void){
    /* Got this routine from http://www.whitefang.com/unix/faq_toc.html
    ** Section 6.5. Modified to redirect to file to prevent clutter
    */
    char dbx[160];
    sprintf(dbx, "echo -ne 'detach\n' | gdb --eval-command=where --pid=%d > %d.dump", getpid(), getpid());
    system(dbx);
    return;
}

When a segmentation fault is trapped, dumpstack gets invoked and prints the most recent stack-trace up to the point when it segmentation faulted and gets redirected to a file with a numeric pid of the process....

A: Why exactly do you not want to run gdb? You can detect the location of segfaults very easily if you use it.


text:
Q: Couldn't write image to file using AndroidViewClient vc.writeImageToFile("C:\image.png") code gives the following error:
File "C:\AndroidViewClientMaster\AndroidViewClient\src\com\dtmilano\android\viewclient.py", line 2309, in writeImageToFile
    self.device.takeSnapshot().writeToFile(filename, format)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 512, in getattr
    raise AttributeError(name)
AttributeError: writeToFile
What is wrong?

A: vc.writeImageToFile("C:\image.png")

should work correctly on AndroidViewClient >= 5.4.7


text:
Q: Understanding the recursive call mechanism for implementing a queue using a stack I'm trying to implement a Queue using a stack and recursive call, this is the class Stack and a few methods:
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class Node{
    public:
        int data;
        Node* next;
};

Node* top = NULL;

void push(int data){
    Node* node = new Node();
    node->data = data;
    node->next = top;
    top = node;
    cout << "pushato: " << node->data << "\n";
};

bool isempty(){
    if(top==NULL){
        return true;
    }else{
        return false;
    }
};

void pop(){
    if(isempty()){
        cout << "lo stack e vuoto.\n";
    }else{
        Node* ptr = top;
        top = top->next;
        cout << "eliminato: " << ptr->data << "\n";
        delete(ptr);
    }
};

Node* showtop(){
    if(!isempty()){
        cout << "l'elemento del top e: " << top->data << "\n";
        return top;
    }else{
        cout << "lo stack e vuoto.\n";
    }
};

And this is the struct for the Queue:
struct Queue{
    void enQueue(int x)
    {
        push(x);
    }

    int deQueue()
    {
        if (isempty()) {
            cout << "Q is empty";
            exit(0);
        }

        // pop an item from the stack
        int x = showtop()->data;
        pop();

        // if stack becomes empty, return
        // the popped item
        if (isempty()){
            return x;
        }

        // recursive call
        int item = deQueue();

        // push popped item back to the stack
        push(x);

        // return the result of deQueue() call
        return item;
    }
};

This is the main:
int main(int argc, char** argv) {
     Queue q;
    q.enQueue(1);
    q.enQueue(2);
    q.enQueue(3);

    cout << q.deQueue() << '\n';
    cout << q.deQueue() << '\n';
    cout << q.deQueue() << '\n';
    return 0;
}

And this is the output:
pushed:1
pushed:2
pushed:3
popped 3
popped 2
popped 1
pushed 2
pushed 3
1
popped 3
popped 2
pushed 3
2
popped 3
3

The code works fine and the output is totally correct, but I don't really get why after the recursive call ends and I return x in the if, all of the previous items get pushed into the stack? How push(x) adds the items into the stack again, without the element at the bottom?

A: To understand how the code pushes elements into the stack by means of push(x), consider the following Q/As regarding a queue with N elements inside it, with 1 as the bottom element and N as the top one:
Q: How many times the deQueue() function is called?
Answer: N times. The first time from main() and N-1 times recursively.
Q: There is an if statement in the deQueue() method which returns x. How many times the condition of this if statement satisfies?
Answer: Only once.
Q. So, how many times the code after the mentioned if statement (including the push(x) statement) is executed?
Answer: N-1 times.
Q: What is the first time that the push(x) line is executed?
Answer: It executes for the first time when its previous statement, i.e. int item = deQueue(); has returned normally without any recursions.
Q: In that case (first call of push(x)), what will be the value of x?
Answer: If the deQueue() return normally and do not recur, the value of x will be 1. But for the latest recursion before that, the value of x is 2.
Q: And what value will be the value of x for the next call to push(x)?
Answer: 3
Q: And for the rest?
Answer: 4, 5, ... N.

A: In your deQueue() function you have this piece of code which (if true) exits the program:
if (isempty()) {
    cout << "Q is empty";
    exit(0);
}

A few lines later you have:
if (isempty()){
    return x;
}

That can never be executed because you called exit(0) before.

A: It "pops" the bottom element of the stack by temporarily storing an element until it reaches the bottom, then putting them back as the recursive calls return.
Remove one item and save it for later:
int x = showtop()->data;
pop();

If it was the bottom item, return it:
if (isempty()){
    return x;
}

Otherwise, let a recursive call remove the bottom item and give it to us:
 int item = deQueue();

Now the stack contains all the items except the bottom one (item) and the one we removed (x), so we put the one we removed back on top:
push(x);

and pass along the bottom item that we got from recursing:
return item;

I suspect that what's tripping you up is that deQueue might return the value to a previous call to deQueue, not directly to main.
(Returning from a recursion is not like exiting a loop.)
More concretely, if your queue is
1 2 3

The first call will first store 1 in x, then recurse (the stack is now 2 3).
The second call stores 2 in its x and recurses (3).
The third call removes the 3, leaving an empty stack, and returns the 3 to its caller.
The second call then pushes back the 2 it took and returns 3 (2).
Then, the first call pushes back 1 and also returns 3 (1 2).


text:
Q: Extract specific data from JSON data from Google Cloud Vision I am quite new to Raspberry Pi and Python coding but I was successful in configuring Google Cloud Vision. However the JSON dump looks like:
{
    "responses": [
        {
            "faceAnnotations": [
                {
                    "angerLikelihood": "UNLIKELY",
                    "blurredLikelihood": "VERY_UNLIKELY",
                    "boundingPoly": {
                        "vertices": [
                            {
                                "x": 129
                            },
                            {
                                "x": 370
                            },
                            {
                                "x": 370,
                                "y": 240
                            },
                            {
                                "x": 129,
                                "y": 240
                            }
                        ]
                    },
                    "detectionConfidence": 0.99543685,
                    "fdBoundingPoly": {
                        "vertices": [
                            {
                                "x": 162,
                                "y": 24
                            },
                            {
                                "x": 337,
                                "y": 24
                            },
                            {
                                "x": 337,
                                "y": 199
                            },
                            {
                                "x": 162,
                                "y": 199
                            }
                        ]
                    },
                    "headwearLikelihood": "VERY_UNLIKELY",
                    "joyLikelihood": "VERY_UNLIKELY",
                    "landmarkingConfidence": 0.77542377,
                    "landmarks": [
                        {
                            "position": {
                                "x": 210.93373,
                                "y": 92.71409,
                                "z": -0.00025338508
                            },
                            "type": "LEFT_EYE"
                        },
                        {
                            "position": {
                                "x": 280.00177,
                                "y": 82.57283,
                                "z": 0.49017733
                            },
                            "type": "RIGHT_EYE"
                        },
                        {
                            "position": {
                                "x": 182.08047,
                                "y": 77.89372,
                                "z": 6.825161
                            },
                            "type": "LEFT_OF_LEFT_EYEBROW"
                        },
                        {
                            "position": {
                                "x": 225.82335,
                                "y": 72.88091,
                                "z": -13.963233
                            },
                            "type": "RIGHT_OF_LEFT_EYEBROW"
                        },
                        {
                            "position": {
                                "x": 260.4491,
                                "y": 66.19005,
                                "z": -13.798634
                            },
                            "type": "LEFT_OF_RIGHT_EYEBROW"
                        },
                        {
                            "position": {
                                "x": 303.87503,
                                "y": 59.69522,
                                "z": 7.8336163
                            },
                            "type": "RIGHT_OF_RIGHT_EYEBROW"
                        },
                        {
                            "position": {
                                "x": 244.57729,
                                "y": 83.701904,
                                "z": -15.022567
                            },
                            "type": "MIDPOINT_BETWEEN_EYES"
                        },
                        {
                            "position": {
                                "x": 251.58353,
                                "y": 124.68004,
                                "z": -36.52176
                            },
                            "type": "NOSE_TIP"
                        },
                        {
                            "position": {
                                "x": 255.39096,
                                "y": 151.87607,
                                "z": -19.560472
                            },
                            "type": "UPPER_LIP"
                        },
                        {
                            "position": {
                                "x": 259.96045,
                                "y": 178.62886,
                                "z": -14.095398
                            },
                            "type": "LOWER_LIP"
                        },
                        {
                            "position": {
                                "x": 232.35422,
                                "y": 167.2542,
                                "z": -1.0750997
                            },
                            "type": "MOUTH_LEFT"
                        },
                        {
                            "position": {
                                "x": 284.49316,
                                "y": 159.06075,
                                "z": -0.078973025
                            },
                            "type": "MOUTH_RIGHT"
                        },
                        {
                            "position": {
                                "x": 256.94714,
                                "y": 163.11235,
                                "z": -14.0897665
                            },
                            "type": "MOUTH_CENTER"
                        },
                        {
                            "position": {
                                "x": 274.47885,
                                "y": 125.8553,
                                "z": -7.8479633
                            },
                            "type": "NOSE_BOTTOM_RIGHT"
                        },
                        {
                            "position": {
                                "x": 231.2164,
                                "y": 132.60686,
                                "z": -8.418254
                            },
                            "type": "NOSE_BOTTOM_LEFT"
                        },
                        {
                            "position": {
                                "x": 252.96692,
                                "y": 135.81783,
                                "z": -19.805998
                            },
                            "type": "NOSE_BOTTOM_CENTER"
                        },
                        {
                            "position": {
                                "x": 208.6943,
                                "y": 86.72571,
                                "z": -4.8503814
                            },
                            "type": "LEFT_EYE_TOP_BOUNDARY"
                        },
                        {
                            "position": {
                                "x": 223.4354,
                                "y": 90.71454,
                                "z": 0.42966545
                            },
                            "type": "LEFT_EYE_RIGHT_CORNER"
                        },
                        {
                            "position": {
                                "x": 210.67189,
                                "y": 96.09362,
                                "z": -0.62435865
                            },
                            "type": "LEFT_EYE_BOTTOM_BOUNDARY"
                        },
                        {
                            "position": {
                                "x": 195.00711,
                                "y": 93.783226,
                                "z": 6.6310787
                            },
                            "type": "LEFT_EYE_LEFT_CORNER"
                        },
                        {
                            "position": {
                                "x": 208.30045,
                                "y": 91.73073,
                                "z": -1.7749802
                            },
                            "type": "LEFT_EYE_PUPIL"
                        },
                        {
                            "position": {
                                "x": 280.8329,
                                "y": 75.722244,
                                "z": -4.3266015
                            },
                            "type": "RIGHT_EYE_TOP_BOUNDARY"
                        },
                        {
                            "position": {
                                "x": 295.9134,
                                "y": 78.8241,
                                "z": 7.3644505
                            },
                            "type": "RIGHT_EYE_RIGHT_CORNER"
                        },
                        {
                            "position": {
                                "x": 281.82813,
                                "y": 85.56999,
                                "z": -0.09711724
                            },
                            "type": "RIGHT_EYE_BOTTOM_BOUNDARY"
                        },
                        {
                            "position": {
                                "x": 266.6147,
                                "y": 83.689865,
                                "z": 0.6850431
                            },
                            "type": "RIGHT_EYE_LEFT_CORNER"
                        },
                        {
                            "position": {
                                "x": 282.31485,
                                "y": 80.471725,
                                "z": -1.3341979
                            },
                            "type": "RIGHT_EYE_PUPIL"
                        },
                        {
                            "position": {
                                "x": 202.4563,
                                "y": 66.06882,
                                "z": -8.493092
                            },
                            "type": "LEFT_EYEBROW_UPPER_MIDPOINT"
                        },
                        {
                            "position": {
                                "x": 280.76108,
                                "y": 54.08935,
                                "z": -7.895889
                            },
                            "type": "RIGHT_EYEBROW_UPPER_MIDPOINT"
                        },
                        {
                            "position": {
                                "x": 168.31839,
                                "y": 134.46411,
                                "z": 89.73161
                            },
                            "type": "LEFT_EAR_TRAGION"
                        },
                        {
                            "position": {
                                "x": 332.23724,
                                "y": 109.35637,
                                "z": 90.81501
                            },
                            "type": "RIGHT_EAR_TRAGION"
                        },
                        {
                            "position": {
                                "x": 242.81676,
                                "y": 67.845825,
                                "z": -16.629877
                            },
                            "type": "FOREHEAD_GLABELLA"
                        },
                        {
                            "position": {
                                "x": 264.32065,
                                "y": 208.95119,
                                "z": -4.0186276
                            },
                            "type": "CHIN_GNATHION"
                        },
                        {
                            "position": {
                                "x": 183.4723,
                                "y": 179.30655,
                                "z": 59.87147
                            },
                            "type": "CHIN_LEFT_GONION"
                        },
                        {
                            "position": {
                                "x": 331.6927,
                                "y": 156.69931,
                                "z": 60.93835
                            },
                            "type": "CHIN_RIGHT_GONION"
                        }
                    ],
                    "panAngle": 0.41165036,
                    "rollAngle": -8.687789,
                    "sorrowLikelihood": "VERY_UNLIKELY",
                    "surpriseLikelihood": "VERY_UNLIKELY",
                    "tiltAngle": 0.2050134,
                    "underExposedLikelihood": "POSSIBLE"
                }
            ]
        }
    ]
}

Yes, it's an eyesore to look at. I am only wanting to extract the likelihood. Preferably in this format:
Anger likelihood is UNLIKEY
Joy likelihood is VERY_UNLIKELY
Sorrow likelihood is VERY_UNLIKELY
Suprise likelihood is VERY_UNLIKELY

Python code can be found here:
https://github.com/DexterInd/GoogleVisionTutorials/blob/master/camera-vision-face.py

A: You can go with dictionary comprehensions. Given that you have your response in variable result, the following code will output exactly what you want.
import json

likelihood = {
    attr[:len(attr) - 10].capitalize(): value
    for attr, value
        in json.loads(result)['responses'][0]['faceAnnotations'][0].items()
    if attr.find('Likelihood') != -1
}

print(*[
    '{} likelihood is {}'.format(e, p) for e, p in likelihood.items()
], sep='\n')

Keep in mind that this code works correctly if there is only one item in both responses and faceAnnotations arrays. If there's more, the code will handle only the first items. It's also kinda ugly.
In len(attr) - 10, 10 is the length of word "Likelihood".

A: Answered my own question in perhaps the most noobiest way:
    print "Anger likelihood is:",
    print(response['responses'][0]['faceAnnotations'][0]['angerLikelihood'])
    print "Joy likelihood is:",
    print(response['responses'][0]['faceAnnotations'][0]['joyLikelihood'])
    print "Sorrow likelihood is:",
    print(response['responses'][0]['faceAnnotations'][0]['sorrowLikelihood'])
    print "Surprise likelihood is:",
    print(response['responses'][0]['faceAnnotations'][0]['surpriseLikelihood'])

Came out looking like:
Anger likelihood is: VERY_UNLIKELY
Joy likelihood is: VERY_LIKELY
Sorrow likelihood is: VERY_UNLIKELY
Surprise likelihood is: VERY_UNLIKELY


text:
Q: Only receiving HTTP requests in Google App Engine Flex with .NET. How to only allow HTTPS? I have a website written in C# using ASP.NET Core MVC5 that I'm deploying onto Google Cloud App Engine Flex. I want to completely disable HTTP and only allow HTTPS. I do not want a redirect from HTTP to HTTPS. How do I go about doing this?
I tried searching and could not find any way to specify it in the app.yaml for .NET and App Engine Flex. So I tried to do it within the webserver code itself. At first as a test, I tried to use the RequireHttps attribute and I also tried an implementation of RequireHttpsOrClose (https://www.recaffeinate.co/post/enforce-https-aspnetcore-api/), which is closer to what I actually want.
When I built the projects and deploy via IIS (i.e. NOT google app engine), everything works fine. However, when I deploy to Google App Engine, they don't work right. When I try to connect to them, it always seems to come in as HTTP, even if the URL I use to connect is set as HTTPS. When I used the RequireHttps attribute, I got a "too many redirects" error, which tells me that it was taking my HTTPS request (e.g. "https://www.test.com") but within the controller, it was seeing it as if I had sent a plain HTTP request (e.g. like it was seeing "http://www.test.com" instead). So it again saw this as a supposed plain HTTP request (though it really wasn't) and attempted to redirect -- once again -- to an HTTPS request, which was again processed as a plain HTTP request. And this seems to continue infinitely, causing a redirect loop.
To test this further, I checked the value of Request.IsHttps, I ALWAYS got false even though I was definitely connecting with HTTPS. So for some reason the site is only receiving HTTP requests even though I'm requesting with HTTPS.
Again, when I test outside of App Engine (by deploying as via IIS on our non-Google web server), everything works perfectly. It is only when I deploy on App Engine that I get this weird behavior.
I can reproduce this by setting up a barebones project with "ASP.NET Core on Google Cloud Platform" template. The only relevant code is my controller, which is barebones and simply returns the dummy values supplied by the template:
[RequireHttps]
[Route("/")]
public class ValuesController : Controller
{
    private readonly ILogger _logger;

    public ValuesController(ILogger<ValuesController> logger)
    {
        _logger = logger;
    }

    // GET api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        // When I remove the RequestHttps attribute in order to stop the redirect
        // loop, I always get values "not https" and "HTTP/1.1" even though
        // my browser is connecting to https://xxxxx.appspot.com

        if (Request.IsHttps) return new string[] { "https", Request.Protocol };
        return new string[] { "not https", Request.Protocol };
    }
}

I publish this with an app.yaml of:
service: testservice
runtime: aspnetcore
env: flex

The web.config is unmodified from the project template:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
  </system.webServer>
</configuration>

So my questions are:

*

*Why am I only receiving HTTP requests when I am definitely entering a HTTPS URL? Did I do something or set something in Google Cloud or in App Engine to cause this to happen?

*Otherwise, is there some other method of disabling HTTP and only allowing HTTPS using App Engine Flex with .NET? All examples I could find of disabling it are for Python using handler in the app.yaml, but that doesn't seem to apply to .NET.

A: In the flexible environment you cannot use the app.yaml configuration to require HTTPS-only access, that can only be done in the standard environment. See related Correctly assign HTTPS only custom domain to flex env
From Request limits:

*

*SSL connections are terminated at the load balancer. Traffic from the load balancer is sent to the instance over an encrypted channel,
  and then forwarded to the application server over HTTP. The
  X-Forwarded-Proto header lets you understand if the origin request was
  HTTP or HTTPs.

This explains why you cannot use Request.IsHttps to identify if the request was HTTPS.
But you can modify that piece of logic to check the X-Forwarded-Proto instead which should get you what you need. I think it could be something along these lines (not 100% certain, I'm not a .NET user):
    if (Request.Headers["X-Forwarded-Proto"] == "https") return new string[] { "https", Request.Protocol };
    return new string[] { "not https", Request.Protocol };


text:
Q: In JavaScript, how will you change the default output of JSON.stringify for any object How will you change the default output of JSON.stringify for any object.

A: You can provide a "replacer" function with special logic for your object type. Check out the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter
An example from their docs:
function replacer(key, value) {
  if (typeof value === "string") {
    return undefined;
  }
  return value;
}

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer);


text:
Q: Oracle SQL Script - Transpose data in pairs for subsequent records I need to transpose records by SQL Oracle Query:
Table1:

Col1
1
2
3
4
5

AS:
1 2
2 3
3 4
4 5

How is it possible ?

A: You can use lead():
select col1, col2
from (select col1, lead(col1) over (order by col1) as col2
      from t
     ) t
where col2 is not null;

If the values are really sequential numbers with no gaps, then you could use a join.


text:
Q: SyntaxError: invalid syntax for a beginner Hi I have been programming in java for a couple of months now and I have had some time off so I wanted to try out some python so I decided to try and write my java programs into python but I can't for the life of me figure out where I'm going wrong on this piece of code. I want to use a for loop and a while loop in this program just for practice but I keep getting an error
Here is my code:
breakLine = "\n-------------------------------------------------\n"

print breakLine

startReading = float(raw_input("Please enter the odometer start reading in Miles "))
endReading = float(raw_input("Now please enter the odometer end reading in Miles "))
totalMiles = endReading - startReading
totalGal = 0.0

gals = [];
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

for i in range (0, 5):
    gals.insert(i, float(raw_input("Enter gals for " + days[i] + " ")))
    totalGal += gals[i]
    i += 1

avgFuel = totalMiles / totalGal

print breakLine
print "Below is some information about your weeks travel"
print breakLine

print ("{0:20} \t {1:20}".format("DAY", "GALLONS USED"))
print breakLine

x = 0

while x < len(days):
    print ("{0:20} \t {1:20}".format(days[x], str(gals[x]))
    x += 1

print breakLine
print "You used a total of:", totalGal, "gallons this week"
print "You travelled a total of:", totalMiles, " Miles this week"
print "Your average fuel consumption for the week is:", avgFuel, "MPG"

and here is the error I get
  File "Week1-2.py", line 31
    x += 1
    ^
SyntaxError: invalid syntax

any help on this would be great

A: You missed parentheses enclose at the end of the print
x = 0
while x < len(days):
    print ("{0:20} \t {1:20}".format(days[x], str(gals[x])))
    x += 1

To aviod those type of problems i recommend to use an IDE like pycharm it will help you to find mistakes easy.


text:
Q: Question on data compression Suppose we have some text as a series of a number of characters and a dictionary consisting of some words that are sub-strings of the text, $D=\{w_1,w_2,\dots,w_n\}$. The dictionary is rich enough so we can write the text by joining words from it. How can we write the text using the minimum number of words from the dictionary (possibly more than once) ? (other than the obvious of finding all combinations of words and choosing the minimum which by the way I don't know how to do... I appreciate
WHAT I HAVE THOUGHT:
Suppose the text is
$$
T=\{c_1,c_2,\dots,c_m\},
$$
where the $c_i$ are the text characters. Determine the maximal $k$ so that the word $w=\{c_1,c_2,\dots,c_k\}$ is in the dictionary. If $k=m$ there is just one word which is the whole text, so just use that and we 're done. If not, mark down that this word has been used, remove $w$ from the beginning of the text and keep doing that until there are no more characters left. It seems that LOCALLY this is the optimal algorithm but there is no guarantee that it's also GLOBALLY optimal. What to do now?

A: Build a graph with nodes $n_0$ to $n_m$ and an edge connecting $n_i$ to $n_j$ if the word $(c_{i+1} c_{i+2} \ldots c_{j}) \in D$. Then you just need to find the shortest path from $n_0$ to $n_m$ using Dijkstra's algorithm or one of its modifications (e.g. A*).
As an implementation note, the graph building may benefit from converting the representation of $D$ into a trie.