text:
Q: Rabbit mq start up error - application_start_failure I am trying to set up a HA rabbit mq cluster and I am following the instruction in https://www.rabbitmq.com/clustering.html
The first rabbit mq server is fine, whereas in the second and third rabbitmq servers I am getting the below error,
Kernel pid terminated (application_controller) ({application_start_failure,kernel,{{shutdown,{failed_to_start_child,net_sup,{shutdown,{failed_to_start_child,auth,{"Cookie file /var/lib/rabbitmq/.erl

I have double check /var/lib/rabbitmq/.erlang.cookie on all three servers have the same value. Stuck with this error, any help on this is appreciated

A: Maybe it is too late but I run into this same issue. Here how I solved it:

*

*Run rabbitmqctl status (as root or use sudo). It gave me some error messages. One of them was:

{error_logger,{{2016,9,20},{12,4,22}},"Cookie file
  /var/lib/rabbitmq/.erlang.cookie must be accessible by owner only",[]}

*Then run  ls -l /var/lib/rabbitmq/.erlang.cookie. It returns to me this:

-rwxrwxrwx 1 rabbitmq rabbitmq 20 Set 25  2014 /var/lib/rabbitmq/.erlang.cookie

*Then change the permissions using chmod 600 /var/lib/rabbitmq/.erlang.cookie
I think other users may have to change the ownership too. It was not my case tough.


text:
Q: On Click Listener suddenly terminating the application I have a text box with OnClickListener(). Also whenever I type an alphabet in the text box, it reads it out aloud using some sound files.
The problem is that after reading out/typing say 5-6 alphabets, the application unexpectedly terminates. I am not able to figure out the reason. Why is it so?
The code is here:
package com.example.newaa;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

import android.os.Bundle;

public class Recipient extends Activity{
     public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.recipient);
            EditText a;
            a=(EditText)findViewById(R.id.editText3);
            a.addTextChangedListener(new TextWatcher(){
                @Override
                public void afterTextChanged(Editable s) {
                       //GET TEXT HERE AFTER TYPING DONE BY PERSON

                    }
                @Override
                public void beforeTextChanged(CharSequence s,int start,int count,int after){
                      //GET TEXT HERE BEFORE TYPING START BY PERSON

                    }
                @SuppressLint("ParserError")
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                   //GET TYPED CHAR HERE

                    char ch=s.charAt(s.length()-1);
                    if(ch=='a')
                    {

                        MediaPlayer mPlayer1 = MediaPlayer.create(Recipient.this, R.raw.a);
                        mPlayer1.start();
                    }
                    if(ch=='b')
                    {
                        MediaPlayer mPlayer2 = MediaPlayer.create(Recipient.this, R.raw.b);
                        mPlayer2.start();
                    }
                    if(ch=='c')
                    {
                        MediaPlayer mPlayer3 = MediaPlayer.create(Recipient.this, R.raw.c);
                        mPlayer3.start();
                    }
                    if(ch=='d')
                    {
                        MediaPlayer mPlayer4 = MediaPlayer.create(Recipient.this, R.raw.d);
                        mPlayer4.start();
                    }
                    if(ch=='e')
                    {
                        MediaPlayer mPlayer5 = MediaPlayer.create(Recipient.this, R.raw.e);
                        mPlayer5.start();
                    }
                    if(ch=='f')
                    {
                        MediaPlayer mPlayer6 = MediaPlayer.create(Recipient.this, R.raw.f);
                        mPlayer6.start();
                    }
                    if(ch=='g')
                    {
                        MediaPlayer mPlayer7 = MediaPlayer.create(Recipient.this, R.raw.g);
                        mPlayer7.start();
                    }
                    if(ch=='h')
                    {
                        MediaPlayer mPlayer8 = MediaPlayer.create(Recipient.this, R.raw.h);
                        mPlayer8.start();
                    }
                    if(ch=='i')
                    {
                        MediaPlayer mPlayer9 = MediaPlayer.create(Recipient.this, R.raw.i);
                        mPlayer9.start();
                    }
                    if(ch=='j')
                    {
                        MediaPlayer mPlayer10 = MediaPlayer.create(Recipient.this, R.raw.j);
                        mPlayer10.start();
                    }
                    if(ch=='k')
                    {
                        MediaPlayer mPlayer11 = MediaPlayer.create(Recipient.this, R.raw.k);
                        mPlayer11.start();
                    }
                    if(ch=='l')
                    {
                        MediaPlayer mPlayer12 = MediaPlayer.create(Recipient.this, R.raw.l);
                        mPlayer12.start();
                    }
                    if(ch=='m')
                    {
                        MediaPlayer mPlayer13 = MediaPlayer.create(Recipient.this, R.raw.m);
                        mPlayer13.start();
                    }
                    if(ch=='n')
                    {
                        MediaPlayer mPlayer14 = MediaPlayer.create(Recipient.this, R.raw.n);
                        mPlayer14.start();
                    }
                    if(ch=='o')
                    {
                        MediaPlayer mPlayer15 = MediaPlayer.create(Recipient.this, R.raw.o);
                        mPlayer15.start();
                    }
                    if(ch=='p')
                    {
                        MediaPlayer mPlayer16 = MediaPlayer.create(Recipient.this, R.raw.p);
                        mPlayer16.start();
                    }
                    if(ch=='q')
                    {
                        MediaPlayer mPlayer17 = MediaPlayer.create(Recipient.this, R.raw.q);
                        mPlayer17.start();
                    }
                    if(ch=='r')
                    {
                        MediaPlayer mPlayer18 = MediaPlayer.create(Recipient.this, R.raw.r);
                        mPlayer18.start();
                    }
                    if(ch=='s')
                    {
                        MediaPlayer mPlayer19 = MediaPlayer.create(Recipient.this, R.raw.s);
                        mPlayer19.start();
                    }
                    if(ch=='t')
                    {
                        MediaPlayer mPlayer20 = MediaPlayer.create(Recipient.this, R.raw.t);
                        mPlayer20.start();
                    }
                    if(ch=='u')
                    {
                        MediaPlayer mPlayer21 = MediaPlayer.create(Recipient.this, R.raw.u);
                        mPlayer21.start();
                    }
                    if(ch=='v')
                    {
                        MediaPlayer mPlayer22 = MediaPlayer.create(Recipient.this, R.raw.v);
                        mPlayer22.start();
                    }
                    if(ch=='w')
                    {
                        MediaPlayer mPlayer23 = MediaPlayer.create(Recipient.this, R.raw.w);
                        mPlayer23.start();
                    }
                    if(ch=='x')
                    {
                        MediaPlayer mPlayer24 = MediaPlayer.create(Recipient.this, R.raw.x);
                        mPlayer24.start();
                    }
                    if(ch=='y')
                    {
                        MediaPlayer mPlayer25 = MediaPlayer.create(Recipient.this, R.raw.y);
                        mPlayer25.start();
                    }
                    if(ch=='z')
                    {
                        MediaPlayer mPlayer26 = MediaPlayer.create(Recipient.this, R.raw.z);
                        mPlayer26.start();
                    }
                  }
                });
     }

}

The logcat is here:
07-05 08:08:42.153: E/AndroidRuntime(321): Uncaught handler: thread main exiting due to uncaught exception
07-05 08:08:42.183: E/AndroidRuntime(321): java.lang.NullPointerException
07-05 08:08:42.183: E/AndroidRuntime(321):  at com.example.newaa.Recipient$1.onTextChanged(Recipient.java:79)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.widget.TextView.sendOnTextChanged(TextView.java:6131)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.widget.TextView.handleTextChanged(TextView.java:6172)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:6316)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.text.SpannableStringBuilder.sendTextChange(SpannableStringBuilder.java:889)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:352)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.text.SpannableStringBuilder.change(SpannableStringBuilder.java:269)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:432)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:409)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:28)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:578)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.view.inputmethod.BaseInputConnection.commitText(BaseInputConnection.java:174)
07-05 08:08:42.183: E/AndroidRuntime(321):  at com.android.internal.widget.EditableInputConnection.commitText(EditableInputConnection.java:120)
07-05 08:08:42.183: E/AndroidRuntime(321):  at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:231)
07-05 08:08:42.183: E/AndroidRuntime(321):  at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:57)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.os.Looper.loop(Looper.java:123)
07-05 08:08:42.183: E/AndroidRuntime(321):  at android.app.ActivityThread.main(ActivityThread.java:4363)
07-05 08:08:42.183: E/AndroidRuntime(321):  at java.lang.reflect.Method.invokeNative(Native Method)
07-05 08:08:42.183: E/AndroidRuntime(321):  at java.lang.reflect.Method.invoke(Method.java:521)
07-05 08:08:42.183: E/AndroidRuntime(321):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
07-05 08:08:42.183: E/AndroidRuntime(321):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
07-05 08:08:42.183: E/AndroidRuntime(321):  at dalvik.system.NativeStart.main(Native Method)

A: EDITED PART.....
Try to release the mediaplayer once the sound is player... And no need to create multiple instances of the mediaplayer... Reinitialize the same one at the starting..

A: You got error due to passing Illegal Activity Context (NULL Context) to any method or other activity.
Refer Uncaught handler: thread main exiting due to uncaught exception , that have the similar problem. You may figure out the problem area.

redpajama_set_name: RedPajamaStackExchange


text:
Q: To shuffle an array a of n elements C++ I have problem with shuffle array
The problem is that according to the seed for the random is again the same Result and not 2-exchange and two array is same!
i want 2 result array exchange random
The code is for 2-exchange
#include <stdio.h>
#include <cstdlib>
#include <ctime>

void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

void printArray(int arr[], int n)
{
    for(int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

// A function to generate a random exchange
int* randomized(int arr[], int n)
{
    // Use a different seed value so that we don't get same
    // result each time we run this program

    srand(time(NULL));
    // Start from the last element and swap one by one. We don't
    // need to run for the first element that's why i > 0
    for(int i = n - 1; i > 0; i--)
    {
        // Pick a random index from 1 to i-1
        int j = rand() % (i - 1 + 1) + 1;
        //int j = rand() % (i+1);

        // Swap arr[i] with the element at random index
        swap(&arr[i], &arr[j]);
    }

    return arr;
}

// Driver program to test above function.
int main()
{
    int *x1, *x2;
    int arr[] = {6, 1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);
    x1 = randomized(arr, n);
    x2 = randomized(x1, n);
    printArray(x1, n);
    printArray(x2, n);
    getchar();
}

A: Obviously, randomized is in both cases returning the pointer to the same array that's being passed in (x1 = x2). "randomized" sounds like a name for a function that should return a randomized copy of the data, not modify the original data.
Decide which version you want and based on that, fix either the function or the test program.


text:
Q: Variables in SQL queries with PyQGIS I want to create spatial indexes in all the tables that are included in a schema in PostGIS.
The layers remain the same but the schema is everytime different.
So I wanted to pass a variable var = schemaname + "l_abluft(geom)" to the SQL query (CREATE INDEX ON test.l_abluft(geom);)
#--Create a Connection to PostGIS
#---------------------------------------------------------------------------
connection = psycopg2.connect (dbname = "xxxxx",
                           user = "xxxxxx",
                           password = "xxxxx",
                           host = "xxxxxx",
                           )
cursor = connection.cursor()

#--Create spatial Indexes
#---------------------------------------------------------------------------
cursor.execute("CREATE INDEX ON test.l_abluft(geom);")
cursor.execute("CREATE INDEX ON test.l_zuluft(geom);")
cursor.execute("CREATE INDEX ON test.rl_isolierung(geom);")
cursor.execute("CREATE INDEX ON test.treppenhaus(geom);")
cursor.execute("CREATE INDEX ON test.waende_saeule_usw(geom);")
connection.commit()
print("Query successful")

I tried the following but I got the error:
psycopg2.errors.SyntaxError: syntax error at end of input
LINE 1: CREATE INDEX ON "test.l_abluft(geom)"
schemaname = "test"
var = schemaname + ".l_abluft(geom)"

#--Create spatial Indexes
#---------------------------------------------------------------------------
cursor.execute(
    sql.SQL("CREATE INDEX ON {}").format(sql.Identifier(var)))
connection.commit()
print("Query successful")

A: You can use f-strings (requires Python version >= 3.6) :
#--Create a Connection to PostGIS
#---------------------------------------------------------------------------
connection = psycopg2.connect(dbname = "xxxxx",
                              user = "xxxxxx",
                              password = "xxxxx",
                              host = "xxxxxx",
                             )
cursor = connection.cursor()

#--Create spatial Indexes
#---------------------------------------------------------------------------
my_schema = "test"
cursor.execute(f"CREATE INDEX ON {my_schema}.l_abluft(geom);")
cursor.execute(f"CREATE INDEX ON {my_schema}.l_zuluft(geom);")
cursor.execute(f"CREATE INDEX ON {my_schema}.rl_isolierung(geom);")
cursor.execute(f"CREATE INDEX ON {my_schema}.treppenhaus(geom);")
cursor.execute(f"CREATE INDEX ON {my_schema}.waende_saeule_usw(geom);")
connection.commit()
print("Query successful")

For Python versions < 3.6 use :
settings = {"my_schema": "test"}
cursor.execute("CREATE INDEX ON {my_schema}.l_abluft(geom);".format(**settings)

With Python 3.6, it will be cleaner (IMHO) to write code like this :
#--Create a Connection to PostGIS
#---------------------------------------------------------------------------
db_params = {
    "dbname": "xxxxx",
    "user" = "xxxxxx",
    "password" = "xxxxx",
    "host" = "xxxxxx",
}

my_schema = "test"
fields = [
    "l_abluft(geom)",
    "l_zuluft(geom)",
    "rl_isolierung(geom)",
    "treppenhaus(geom)",
]

with psycopg2.connect(**db_params) as conn:
    with conn.cursor() as curs:
        list(map(
            curs.execute,
            [f"CREATE INDEX ON {my_schema}.{fld};" for fld in fields]
        ))

print("Query successful")


text:
Q: How to take control to next cell in the same row in a GRID in C#.net I have one datagrid in c#.net windows application , I want to type numbers into the cell and want to shift to next cell in the same row after pressing enter , moreover if the cell is last in the row , the control should go to the next row , first column

A: i use this (use for DG form class):
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
    if (keyData == Keys.Enter && this.dataGridView1.IsCurrentCellInEditMode && this.dataGridView1.CurrentCell.ColumnIndex==this.dataGridView1.Columns.Count-1)
    {
        SendKeys.Send("{DOWN}");
        return true;
    }
    else
        return base.ProcessCmdKey(ref msg, keyData);

}


text:
Q: Sylow $p$-groups in $GL_3(\Bbb F_p)$ Fix a prime $p$.

How many Sylow $p$-groups are there in $GL_3(\Bbb F_p)$?

Let $s_p$ be the number of Sylow $p$-groups in $GL_3(\Bbb F_p)$. By the Sylow theorems, $s_p\equiv 1\mod p$ and if $p^e$ is the maximal prime power of the order of $GL_3(\Bbb F_p)$, then $s_p$ divides $\frac{\left|GL_3(\Bbb F_p) \right|}{p^e}$.
Unfortunately I don't even really know how to figure out the cardinality of that group.

A: I assume you use column vectors.
One particular Sylow $p$-subgroup is
$$
L
=
\left\{
\begin{bmatrix}
1 & 0 & 0\\
a & 1 & 0\\
c & b & 1\\
\end{bmatrix}
:
a, b, c \in \Bbb F_p
\right\}.
$$
You may try and compute its normalizer. The index will give you the number of Sylow $p$-subgroups.
Alternatively, you may note that $x \in L$ iff $x - 1$ maps the underlying vector space to $\langle e_{2}, e_{3} \rangle$, $\langle e_{2}, e_{3} \rangle$ to $\langle e_{3} \rangle$ and $\langle e_{3} \rangle$ to $\{  0 \}$, where $e_{1}, e_{2}, e_{3}$ is the standard basis. So there are as many Sylow $p$-subgroups as the number of pairs $U_{2} \supseteq U_{1}$ of subspaces, with $\dim(U_{i}) = i$. You will obtain the same number as with the previous method.


text:
Q: Add a header to a viewport component I have created a viewport in ExtJS 6.2.0 like so :
    Ext.define('Mine.view.Main', {
        extend: 'Ext.container.Viewport',
        alias: 'widget.main',
        id: 'mainView',
        xtype : 'mainV', ...

With a region south collapsible panel.
I want to add a fixed Header at the top so I added as an item of the viewport this :

   {
        region: 'north',
        //collapsed: true,
        xtype: 'panel',
        height: 30,
        collapsible:false,
        layout: 'border',
        collapsed: false
        // titleCollapse: true
    },

But I am not getting a fixed header, instead I am getting a collapsible north window.
How to achieve this?
Thanks!

A: My bad i was defaulting my viewport to have item panels collapsible. So i got what i wanted by removing the collapsible true from defaults config in my viewport and setting items with property collapsible in a customized way (true or false each depending on the case)


text:
Q: How to document individual actions of a ViewSet using `drf-spectacular`? Using DRF's built-in way of documenting the API, I was able to write a docstring like the following and each action was documented by its corresponding line:
"""
list:    The list action returns all available objects.
retrieve:The retrieve action returns a single object selected by `id`.
create:  The create action expects the fields `name`, creates a new object and returns it.
"""

I am in the middle of switching to the library drf-spectacular, which allows for an easy generation of OpenAPI conforming schemes. However, the same docstring is now rendered for every action, which makes my documentation really long and redundant.
Is there a way that only the relevant part of the docstring is rendered for each action?

A: I have just found out that the library provides very in-depth documentation functionality via their decorators. Without overriding any of the ViewSet methods, the above docstring could be written as:
@extend_schema_view(
    list=extend_schema(
        description="The list action returns all available actions."
    ),
    create=extend_schema(
        description="The create action expects the fields `name`, creates a new object and returns it."
    ),
    retrieve=extend_schema(
        description="The retrieve action returns a single object selected by `id`."
    )
)
class MyViewSet(viewsets.ViewSet):
    pass


text:
Q: How to exclude multiple users from find command result in tcsh? I want to exclude a group of users from find results, they don't belong to the same unix group, this is not the best way, right ?
find . -maxdepth 1 -type d -name '*_pattern_*' ! -user user1 ! -user user2 ...

Can I pass in the users as a string or an array? maybe with awk ?

A: On a cshell you can cobble up the find command to perform the job as follows:
 #!/bin/tcsh -f

 # persona non grata
 set png = ( \
    user1 \
    user2 \
    user3 \
    user4 \
 )

 # build dynamically a portion of the `find` command
 set cmd = ( `printf '! -user %s\n' $png:q` )

 # now fire the generated find command
 find . -maxdepth 1 -type d -name '*_pattern_*'  $cmd:q

A: Except for the fact that csh does not like an unescaped exclamation mark, in the command line, your command looks OK and cannot be made better

A: If you're happy to run it from a /bin/sh script:
#!/bin/sh

# the users to avoid
set -- user1 user2 user3 user4

# create a list of
# -o -user "username" -o -user "username" etc.
for user do
    set -- "$@" -o -user "$user"
    shift
done
shift # remove that first "-o"

# use the created array in the call to find
find . -maxdepth 1 -type d -name '*_pattern_*' ! '(' "$@" ')'

Alternatively, to build the same sort of ! -user "username" list that you use:
#!/bin/sh

# the users to avoid
set -- user1 user2 user3 user4

# create a list of
# ! -user "username" ! -user "username" etc.
for user do
    set -- "$@" ! -user "$user"
    shift
done

# use the created array in the call to find
find . -maxdepth 1 -type d -name '*_pattern_*' "$@"


text:
Q: d3 adding new key value to existing json data I have a question that would like to seek your expertise on.
This is my JSON array that I have in:
[{
    key : "Group 0",
    values : [{
        x : 0.12817352913159197,
        y : 4.360475517778741,
        size : 0.8945912778023366
    }, {
        x : -1.8709283296311146,
        y : 1.4047025584603734,
        size : 0.3621509721039796
    }]
}, {
    key : "Group 1",
    values : [{
        x : 0.6574795166435595,
        y : -0.6037258352005531,
        size : 0.0942101986534386
    }, {
        x : -0.4951370796031603,
        y : -0.18739226817326712,
        size : 0.8843348380774309
    }]
}]

i am passing this to scatterChart so the data inside contain this, now i want to add shape to each values, finaly i want it like this to be in chart data:
[{
    key : "Group 0",
    values : [{
        x : 0.12817352913159197,
        y : 4.360475517778741,
        size : 0.8945912778023366,
        shape : "circle"
    }, {
        x : -1.8709283296311146,
        y : 1.4047025584603734,
        size : 0.3621509721039796,
        shape : "diamond"
    }]
}, {
    key : "Group 1",
    values : [{
        x : 0.6574795166435595,
        y : -0.6037258352005531,
        size : 0.0942101986534386,
        shape : "circle"
    }, {
        x : -0.4951370796031603,
        y : -0.18739226817326712,
        size : 0.8843348380774309,
        shape : "diamond"
    }]
}]

how to acheive this using d3 or nvd3?

A: If I understood your question correctly
var demo = [{
    key: "Group 0",
    values: [{
        x: 0.12817352913159197,
        y: 4.360475517778741,
        size: 0.8945912778023366,
    }, {
        x: -1.8709283296311146,
        y: 1.4047025584603734,
        size: 0.3621509721039796,
    }]
}, {
    key: "Group 1",
    values: [{
        x: 0.6574795166435595,
        y: -0.6037258352005531,
        size: 0.0942101986534386,
    }, {
        x: -0.4951370796031603,
        y: -0.18739226817326712,
        size: 0.8843348380774309,
    }]
}];

for (var i = 0, j = demo.length; i < j; i++) {
    group = demo[i]['values'];
    for (var x = 0, y = group.length; x < y; x++) {
        if (x == 0) {
            // Assuming the first is always circle
            group[x]['shape'] = "circle";
        } else {
            // Assuming the second is always diamond
            group[x]['shape'] = "diamond";
        }
    };
};

console.log(demo);

There is a working version here.
Hope it helps


text:
Q: JSON Object passed to External JavaScript I was looking at FireBug Lite and saw that they use a pretty cool technique to pass options into an external script file:
<script type="text/javascript" src="https://getfirebug.com/firebug-lite.js">
{
    overrideConsole: false,
    startInNewWindow: true,
    startOpened: true,
    enableTrace: true
}
</script>

What is the name of this technique and how does it work?

A: It's not an automatic variable-passing-technique as you may think.
All their code does is loop through all the script tags until they find the one which loaded their code (by comparing the src attribute to a regular expression (/(firebug-lite(?:-\w+)?(?:\.js|\.jgz))(?:#(.+))?$/;).
If it finds the tag, it simply gets the .innerHTML of the script tag, and evaluates it.
I guess this (unnamed) techique isn't relevant in the real-world, as we don't have a guaranteed method of finding which script tag refers to our library (especially as it is common for all script's to be combined into one script file on live servers).
Furthermore, I have my doubts over how cross-browser this is; as it certainly doesn't go by the spec, which states:
Having said that (and thought about it): the spec states that the browser shouldn't interpret both. However this isn't relevant with this technique. The browser doesn't have to interpet both, as the content of the script is read in through innerHTML (and even if it did read in the content, it doesn't do any harm anyway). Aslong as the browser conforms to the spec, and loads the URI (which all browsers do), there's no problem! (apart from not knowing/ guaranteeing which script tag your library belongs to).

The script may be defined within the
  contents of the SCRIPT element or in
  an external file. If the src attribute
  is not set, user agents must interpret
  the contents of the element as the
  script. If the src has a URI value,
  user agents must ignore the element's
  contents and retrieve the script via
  the URI.

(i.e., don't interpret both).

A: Further to @Matt's answer, and to clarify my comment:
var doc = Firebug.browser.document;
var script = doc.getElementsByTagName("script")[index];
var url = getScriptURL(script);
var isExternal = url && url != doc.location.href;

try
{
  if(isExternal)
  {
    Ajax.request({url:url, onSuccess:renderProcess, onFailure:onFailure})
  }
  else
  {
    var src = script.innerHTML;
    renderProcess(src)
  }
}
catch(e)
{
  onFailure()
}


text:
Q: UIApplication beginBackgroundTaskWithExpirationHandler question guys :)
I have an iOS alarm app, which uses UILocalNotification-s to schedule the user defined alarms if the app enters background. Since this (in my implementation) can be a relatively long process, I need to make sure that the registering of the notifications is completed before the app goes inactive. I read that there is a method in UIApplication: beginBackgroundTaskWithExpirationHandler, which asks iOS for more time, so that it can complete its tasks, but I have no idea how to use it. These (void(^)(void)) parameters scare me :). I know it's too much to ask, but... if I have a method [self registerLocalNotifications], which registeres all local notifications, can you please point me how to make sure the method finishes before the app goes to background. Huge thanks!

A: This looks like good sample code where you can see the usage of blocks ^{} together with applicationDidEnterBackground: http://iphonesdkdev.blogspot.com/2010/04/local-push-notification-sample-code-os.html


text:
Q: Dropdown Toggle working only for alternative buttons and not all buttons I have multiple dropdown buttons with the same class as they were dynamically added to the page. I want to toggle the dropdown on the clicked button and not all.
I am using closest() and find() to do that, but this works only alternatively and not for every button.
For example if I click button 1 it works and not for button 2 and it again works for button 3 and not button 4 and it goes on with dynamic buttons.

$('.btn').click(function() {
  $(this).closest('div').find('.dropdown-content').toggleClass('show');
});
.dropdown-content { display: none; }
.dropdown-content.show { display: block; }

  <button class="btn" type="button" data-toggle="dropdown">  </button>

    // content

  <button class="btn" type="button" data-toggle="dropdown">  </button>

    // content

  <button class="btn" type="button" data-toggle="dropdown">  </button>

    // content

  <button class="btn" type="button" data-toggle="dropdown">  </button>

    // content


text:
Q: OpenGL VBO - Array Stride wrong? Now I hope you can help me with that problem, I have had for several days, without finding any solution. I feel, I've tried everything out to fix that problem, but none of them worked.
First of all:
I have some Objects in my scene, that use VBOs for rendering. Nothing else, no other quads, polys, etc. only the ones in the screenshots, that will follow.
My generation-Code of the VBOs is very simple and hopefully clear and comprehensable:
Generating VBO
public boolean buffer() {
    FloatBuffer[] vertexBuffer = new FloatBuffer[1];
    vertexBuffer[0] = FloatBufferFactory.create(this.triangles.size() * 3 * 11);

    for (Triangle triangle : this.triangles) {
        for (int i = 0; i < 3; i++) {
            vertexBuffer[0].put(triangle.vertex[i].position.x);
            vertexBuffer[0].put(triangle.vertex[i].position.y);
            vertexBuffer[0].put(triangle.vertex[i].position.z);

            vertexBuffer[0].put(triangle.vertex[i].normal.x);
            vertexBuffer[0].put(triangle.vertex[i].normal.y);
            vertexBuffer[0].put(triangle.vertex[i].normal.z);

            vertexBuffer[0].put(triangle.vertex[i].color.r);
            vertexBuffer[0].put(triangle.vertex[i].color.g);
            vertexBuffer[0].put(triangle.vertex[i].color.b);

            vertexBuffer[0].put(triangle.vertex[i].uvset.x);
            vertexBuffer[0].put(triangle.vertex[i].uvset.y);
        }
    }

    vertexBuffer[0].position(0);

    GLES20.glGenBuffers(1, this.buffer, 0);
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.buffer[0]);
    GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, vertexBuffer[0].capacity() * 4, vertexBuffer[0], GLES20.GL_STATIC_DRAW);

    return true;
}

It's very simple: My own function in FloatBufferFactory creates a Floatbuffer with count-of-triangles * 3 * 11 * 4 Bytes.
Then I put the data in it, for each Vertex of the triangles.
My logic: 12 Bytes (3 * 4 Bytes) for one vertexposition, 12 Bytes for one normalposition, 12 Bytes for Vertexcolordata and 8 Bytes for UV-coordinates.
Rendering
When I render the mesh, I use following function as simple as the other one:
public void render() {
    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.buffer[0]);

    GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeVertex, 3, GLES20.GL_FLOAT, false, 44, this.buffer[0]);
    GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeNormal, 3, GLES20.GL_FLOAT, false, 44, this.buffer[0] + 12);
    GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeColor, 3, GLES20.GL_FLOAT, false, 44, this.buffer[0] + 24);
    GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeUV, 2, GLES20.GL_FLOAT, false, 44, this.buffer[0] + 36);

    this.passMaterialUniforms();
    GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, this.triangles.size() * 3);
}

Now, my logic, as I understood it:
All data in Bytes for one Vertex is: 12Bytes (position) + 12Bytes (normal) + 12Bytes (color) + 8Bytes (uv) -> makes in conclusion: 44 Bytes for each Vertex, so the next Vertex should be after 44 Bytes. -> Stride: 44 Bytes for each data.
The next idea was to set the start offset: 0Bytes for position, 12Bytes for normal, 24Bytes for color and 36Bytes for uv.
So far so good.
The main problem
Now there seems to happen something very, very weird in the programm. After creating more than 3 Objects or so, the objects that were generated after the first three, are displayed wrong.
Here the screenshots:
First example and try ( Generated: 5 Torus in a row):

Second try ( Generated 2 Spheres, 1 Torus, another Sphere, another Torus):

As you can see, in the first picture the 4. and 5. Torus ( Tori?!) are distorted and look like beans or lenses, or something like that.
In the second picture, the 3. Sphere ( 4. generated object) looks quite normal, when you just look at the positions, but the texture-coordinates are very strange.
So why is that? How can I fix that problem?
Thanks! :)

A: I think it is due to the way you enabled the attrib pointer.
You wrote this:
GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeVertex, 3, GLES20.GL_FLOAT, false, 44, this.buffer[0]);
GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeNormal, 3, GLES20.GL_FLOAT, false, 44, this.buffer[0] + 12);
GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeColor, 3, GLES20.GL_FLOAT, false, 44, this.buffer[0] + 24);
GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeUV, 2, GLES20.GL_FLOAT, false, 44, this.buffer[0] + 36);

It should be like this:
GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeVertex, 3, GLES20.GL_FLOAT, false, 44, 0);
GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeNormal, 3, GLES20.GL_FLOAT, false, 44, 12);
GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeColor, 3, GLES20.GL_FLOAT, false, 44, 24);
GLES20.glVertexAttribPointer(BaseActivity.activeShader.attributeUV, 2, GLES20.GL_FLOAT, false, 44, 36);

I suggest anyway to define some constants for the offset calculations.
In my C engine I based everything with the sizeof function


text:
Q: scipy.sparse.linalg: factorized() vs SuperLU В чем разница между
 scipy.sparse.linalg.factorized(A)

и
 scipy.sparse.linalg.splu(A)

Обе функции возвращают объект с методом .solve(rhs) и для обоих в документации сказано, что используется LU-разложение матрицы. Хотел бы узнать, чем они отличаются, как в плане алгоритма, так и в  плане производительности.
Если подробнее, то я пишу МКЭ модель с использованием python/numpy/scipy. Мне нужно решать уравнение Au = f на каждом шаге по времени. A матрица большой размерности, но разреженная и не зависит от времени, так что я хотел бы делать какие-то предварительные действия с А, чтобы ускорить итерации (их может быть несколько тысяч, если расчет долгий). Я пробовал использовать scipy.sparse.linalg.inv(A), но получал memory exceptions при большом числе узлов сетки. До недавнего момента использовал scipy.linalg.spsolve на каждом шаге, сейчас думаю применить какое-нибудь разложение, чтобы ускорить итерации. Если у вас есть какие-то предложения помимо LU-разложения, буду рад услышать.

A: scipy.sparse.linalg.splu() - вычисляет LU-разложение разреженной матрицы с помощью библиотеки SuperLU. Это эффективный и достаточно гибкий способ решить разреженную систему линейных уравнений прямым (неитеративным) способом.
scipy.sparse.linalg.factorized() - тоже вычисляет LU-разложение разреженной матрицы, однако конкретный метод для вычисление не определен. В частности, если установить с помощью scipy.sparse.linalg.use_solver параметр useUmfpack, то для разложения будет использоваться UMFPACK. По состоянию на данный момент, useUmfpack==True по умолчанию, если UMFPACK подключен к SciPy. В будущем, вполне могут появиться дополнительные опции.
Исходя из этого, если на вашей системе установлен UMFPACK в SciPy, то scipy.sparse.linalg.splu() и scipy.sparse.linalg.factorized() будут использовать разные библиотеки для разложение разреженной матрицы A.
Исходя из моего опыта, UMFPACK показывает лучшую производительность чем SuperLU при полных разложениях разреженных матриц (ваш случай). Однако, при использовании неполных разложений (для предобуславливателей-preconditioners) - ILU (incomplete LU) - SuperLU был предпочтительней (см, scipy.sparse.linalg.spilu). Моя область применения была заточена под матрицы происходящие из различных задач вычислительного электромагнетизма: дифференциальных и интегральных формулировок.
В вашем случае, я бы попробовал оба варианта, но все же склонился к тому, чтобы заморочиться с UMFPACK. Многое зависит от настроек и конкретных свойств системы, которую вы пытаетесь решить.


text:
Q: how to export a mysql data table search query into csv using php? how to export a mysql data table search query into csv using php?
hear is query
if ($_REQUEST["startfrom"]<>'' and $_REQUEST["end"]<>'') {
    $sql = "SELECT ECRNo,SalesDate,TimeSold,AmountDue,OutletName,ProductCode,Category,MealType,SUM(Quantity) AS Quantity1,SUM(NetPrice) AS NetPrice1 FROM ".$SETTINGS["data_table"]." WHERE SalesDate BETWEEN '".mysql_real_escape_string($_REQUEST["startfrom"])."'And'".mysql_real_escape_string($_REQUEST["end"])."'".$search_OutletName.$search_Category.$search_ProductCode.$search_groupby;
} else if ($_REQUEST["startfrom"]<>'') {
    $sql = "SELECT ECRNo,SalesDate,TimeSold,AmountDue,SalesDate,OutletName,ProductCode,Category,MealType,SUM(Quantity) AS Quantity1,SUM(NetPrice) AS NetPrice1 FROM ".$SETTINGS["data_table"]." WHERE SalesDate >= '".mysql_real_escape_string($_REQUEST["startfrom"])."'".$search_OutletName.$search_Category.$search_ProductCode.$search_groupby;
} else if ($_REQUEST["end"]<>'') {
    $sql = "SELECT ECRNo,SalesDate,TimeSold,SalesDate,AmountDue,OutletName,ProductCode,Category,MealType,SUM(Quantity) AS Quantity1,SUM(NetPrice) AS NetPrice1 FROM ".$SETTINGS["data_table"]." WHERE SalesDate <= '".mysql_real_escape_string($_REQUEST["end"])."'".$search_OutletName.$search_Category.$search_ProductCode.$search_groupby;
}else {
    $sql = "SELECT ECRNo,SalesDate,TimeSold,SalesDate,AmountDue,OutletName,ProductCode,Category,MealType,SUM(Quantity) AS Quantity1,SUM(NetPrice) AS NetPrice1 FROM ".$SETTINGS["data_table"]." WHERE ECRNo>0 ".$search_OutletName.$search_Category.$search_ProductCode.$search_groupby;
}

how do i export its query result?

A: All good answers here but if you want to do it using PHP, here is another option:
<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

The $list array would be your results from the DB.
Taken from here

A:
From
  http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/

SELECT *
FROM tableName
INTO OUTFILE '/tmp/fileName.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

A: This is work perfectly, Please try this...
SELECT * INTO OUTFILE "Database/business.sql"
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n'
FROM `business`

Thank You.

A: you can use mysql feature:
SELECT * FROM tableName INTO OUTFILE 'filename.csv'

. I think it should work


text:
Q: Procedures not working in pgAdmin
Possible Duplicate:
SQL Procedure error

Hello, i cant get my procedures working in pgAdmin, not even a simple one like this
CREATE PROCEDURE test_Proc
AS
    SELECT * FROM Category;
ERROR:  syntax error at or near "PROCEDURE"
LINE 1: CREATE PROCEDURE test_Proc

Any ideas why this is happening?


text:
Q: AJAX displays undefined I have a html page that have these codes, what this does is it displays the list of employees residing in the database
<!DOCTYPE html>

<title></title>
<meta charset="utf-8" />

    <input id="DisplayEmp" type="button" value="Display Employees" />
    <input id="ClearEmp" type="button" value="Clear Employees" />

I am new to jquery so I am not really familiar with the codes. But when I ran the program it displays undefined which is I dont have any Idea in its confusing. I checked my codes one by one but still failed to find the problem.
this is my model class
 public partial class tblEmployee
{
    public int Employee_ID { get; set; }
    public string Employee_Name { get; set; }
    public string Gender { get; set; }
    public Nullable<int> Age { get; set; }
    public Nullable<int> Department_ID { get; set; }
    public Nullable<int> Salary { get; set; }
}

and I have a controller named Employees when I run the API through URI it displays the list of employees properly.
EDIT 1
Here is the response of the server

EDIT 2
Here is my controller
[HttpGet]
    public HttpResponseMessage GetEmployees(string gender = "All")
    {
        using (EmployeeDBEntities employeeEntity = new EmployeeDBEntities())
        {
            switch (gender.ToLower())
            {
                case "all":
                    return Request.CreateResponse(HttpStatusCode.OK, employeeEntity.tblEmployees.ToList());
                case "male":
                    return Request.CreateResponse(HttpStatusCode.OK, employeeEntity.tblEmployees.Where(e => e.Gender.ToLower() == gender).ToList());
                case "female":
                    return Request.CreateResponse(HttpStatusCode.OK, employeeEntity.tblEmployees.Where(e => e.Gender.ToLower() == gender).ToList());
                default:
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Value for gender must be All,Male or Female" + gender + "is invalid.");
            }
        }
    }

EDIT 3:
 Find it weird, as you can see my model class have a property Age so I tried using that property val.Age and it still displays undefined however if I replaced it with val.age notice the lowercase it displays the correct data. But when I tried it with val.Employee_Name to val.employee_name it still displays undefined.

A: Change it this way to see the errors from your server:
$.ajax({
  type: 'GET',
  url: 'api/employees',
  dataType: 'xml',
  success: function (data) {
    employeeList.empty();
    var x = $(data).find('ArrayOftblEmployee');
    $.each(x, function (index, val){
      var fullName = val.find('tblEmployee').find('Employee_Name');
      employeeList.append('
' + fullName + '
')
    });
  }
});

Your jquery code seems ok. My suggestion is that you work with your "model class" in your server.

A: You have xml response, so you can use following code:
<!DOCTYPE html>

<title></title>
<meta charset="utf-8" />

    <input id="DisplayEmp" type="button" value="Display Employees" />
    <input id="ClearEmp" type="button" value="Clear Employees" />

A: Finally found out how to display the right value I used val.employee_Name I lowered case the Employee can someone explain it to me? Ill accept it as an answer


text:
Q: Como abrir dialogo para sabes si se quiere cerrar la app (android studio) estoy haciendo una app web, he estado documentandome y no encuentro una forma fácil y efectiva de que se abra un dialogo cuando el usuario esta apunto de cerrar la aplicación y preguntarle si realmente quiere o no cerrarla.
Estoy usando un webview.
Gracias por la ayuda.

A: Crea al metodo:
  private void cerrarAplicacion() {
            new AlertDialog.Builder(this)
                    .setIcon(R.drawable.alacran)
                    .setTitle("¿Realmente desea cerrar la aplicación?")
                    .setCancelable(false)
                    .setNegativeButton(android.R.string.cancel, null)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {// un listener que al pulsar, cierre la aplicacion
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            android.os.Process.killProcess(android.os.Process.myPid()); //Su funcion es algo similar a lo que se llama cuando se presiona el botón "Forzar Detención" o "Administrar aplicaciones", lo cuál mata la aplicación
                            //finish(); Si solo quiere mandar la aplicación a segundo plano
                        }
                    }).show();
        }

Mandalo a traer con el evento:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
       cerrarAplicacion();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

O bien desde un Boton:
tuBoton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
          cerrarAplicacion();
            }
        });


text:
Q: Writing a dict to txt file and reading it back? I am trying to write a dictionary to a txt file. Then read the dict values by typing the keys with raw_input. I feel like I am just missing one step but I have been looking for a while now.
I get this error
File "name.py", line 24, in reading
    print whip[name]
TypeError: string indices must be integers, not str

My code:
#!/usr/bin/env python
from sys import exit

class Person(object):
    def __init__(self):
        self.name = ""
        self.address = ""
        self.phone = ""
        self.age = ""
        self.whip = {}

    def writing(self):
        self.whip[p.name] = p.age, p.address, p.phone
        target = open('deed.txt', 'a')
        target.write(str(self.whip))
        print self.whip

    def reading(self):
        self.whip = open('deed.txt', 'r').read()
        name = raw_input("> ")
        if name in self.whip:
            print self.whip[name]

p = Person()

while True:
    print "Type:\n\t*read to read data base\n\t*write to write to data base\n\t*exit to exit"
    action = raw_input("\n> ")
    if "write" in action:
        p.name = raw_input("Name?\n> ")
        p.phone = raw_input("Phone Number?\n> ")
        p.age = raw_input("Age?\n> ")
        p.address = raw_input("Address?\n>")
        p.writing()
    elif "read" in action:
        p.reading()
    elif "exit" in action:
        exit(0)

A: I created my own functions which work really nicely:
def writeDict(dict, filename, sep):
    with open(filename, "a") as f:
        for i in dict.keys():
            f.write(i + " " + sep.join([str(x) for x in dict[i]]) + "\n")

It will store the keyname first, followed by all values. Note that in this case my dict contains integers so that's why it converts to int. This is most likely the part you need to change for your situation.
def readDict(filename, sep):
    with open(filename, "r") as f:
        dict = {}
        for line in f:
            values = line.split(sep)
            dict[values[0]] = {int(x) for x in values[1:len(values)]}
        return(dict)

A: To store Python objects in files, use the pickle module:
import pickle

a = {
  'a': 1,
  'b': 2
}

with open('file.txt', 'wb') as handle:
  pickle.dump(a, handle)

with open('file.txt', 'rb') as handle:
  b = pickle.loads(handle.read())

print a == b # True

Notice that I never set b = a, but instead pickled a to a file and then unpickled it into b.
As for your error:
self.whip = open('deed.txt', 'r').read()

self.whip was a dictionary object. deed.txt contains text, so when you load the contents of deed.txt into self.whip, self.whip becomes the string representation of itself.
You'd probably want to evaluate the string back into a Python object:
self.whip = eval(open('deed.txt', 'r').read())

Notice how eval sounds like evil. That's intentional. Use the pickle module instead.

A: You can iterate through the key-value pair and write it into file
pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')

A: Have you tried the json module? JSON format is very similar to python dictionary. And it's human readable/writable:
>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))

This code dumps to a text file
$ cat text.txt
{"two": 2, "one": 1}

Also you can load from a JSON file:
>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}

A: Hi there is a way to write and read the dictionary to file you can turn your dictionary to JSON format and read and write quickly just do this :
To write your date:
 import json

 your_dictionary = {"some_date" : "date"}
 f = open('destFile.txt', 'w+')
 f.write(json.dumps(your_dictionary))

and to read your data:
 import json

 f = open('destFile.txt', 'r')
 your_dictionary = json.loads(f.read())

A: Your code is almost right!  You are right, you are just missing one step.  When you read in the file, you are reading it as a string; but you want to turn the string back into a dictionary.
The error message you saw was because self.whip was a string, not a dictionary.  So you need to convert the string to a dictionary.
Example
Here is the simplest way: feed the string into eval().  Like so:
def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = eval(s)

You can do it in one line, but I think it looks messy this way:
def reading(self):
    self.whip = eval(open('deed.txt', 'r').read())

But eval() is sometimes not recommended.  The problem is that eval() will evaluate any string, and if someone tricked you into running a really tricky string, something bad might happen.  In this case, you are just running eval() on your own file, so it should be okay.
But because eval() is useful, someone made an alternative to it that is safer.  This is called literal_eval and you get it from a Python module called ast.
import ast

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = ast.literal_eval(s)

ast.literal_eval() will only evaluate strings that turn into the basic Python types, so there is no way that a tricky string can do something bad on your computer.
EDIT
Actually, best practice in Python is to use a with statement to make sure the file gets properly closed.  Rewriting the above to use a with statement:
import ast

def reading(self):
    with open('deed.txt', 'r') as f:
        s = f.read()
        self.whip = ast.literal_eval(s)

In the most popular Python, known as "CPython", you usually don't need the with statement as the built-in "garbage collection" features will figure out that you are done with the file and will close it for you.  But other Python implementations, like "Jython" (Python for the Java VM) or "PyPy" (a really cool experimental system with just-in-time code optimization) might not figure out to close the file for you.  It's good to get in the habit of using with, and I think it makes the code pretty easy to understand.


text:
Q: Access Ubuntu Server VM on Azure I've setup an Ubuntu Server on Azure. On this server, an application is running on port 3000. I want to access this application external. Azure tells me my server has public ip 40.68.XXX.XXX.
When I ping this IP, there is no response, despite ssh works when connecting to this IP-address.
I want to access 40.68.XXX.XXX:3000 external, does somebody know how to get this work?

A: Yes, you need to open up a port on the Network Security Group (NSG) and open up the port on your firewall (on the VM itself).
Easiest way to open the port is using the portal:
https://learn.microsoft.com/en-us/azure/virtual-machines/virtual-machines-windows-nsg-quickstart-portal


text:
Q: How to split a string into multiple lines in python? I am a newbie in Python. I am trying to write a program that prints the following three words (without punctuation) on three separate lines: first, second, third
m = 'first, second, third'
no_punct = ''
for x in m :
    if x != ',':
        no_punct+= x
k = no_punct.strip()
print(k)

This is the output I had from the above program:
first second third

A: You can use split to remove space, and put each element in a list, then iterate over the list and use strip to remove the occasional ',' char:
m = 'first, second, third'
for x in m.split():
    print(x.strip(','))

first
second
third

Demo:
>>> m = 'first, second, third'
>>> y = m.split()
>>> y
['first,', 'second,', 'third']
>>> y[0].strip(',')
'first'

Split docs (str.split())
Strip docs (str.strip())

A: You can print new lines by using '\n'.
So you need to replace "," with '\n'.
m.replace(',', '\n')
print(m)

A: Instead of storing it in one variable, you can print it immediately.
for x in m :
    if x != ',':
        no_punct+= x
    else:
        print(no_punct.strip())
        no_punct = ""

A one-liner can be
print(*[x.strip() for x in m.split(',')], sep='\n')

A: If the pattern between words is consistently a comma followed by a space, then you can split by a comma and a space like the following:
>>> m = 'first, second, third'
>>> m.split(', ')
['first', 'second', 'third']
>>>

Then once it's split, you can take the elements and join them with a newline, and print the result:
>>> print('\n'.join(m.split(', ')))
first
second
third

A: A simple solution would be like this:
m = 'first, second, third'
print (m.replace(', ', '\n'))

make sure to include the space after the comma in the replace or you will end up with indents.


text:
Q: Load image coming from Server on Canvas I have a designer application in FabricJS. Designer view is being loaded from my Controller action. I am passing an image path with view model to my view.
How can i load this image from path on to my canvas for manipulations.
I am trying to do something like this:
function UploadArtwork() {
        var reader = new FileReader();

        reader.onloadend = function () {
            App.renderImageFromUrl(reader.result, function (image) {
                caseApp.getCanvas().setActiveObject(image);
                }
            });
            event.currentTarget.value = null;
        };

         reader.readAsDataURL('@file');
        }
    }

And i am reading file like this:
var webClient = new WebClient();
    var file = webClient.DownloadData(artwork.ArtworkPath);

Its not working. Any suggestions ?


text:
Q: 7 port powered USB hub backfeeding to my PC I just bought two 7 port usb hubs: LogiLink UA0124. Just to run into a strange situation.
I did some servicing to my PC today and disconnected the main power cord from the PSU. Only to find out that all my usb devices(connected to other usb ports on the PC) are still powered up!
At first I thought that I somehow accidentally  managed to make a perpetuum mobile!!!
When my euphoria run out I figured out that the hubs are giving a constant 5 volts to the PC port (backfeeding), even when I turn off the switch on the usb hub!
I also noticed that the processor fan has a small movement like twitching every 5 seconds...
So there must be some weird current running through my motherboard.
What should I do? This does not seem like some no name cheap product. So I wonder why is it designed in this way. Is it OK when the PC is powered up? I mean does the default voltage of the PC usb port counteract with this one and everything is fine? In that case I should only watch out when turning off the PC? Or is this something serious that could damage my other components?
UPDATE
As per request in the comments, I'm adding few pictures here. And many more on this LINK (LogiLink 7 port USB HUB dismantled)

A: I eventually ended up cutting the +5V(red) line going from the hub to the PC. The only drawback is that the hub obviously needs to be connected to its own power supply to work.


text:
Q: Java Cipher Strange chars in decryption i have a strange problem with my program, i want to encrypt some strings and then decrypt them; I made a trial class to test the function of encryption and decryption. Things works fine for the encryption, but when i try to decrypt, only sometimes, i have strange chars in the middle of the string.
Here is my code:
public class Prova {

public static void main(String[] args){
    String s = "with the lights out is less dangerous here we are now entertain us";
    s = cripta(s);
    System.out.println(s);
    s = decripta(s);
    System.out.println(s);
}

public static String cripta(String s){
    System.out.println("lunghezza stringa:"+s.length());
    byte[] input = s.getBytes();
    byte[] output;
    byte[] keyBytes = hexStringToByteArray("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    byte[] ivBytes = hexStringToByteArray("AAAAAAAAAAAAAAAA");
    String out = "";

    SecretKeySpec key = new SecretKeySpec(keyBytes, "DESede" );
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    try {
        Cipher cp = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cp.init(Cipher.ENCRYPT_MODE, key);
        byte[] criptati = new byte[cp.getOutputSize(input.length)];
        int enc_len = cp.update(input, 0, input.length, criptati, 0);
        enc_len += cp.doFinal(criptati, enc_len);
        out = new String(criptati);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ShortBufferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return out;
}

public static String decripta(String s){

    byte[] input = s.getBytes();
    byte[] output;
    byte[] keyBytes = hexStringToByteArray("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    byte[] ivBytes = hexStringToByteArray("AAAAAAAAAAAAAAAA");
    String out = "";

    try {
        SecretKeySpec key = new SecretKeySpec(keyBytes, "DESede");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        Cipher cp = Cipher.getInstance("DESede/ECB/NoPadding");
        cp.init(Cipher.DECRYPT_MODE,  key);
        byte[] decrypt = new byte[cp.getOutputSize(input.length)];

        int dec_len = cp.update(input, 0, input.length, decrypt, 0);
        System.out.println(dec_len);
        dec_len += cp.doFinal(decrypt, dec_len );
        System.out.println(dec_len);
        out = new String(decrypt);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ShortBufferException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BadPaddingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return out;
}

private static byte[] hexStringToByteArray(String s) {
    // TODO Auto-generated method stub
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;

}

}
The output i recieve is "with the lights out is less dangÝâ¥8,–xÖÆZŽÏö=æe now entertain us"

A: The problem is that encrypted bytes may contain some values that lead to strange behaviour when simply converted to a String. So you should use base64-encoding like that:
In encripta:
out = new String(Base64.getEncoder().encode(criptati));

in decripta:
byte[] input = Base64.getDecoder().decode(s.getBytes());

By the way: Why do you use cp.update()? Why not just cp.doFinal() like that:
Cipher cp = Cipher.getInstance("DESede/ECB/PKCS5Padding");
cp.init(Cipher.ENCRYPT_MODE, key);
byte[] criptati = cp.doFinal(input);
out = new String(Base64.getEncoder().encode(criptati));

and the same for decripta?
EDIT
Working example with all clutter (TODO-comments, unused code, etc.) removed:
public static void main(String[] args) {
        String s = "with the lights out is less dangerous here we are now entertain us";
        s = cripta(s);
        System.out.println(s);
        s = decripta(s);
        System.out.println(s);
    }

    public static String cripta(String s) {
        System.out.println("lunghezza stringa:" + s.length());
        byte[] input = s.getBytes();
        byte[] keyBytes = hexStringToByteArray("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        String out = "";

        SecretKeySpec key = new SecretKeySpec(keyBytes, "DESede");
        try {
            Cipher cp = Cipher.getInstance("DESede/ECB/PKCS5Padding");
            cp.init(Cipher.ENCRYPT_MODE, key);
            byte[] criptati = cp.doFinal(input);
            out = new String(Base64.getEncoder().encode(criptati));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

        return out;
    }

    public static String decripta(String s) {

        byte[] input = Base64.getDecoder().decode(s.getBytes());
        byte[] keyBytes = hexStringToByteArray("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        String out = "";

        try {
            SecretKeySpec key = new SecretKeySpec(keyBytes, "DESede");
            Cipher cp = Cipher.getInstance("DESede/ECB/NoPadding");
            cp.init(Cipher.DECRYPT_MODE, key);
            byte[] decrypt = cp.doFinal(input);
            out = new String(decrypt);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return out;
    }


text:
Q: Doctrine ORM - Same entity, different table for different ownership I have an entity that in it's lifetime moves to different tables. Like so:
A village has many units
An army movement on the map contains many units
After an attack, the log file contains many units (with extra amount_killed column)
So anyway, this Unit is what I consider my entity, that can either be attached to a Village, Movement or Log via a table and foreign key.
I would think in Doctrine there is a way to say, this is an entity and it can as a foreign key to multiple tables. The thing is, I want to pluck Units from my Village and put them into a Movement but they're not defined as the same item so it will break.
My code for current usage will look something like this for transferring an entity to another table:
$villageUnits = $village->getVillageUnits();
$movementUnits = new ArrayCollection();
foreach ($villageUnits as $villageUnit) {
    $movementUnit = new MovementUnit();
    $movementUnit
        ->setLevel($villageUnit->getLevel());
        ->setAmount($villageUnit->getAmount());
        ->setUnitType($villageUnit->getUnitType());
    $movementUnits->add($movementUnit);
}

At the moment, they're all seperate entities defined with Doctrine as follows:
TABLES

village_units
---------
id, village_id, unit_type_id, amount, level

movement_units
---------
id, movement_id, unit_type_id, amount, level

log_units
---------
id, log_id, unit_type_id, amount, amount_killed, level

ENTITIES

/**
 * MovementUnit
 *
 * @ORM\Table(name="movement_units")
 * @ORM\Entity
 */
class MovementUnit
{

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\GeneratedValue(strategy="IDENTITY")
 * @ORM\Id
 */
private $id;

/**
 * @var integer
 *
 * @ORM\Column(name="amount", type="integer", nullable=false)
 */
private $amount;

/**
 * @var integer
 *
 * @ORM\Column(name="level", type="integer", nullable=false)
 */
private $level;

/**
 * @var Movement
 *
 * @ORM\ManyToOne(targetEntity="Movement")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="movement_id", referencedColumnName="id")
 * })
 */
private $movement;

/**
 * @var UnitType
 *
 * @ORM\OneToOne(targetEntity="UnitType")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="unit_type_id", referencedColumnName="id")
 * })
 */
private $unitType;

}

/**
 * VillageUnit
 *
 * @ORM\Table(name="village_units")
 * @ORM\Entity
 */
class VillageUnit
{

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\GeneratedValue(strategy="IDENTITY")
 * @ORM\Id
 */
private $id;

/**
 * @var integer
 *
 * @ORM\Column(name="amount", type="integer", nullable=false)
 */
private $amount;

/**
 * @var integer
 *
 * @ORM\Column(name="level", type="integer", nullable=false)
 */
private $level;

/**
 * @var Village
 *
 * @ORM\ManyToOne(targetEntity="Village")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="village_id", referencedColumnName="id")
 * })
 */
private $village;

/**
 * @var UnitType
 *
 * @ORM\OneToOne(targetEntity="UnitType")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="unit_type_id", referencedColumnName="id")
 * })
 */
private $unitType;

}

/**
 * LogUnit
 *
 * @ORM\Table(name="log_units")
 * @ORM\Entity
 */
class LogUnit
{

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\GeneratedValue(strategy="IDENTITY")
 * @ORM\Id
 */
private $id;

/**
 * @var integer
 *
 * @ORM\Column(name="amount", type="integer", nullable=false)
 */
private $amount;

/**
 * @var integer
 *
 * @ORM\Column(name="dead", type="integer", nullable=false)
 */
private $dead;

/**
 * @var integer
 *
 * @ORM\Column(name="level", type="integer", nullable=false)
 */
private $level;

/**
 * @var LogArmy
 *
 * @ORM\ManyToOne(targetEntity="LogArmy")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="log_army_id", referencedColumnName="id")
 * })
 */
private $logArmy;

/**
 * @var UnitType
 *
 * @ORM\OneToOne(targetEntity="UnitType")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="unit_type_id", referencedColumnName="id")
 * })
 */
private $unitType;

}

A: I had the exact same problem and solved it with the answer of Robin in this question: Doctrine 2 Inheritance Mapping with Association
Just change the inheritanceType from "SINGLE_TABLE" to "JOINED" and your setup is working. If not, try using doctrine-module orm:schema-tool:create it will create the tables for you.


text:
Q: Oauth2RestTemplate - not reading certificates from custom truststore By default, Oauth2RestTemplate is reading certificates from jre truststore. But when we configure the template with HttpComponentsClientHttpRequestFactory, it is not reading the certificates from the custom truststore.
Below is the code:
@Configuration
public class OauthConfig {

@Resource
private HttpComponentsClientHttpRequestFactory backendHttpComponentsClientHttpRequestFactory;

@Resource
private PoolingHttpClientConnectionManager backendPoolingHttpClientConnectionManager;

@Value("${keystore.path}")
private File certificatePath;

@Value("${keystore.password}")
private String certificatePassword;

@Bean("testOauthRestTemplate")
public OAuth2RestOperations oauth2RestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException

{
    ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails();
    resourceDetails.setClientId("clientId");
    resourceDetails.setClientSecret("12345");
    resourceDetails.setAccessTokenUri("https://test:8080/oauth/token");
    resourceDetails.setGrantType("client_credentials");
    resourceDetails.setAuthenticationScheme(AuthenticationScheme.header);
    AccessTokenRequest request = new DefaultAccessTokenRequest();

    OAuth2RestTemplate oauth2RestTemplate = new OAuth2RestTemplate(resourceDetails, new DefaultOAuth2ClientContext(request));

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    HttpClient httpClient = null;

    httpClient = clientBuilder.setConnectionManager(backendPoolingHttpClientConnectionManager)
            .setSSLSocketFactory(SslSettings.sslConnectionSocketFactory(certificatePath, certificatePassword))
            .disableCookieManagement().build();

    backendHttpComponentsClientHttpRequestFactory.setHttpClient(httpClient);

    oauth2RestTemplate.setRequestFactory(backendHttpComponentsClientHttpRequestFactory);

    return oauth2RestTemplate;
}

@Bean("backendHttpComponentsClientHttpRequestFactory")
public HttpComponentsClientHttpRequestFactory backendHttpComponentsClientHttpRequestFactory() {
    return new HttpComponentsClientHttpRequestFactory();
}

@Bean("backendPoolingHttpClientConnectionManager")
public PoolingHttpClientConnectionManager backendPoolingHttpClientConnectionManager() throws KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {

    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", SslSettings.sslConnectionSocketFactory(certificatePath, certificatePassword))
            .build();

    PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
            new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    poolingHttpClientConnectionManager.setDefaultMaxPerRoute(20);
    poolingHttpClientConnectionManager.setMaxTotal(200);

    return poolingHttpClientConnectionManager;
}

}

Below is the Exception:
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
                at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1964)
                at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:328)
                at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:322)
                at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1614)
                at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
                at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1052)
                at sun.security.ssl.Handshaker.process_record(Handshaker.java:987)
                at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1072)
                at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
                at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
                at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
                at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
                at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
                at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:162)
                at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76)
                at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
                at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
                at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:723)
                ... 73 common frames omitted
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:397)
                at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:302)
                at sun.security.validator.Validator.validate(Validator.java:260)
                at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
                at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
                at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
                at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1596)
                ... 87 common frames omitted
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
                at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
                at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
                at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:392)
                ... 93 common frames omitted

Need some suggestion/help..Not able to find the solution..

A: The currently accepted answer gives a solution with incorrect reasoning. The error is not because your OAuth2RestTemplate is unable to access the certificate stores, but it is because the AccessTokenProvider on the OAuth2RestTemplate creates its own RestTemplate internally in order to request the token. In order to set the provider for that internal RestTemplate, you can do the below (change to different types of AccessTokenProviders based on what kind of OAuth you're doing)
ClientCredentialsAccessTokenProvider provider = new ClientCredentialsAccessTokenProvider();
provider.setRequestFactory(requestFactory);
restTemplate.setAccessTokenProvider(provider);

The accepted answer works by applying the trustStore to all requests, which isn't always what you want to do, as it's almost always better to be specific.

A: Your manually configured HttpClient seems not to be able to access the TLS certificate stores. The given error message (javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: ...) points out that a valid SSL-connection couldn't be established, because the program is not able to find the path to the certificate stores.
To solve this issue, you can try to set the Java keystore and truststore settings like this:
SSLConfig.java
@Configuration
public class SSLConfig {
    @Autowired
    private Environment env;

    @PostConstruct
    private void configureSSL() {
      //load the 'javax.net.ssl.trustStore' and
      //'javax.net.ssl.trustStorePassword' from application.properties
      System.setProperty("javax.net.ssl.trustStore", env.getProperty("server.ssl.trust-store"));
      System.setProperty("javax.net.ssl.trustStorePassword",env.getProperty("server.ssl.trust-store-password"));
    }
}

application.properties:
server.ssl.trust-store: YOUR_TRUST_STORE_PATH
server.ssl.trust-store-password: YOUR_TRUST_STORE_PASSWORD


text:
Q: Compare line by line between two files and get store unique data in 2nd file [linux/java] I am trying to make a shell script that will compare two files and append the unique lines in file 1 to file 2.
So, to be more objective:
A fine named temp.txt will be overwritten with a log-file data downloaded using a curl recursively for every 5 minutes.
curl -X GET https://anypoint.mulesoft.com/cloudhub/api/v2/applications/app-name/instances/5y83962206n79e114d530a41-1/log-file -H 'Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=' -H 'Cache-Control: no-cache' -H 'X-ANYPNT-ENV-ID: Sandbox' > temp.txt

Now, i also have a file named backup.txt which needs to be compared to temp.txt and add anything that is unique. The following scenarios arise

*

*During the 1st run the whole temp.txt is copied to backup.txt
1st Run File content

*In 2nd run only the new lines if any should be added to backup.txt
2nd Run File content
I was able to achieve till here using the comm utility of linux
There may also be a situation where the temp.txt is entirely having new content from very first line.

*In this scenario 3rd run, again we need to append the entire data to the backup.txt
3rd Run File content

*In the 4th run we will have new lines compared to the content in 3rd run but completely different compared to the 1st and 2nd run content.
4th Run File content
Here is the challenge i am facing and unable to proceed further.
I have used awk as below from one of the SO links
awk 'FNR==NR {a[$0]++; next} !a[$0]' file2.txt file1.txt >> file2.txt

but it fails when there similar lines from 1st and 2nd runs. It omits those lines! Ex: the json in 3rd and 4th run images if repeated common lines is ignored.

"httpStatus": 400, "errorOccurred": true"

The above fields are ignored while using awk causing loss of data.
Any help is higly appreciated! I have not had a java code yet but i am primary looking for a logic help here.
Regards
Kaushik

A: Why not have the copy of newly downloaded file if it has all the content of the backup + some new lines?


text:
Q: Flutter, android project runs into an error while compiling Ran into build errors, migrated to android X,
Changed the plugins
.....................................
Running "flutter packages get" in prototype...                   1.4s
Launching lib\main.dart on Redmi 5 Plus in debug mode...
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:9: error: cannot find symbol
import androidx.annotation.NonNull;
                          ^
  symbol:   class NonNull
  location: package androidx.annotation
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:10: error: cannot find symbol
import androidx.annotation.Nullable;
                          ^
  symbol:   class Nullable
  location: package androidx.annotation
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:706: error: cannot find symbol
  private void reportException(Result result, @Nullable Exception exception) {
                                               ^
  symbol:   class Nullable
  location: class FirebaseAuthPlugin
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:610: error: cannot find symbol
    public void onComplete(@NonNull Task task) {
                            ^
  symbol:   class NonNull
  location: class FirebaseAuthPlugin.SignInCompleteListener
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:629: error: cannot find symbol
    public void onComplete(@NonNull Task task) {
                            ^
  symbol:   class NonNull
  location: class FirebaseAuthPlugin.TaskVoidCompleteListener
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:647: error: cannot find symbol
    public void onComplete(@NonNull Task task) {
                            ^
  symbol:   class NonNull
  location: class FirebaseAuthPlugin.GetSignInMethodsCompleteListener
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:187: error: cannot find symbol
                      public void onComplete(@NonNull Task task) {
                                              ^
  symbol: class NonNull
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:492: error: cannot find symbol
              public void onComplete(@NonNull Task task) {
                                      ^
  symbol: class NonNull
C:\Users\kenny\Documents\flutter.pub-cache\hosted\pub.dartlang.org\firebase_auth-0.8.1+4\android\src\main\java\io\flutter\plugins\firebaseauth\FirebaseAuthPlugin.java:559: error: cannot find symbol
          public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                                          ^
  symbol: class NonNull
9 errors
         *********************************************************
WARNING: This version of cloud_firestore will break your Android build if it or its dependencies aren't compatible with AndroidX.
         See .... for more information on the problem and how to fix it.
         This warning prints for all Android build failures. The real root cause of the error may be unrelated.
         *********************************************************
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':firebase_auth:compileDebugJavaWithJavac'.

Compilation failed; see the compiler error output for details.

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 10s
Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

A: I stumbled upon a similar problem, because a firebase plugin used compileSdkVersion 27 - I simply forked it to use 28, but it should also be possible to override it from the project root's build.gradle: https://stackoverflow.com/a/50916298/109219
subprojects {
    afterEvaluate {project ->
        if (project.hasProperty("android")) {
            android {
                compileSdkVersion 28
            }
        }
    }
}

A: Have you migrated your project to AndroidX?
Looks like you haven't migrated your project to AndroidX.

What is AndroidX?

"AndroidX is a major improvement to the original Android Support Library. AndroidX fully replaces the Support Library. All new android projects are requested to be migrated to AndroidX if your project is dependant on libraries using AndroidX"

read more here ...

How to migrate to AndroidX

Summary
[ Prerequisite: Android Studio 3.2+. ]
[ Please take a backup before proceeding.]

*

*Open your android project in Android Studio

*Add these two lines to your gradle.properties file
android.useAndroidX=true
android.enableJetifier=true

*Go to your app level build.gradle file and change your
  compileSdkVersion and targetSdkVersion to 28

*From menu click on Refactor > Migrate to AndroidX

*Optionally you can take a zip backup on prompt.

*Once the list is prepared, click on 'Do Refactor'

read more here ...

A: have you move to android X? if yes,
1)make sure your compileSdkVersion and targetSdkVersion is 28
2)sometimes kotlin version is also a cause of this type of error, make sure you use the       latest version of kotlin .(ext.kotlin_version = '1.3.10', in my case).
3)classpath 'com.google.gms:google-services:4.3.2'
4) follow firebase instruction carefully, for adding your application to firebase.
5) if you are using firebase_auth, make sure you enter SHA-1 and SHA-256 signature while adding your application to firebase.
don't forget to consider flutter clean as last step

A: With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
The refactor command makes use of two flags. By default, both of them are set to true in your gradle.properties file:
android.useAndroidX=true

The Android plugin uses the appropriate AndroidX library instead of a Support Library.
android.enableJetifier=true

The Android plugin automatically migrates existing third-party libraries to use AndroidX by rewriting their binaries.


text:
Q: Generics and predicates in c# I have the following code which is not working. It is saying that the values of PartitionKey and RowKey cannot be resolved. I hope that there is some expert out there who can give me some advice. What I have so far is based on some suggestions but still not working.
public class BaseTable
{
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
}

public abstract class AzureTableBase<T> : IAzureTable<T>
    {

     // This method gives the errors. The idea of this method is that instead of
     // supplying the predicate you can just supply a value for partitionkey and
     // rowkey as parameters. The problem is that it doesn't work and give the
     // following syntax errors:
     //
     // Cannot resolve symbol PartitionKey
     // Cannot resolve symbol RowKey
     public virtual T Get<T>(string pkey, string rkey) where T : BaseTable
     {
         var a = this.Query.Where(u => u.PartitionKey == pkey && u.RowKey == rkey);
     }

     //  Following method works:
     public virtual T Get(Expression<Func<T, bool>> predicate)
     {
         return this.Query.Where(predicate).FirstOrDefault();
     }

     public virtual IQueryable<T> Query
     {
        get
        {
            TableServiceContext context = CreateContext();
            return context.CreateQuery<T>(TableName).AsTableServiceQuery();
        }
     }

}

Below is an example of how I currently call the second Get function:
SubTest = testTable.Get(u => u.PartitionKey == "XX" & u.RowKey == "YY")

What I want is to be able to call it like this:
SubTest = testTable.Get("XX","YY")

A: If that's your exact code, you can't have free-floating functions, you need to put your Get<T> in a class, one that preferably has a Query field of sorts.
Based on your updated post and your complete refusal of posting a complete piece of code, I can only assume you don't truly care (or even understand) what your code does, only that it compiles. On that note,
public abstract class AzureTableBase<T> : IAzureTable<T> where T : BaseTable
{
     // don't need to re-generalize this function, T is already inherited from your class
     public virtual T Get(string pkey, string rkey)
     {
         var a = this.Query.Where(u => u.PartitionKey == pkey && u.RowKey == rkey);
         return a.FirstOrDefault();     // again, only guessing.
     }

     public virtual IQueryable<T> Query
     {
        get
        {
            TableServiceContext context = CreateContext();
            return context.CreateQuery<T>(TableName).AsTableServiceQuery();
        }
     }
}

A: This is going to return some sort of collection, probably an IQueryable:
this.Query.Where(u => u.PartitionKey == pkey && u.RowKey == rkey);

Your method claims to be returning a value of type T, which in this case is constrained to be BaseTable (or possibly a subclass). Those two types are not compatible.

A: @Blindly is correct but there is one other piece... Does the T or Type return by context.CreateQuery<T>(TableName).AsTableServiceQuery(); actually inherit from BaseTable?
Example
class OneOfYourTables : BaseTable
{

}

If it doesn't then that is your problem.


text:
Q: ¿Cómo saber si un elemento existe en mi arreglo de objetos javascript? Tengo una lista de objetos de la siguiente manera:
let arreglo = [{"sectorId":1},{"sectorId":2},{"sectorId":3},{"sectorId":4},{"sectorId":5},{"sectorId":6},{"sectorId":7},{"sectorId":8}];

Y necesito saber: ¿Cómo es que puedo saber si existe un objeto consultando solo por el ID?

A: Podrías probar:
if(arreglo.findIndex( (e) => e.sectorId === 5) !== -1) {
// existe
} else {
 // no existe
}

Luego utilizas una variable y reemplazas el 5 de ser necesario.
Acá dejo el enlace a la documentación:
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
También podrías utilizar el método find el cual retorna el elemento encontrado o undefined:
if(arreglo.find( (e) => e.sectorId === 5)) {
// existe
} else {
 // no existe
}

https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/find

A: Usando filter:
Con la funcionalidad de array.filter() ver documentación, puedes obtener los elementos que cumplan la condición del callback que le introduzcas.

let arreglo = [{"sectorId":1},{"sectorId":2},{"sectorId":3},{"sectorId":4},{"sectorId":5},{"sectorId":6},{"sectorId":7},{"sectorId":8}];

let id=8;
let result=arreglo.filter(x=>x.sectorId==id);
console.log(result.length?"existe":"no existe");

id=9;
result=arreglo.filter(x=>x.sectorId==id);
console.log(result.length?"existe":"no existe");

Usando regex:
Es menos confiable porque utilizas el texto y podría haber un salto entre un elemento y otro, pero si utilizas bien el regex podrías lograr "filtros" más complejos. Por ejemplo si el sectorId fuese compartido entre varios nodos incluido padre o hijo (diferentes herarquía).

let arreglo = [{"sectorId":1},{"sectorId":2},{"sectorId":3},{"sectorId":4},{"sectorId":5},{"sectorId":6},{"sectorId":7},{"sectorId":8}];
let id=5;
console.log(JSON.stringify(arreglo).match(`sectorId.{0,2}${id}}`)?"existe":"no existe");

id=9;
console.log(JSON.stringify(arreglo).match(`sectorId.{0,2}${id}}`)?"existe":"no existe")

A: Si sólo quieres saber si existe en el array y no necesitas recuperarlo, puedes usar some, que comprueba si al menos un elemento del array cumple la condición. En teoría debe ser más eficiente que filter, porque en el momento que encuentra un elemento que cumpla la condición, ya no sigue recorriendo el array, mientras que filter procesará todos los elementos.
find tampoco recorre el array hasta el final si encuentra un elemento que cumpla antes, pero te devuelve un entero que tienes que comparar con -1 mientras que some te devuelve directamente un booleano (una diferencia menor, pero es cuestión de gustos)
https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Array/some
if(arreglo.some(s => s.sectorId === 4)){}


text:
Q: Automatically Transcode Video and Upload to Cloud I asked this over on superuser, with no luck - I'm hoping serverfault is the more appropriate site.
I'm looking for a solution to take video files from my HD Camera and automate transcoding to a smaller format and then uploading to the cloud (AWS or otherwise).
The ideal workflow would be where I have a NAS or a folder where I could simply drag the raw files from the camera (call it /toEncode ?). The NAS/computer would see new files there and automatically transcode the video to settings I have already picked and save them to a folder (/readyToUpload) that is sync'd with AWS S3 or some other cloud storage system.
I know that freenas and such will do somehting similar for xbox360 and ps3 transcoding - can I tap into this for my solution?

A: It really does depend on what formats you want to ingest and transcode to/from but certainly any Mac will happily let you create that kind of chain of work. You'd just create a small automator app or applescript and link it to a watch-folder, which would do the work and drop it wherever you like, it could do the upload too if you wished. I'm sure you could write something similar in powershell or a bash script too but I know for a fact it'll work on a Mac.

A: Really depends on the computer. A NAS is generally a basic linux host so you could use a scripted workflow with the aid of a few command line tools. ie.
fsniper (folder watching tool)
ffmpeg (swiss army knife of video transcoding tools)
s3fs  (Fuse based S3 filesystem)
a script in your favourite language would be activated by new files identified by fsniper, it would pass them one at a time to ffmpeg with your preferred transcoding option and then write the output to an interim directory and then move the file using normal file commands to the s3 mounted filesystem.
This should give you the expected workflow above.
M.


text:
Q: A question about proof (-Module over a PID) I can understand the final part of the proof of the Lemma 6.8, page 248, Algebra, Hungerford.
Lemma6.8
Let $A$ be a module over a principal ideal domain $R$ such that $\ p^{n}A=0, p^{n-1}A \neq 0 $ for some prime  $p\in R $ and positive integer $n$. Let $a$ be an element of $A$ of order  $\ p^{n} $
(ii)  There is a submodule $C$ of $A$ such that $A = Ra \oplus C$.
in case of $ A\neq Ra $, Roughly speaking , the author constructs the maximal submodule $C$ s.t $ Ra \cap C = 0.......(1)$ (by using Zorn's Lemma where $C$ is a maximal submodule which satisfies (1)). And then, the author ascertains that the quotient group $A/C$ is cyclic, which is generated $a+C $, i.e $A/C=R(a+C)$. And, finally

...   $A/ C$ is the cyclic $R$-module generated by $a + C$ (that is, $A/C = R(a +
> C)$). Consequently, A = Ra + C,  whence A=Ra $\oplus$ C
  (Q.E.D)

But I cannot understand that $A/C=R(a+C)$ implies $A = Ra+ C$.

A: If $A/C=R(a+C)$, then as sets of cosets we have that $$\{a'+C:a'\in A\}=\{ra+C:r\in R,c\in C\}$$ since $r(a+C)=ra+C$ for $r\in R$ by the definition of the action on the quotient module.
Again as a set, for any $a'\in A$ we have that $$a'+C=\{a'+c:c\in C\}$$
Since $0\in C$, for any $a'\in A$ we have $$a'=a'+0\in a'+C=ra+C$$ for some $r\in R$. Then $$a'=ra+c\in Ra+C$$ for some $c\in C$.
This shows that $A\subseteq Ra+C$. Clearly $Ra+C\subseteq A$, so $A=Ra+C$. By the definition of $C$ we have that $Ra\cap C=0$, so the sum is direct and $A=Ra\oplus C$.

(Edited for clarity)


text:
Q: Destroying Base classes based on derived class I am using two classes one is Base class vehicle and other one derived class Car. All method and properties of base class accessing in multiple derived classes.Instance created only for child class Car etc.
here i have created sample example in github,stackblitz(for me heap snapshot not working)
Base class:
export class Vehicle implements OnDestroy{
}

Derived class:
export class Car extends Vehicle {
}

form component:
import { Component, OnInit } from '@angular/core';
import { Car } from '../utils/Car';
import { AppService } from '../app.service';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {

  utilInstance;
  isInitialization
  constructor(public appService:AppService) { }

  ngOnInit() {
    this.utilInstance=new Car(this.appService);
  }

  ngOnDestroy(){
    console.log('form destroy')

   this.utilInstance=null;
  }

}

After destroying Car class,Taken chrome browser dev-tool heap  but Vehicle class still present in memory even after deleted existing snapshot and than refreshed application tab and again taken heap snapshot.
How to destroy base class Vehicle?
Please give me suggestion.
Thanks.


text:
Q: Why isn't this awk command working So the question is:
Display all of the lines in the file showing only the quantity and product name, in that order, using awk. Product name is the first field and quantity is the second field. The data file is "inventory"
The contents to inventory:
Strawberry Jam,300,4

Raspberry Jam,1216,7

Blueberry Jam,96,195

Strawberry Compote,49,621

Raspberry Compote,1937,624

Blueberry Compote,200,625

Frozen Strawberries,130,1941

Straw Hats,16,2047

My command was
awk '$2 $1' inventory

That should work right? I also tried like
awk '{print $2 $1}' inventory
awk '$2, $1' inventory

and a lot of variations of that, but none works! Can anyone help figure out why?

A: That is a csv (comma seperated values) file so the field separator needs to be specified as , using the -F option.
$ awk -F, '{print $2,$1}' inventory

300 Strawberry Jam
1216 Raspberry Jam
96 Blueberry Jam
49 Strawberry Compote
1937 Raspberry Compote
200 Blueberry Compote
130 Frozen Strawberries
16 Straw Hats

A: Here we go:
awk 'BEGIN{FS=OFS=","} {print $2, $1}' inventory