text:
Q: Django - Search last object created for every id and keep sum off other field I'm doing a query where I want to get the list of all Games, related to an specific Team, but I want the field "date_created", to save only the last date.
So here is my query:
 "games": [
        {
            "id": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2017-08-24T00:00:00",
            "points": "10",
        },
        {
            "id": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2017-09-18T00:00:00",
            "points": "10",
        },
        {
            "donation__sponsor": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2016-06-20T00:00:00",
            "points": "10",
        },
        {
            "id": 5,
            "first_name": "Bail",
            "last_name": "Brownbill",
            "date_created": "2017-11-10T00:00:00",
            "points": "10",
        },
        {
            "id": 5,
            "first_name": "Bail",
            "last_name": "Brownbill",
            "date_created": "2018-01-31T00:00:00",
            "points": "10",
        }
]

And my desire query is:
 "games": [
        {
            "id": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2017-09-18T00:00:00",
            "points": "10",
        },
        {
            "id": 5,
            "first_name": "Bail",
            "last_name": "Brownbill",
            "date_created": "2018-01-31T00:00:00",
            "points": "10",
        }
]

My final objective with this is to have a query with another field that sums an attribute inside
Something like this:
 "games": [
        {
            "id": 3,
            "first_name": "Odille",
            "last_name": "Adamovitz",
            "date_created": "2017-08-24T00:00:00",
            "points": "30",
        },
        {
            "id": 5,
            "first_name": "Bail",
            "last_name": "Brownbill",
            "date_created": "2018-01-31T00:00:00",
            "points": "20",
        }
]

Here is my closest idea:
#I get the sum of points with the name, but missing last date_created
qs = Game.filter(id=1).values('first_name', 'last_name', 'date_created').annotate(points = Sum('points')

With .latest() I'm only getting the last Game, not the last game related to every id.
I thought that I need to do two querysets, and then somekind of union, but idk

A: Try this,
from django.db.models import Sum, Max

Game.objects.values('id').annotate(points=Sum('point'), date_created=Max('date_created'))

This form is equivalant to raw sql,
Select id,SUM(point) as points, MAX(date_created) as date_created from GameTable Group By id


text:
Q: Probability theorem proof: adding a constant to each of the outcomes This is all I have so far... it sounds like a rather straight forward proof but I'm not really sure how to go about this. Also I don't understand how adding a constant to each outcome would be the same as just adding that constant at the end? If you add the constant to each outcome wouldn't that cause a greater result? Just trying some practice homework questions

A: The constant is added to the outcomes. You've added it to the product of outcome and probability. Your last line should say
$$
p_1(x_1+c)+p_2(x_2+c)+\cdots+p_n(x_n+c)\;.
$$
Then you can collect all the terms with the constant and use $\sum_ip_i=1$.

A: Let $X$ be a random variable which takes on the values $x_i$ with probability $p_i$ for $i=1,\dotsc, n$. Then
$$
EX=\sum_{i=1}^nx_ip_i
$$
and
$$
E(X+c)=\sum_{i=1}^n(x_i+c)p_i=\sum_{i=1}^nx_ip_i+c\sum_{i=1}^np_{i}=EX+c
$$
since the probabilities sum to one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Animate LayoutChanges does not work properly I want to animate text in my textswitcher. I went through all the stack questions and the documentation, but they didn't solve my problem.
Here is my XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv__inc_pre_sing__screen_title"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#fff"
        android:gravity="center"
        android:text="PRACTICE"
        android:textAllCaps="true"
        android:textColor="@color/colorAccent"
        android:textSize="16dp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.constraint.ConstraintLayout
        android:id="@+id/rl__inc_pre_sing__tm_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:animateLayoutChanges="true"
        android:background="#efff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv__inc_pre_sing__screen_title">

        <ImageView
            android:id="@+id/tv__inc_pre_sing__quotation_mark"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:src="@drawable/ic_archive_black_24dp"
            app:layout_constraintTop_toTopOf="parent" />

        <TextSwitcher
            android:id="@+id/tv__inc_pre_sing__teacher_message"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="24dp"
            android:layout_marginTop="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/tv__inc_pre_sing__quotation_mark"
            app:layout_constraintTop_toTopOf="parent" />

        <ImageView
            android:id="@+id/iv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:src="@drawable/ic_archive_black_24dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/tv__inc_pre_sing__teacher_message" />

    </android.support.constraint.ConstraintLayout>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:text="Click Me"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <View
        android:layout_width="0dp"
        android:layout_height="16dp"
        android:background="@drawable/ic_launcher_background"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/rl__inc_pre_sing__tm_container" />

</android.support.constraint.ConstraintLayout>

Here is my code
public class Main3Activity extends AppCompatActivity {

    private TextSwitcher mSwitcher;
    Button btnNext;
    int currentIndex=-1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        Resources resources = getApplicationContext().getResources();
        final String[] textString = resources.getStringArray(R.array.teacher_messages);

        btnNext = findViewById(R.id.button);
        mSwitcher = findViewById(R.id.tv__inc_pre_sing__teacher_message);

        mSwitcher.setFactory(new ViewSwitcher.ViewFactory() {

            public View makeView() {
                // TODO Auto-generated method stub
                // create new textView and set the properties like clolr, size etc
                TextView myText = new TextView(Main3Activity.this);
                myText.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
                myText.setTextColor(Color.BLUE);
                return myText;
            }
        });

        // Declare the in and out animations and initialize them
        Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
        Animation out = AnimationUtils.loadAnimation(this,android.R.anim.slide_out_right);

        // set the animation type of textSwitcher
        mSwitcher.setInAnimation(in);
        mSwitcher.setOutAnimation(out);

        // ClickListener for NEXT button
        // When clicked on Button TextSwitcher will switch between texts
        // The current Text will go OUT and next text will come in with specified animation
        btnNext.setOnClickListener(new View.OnClickListener() {
            //
            public void onClick(View v) {
                // TODO Auto-generated method stub
                currentIndex++;
                // If index reaches maximum reset it
                if(currentIndex==textString.length)
                    currentIndex=0;
                mSwitcher.setText(textString[currentIndex]);

                ((ViewGroup) findViewById(R.id.rl__inc_pre_sing__tm_container)).getLayoutTransition()
                        .enableTransitionType(LayoutTransition.CHANGING);

            }
        });

    }
}

The animation on ConstraintLayout whose id is rl__inc_pre_sing__tm_container does not work properly. Suppose my TextSwitcher has text whose length is greater than 3 and then TextSwitcher shows text whose length is 1 then the ConstraintLayout does not animate, if the next text is of length 1 then the constraintlayout animates.
I am not able to figure out this weird behaviour.

A: Here is the issue: When the TextSwitcher transitions from X lines of text to something less than X lines then the TextSwitcher's height does not change.
The TextSwitcher inherits some behavior from ViewAnimator which considers the height of all views when determining the height of the widget. The solution is to add the following XML to the TextSwitcher definition in the layout file that will inhibit this behavior:
    android:measureAllChildren="false"

Thanks to this Stack Overflow answer that states all this better than I have.


text:
Q: Syncing app data to Google Account How exactly does one use the Google account sign in feature in Android Apps?
For example, is it possible to store application data such as tables, shared preferences etc., to a google account from an Android app, and what advantages does this offer over a normal account creation feature inside an app?
The reason I ask is that in the app I plan to develop, it will contain an sqlite database to store rss urls to a user, along with shared preferences and content providers. How would the login process differ between the custom login for the app vs the Google Account login process?

A: Unfortunately Storing app data is deprecated now. Here is a discussion about a way to replace it.
In general Google recommends to use slutions like Cloud Firestore:

Accessing App Data
  Support for storing and syncing in the app data folder will likely be removed from Drive in the future. Clients requiring app data storage are strongly encouraged to migrate to a non-Drive solution such as Cloud Firestore.

A: I recommend using the Google Drive Android API if you want to store data to the cloud.
To use those APIs, you will need to authenticate your users using this guide.

For example, is it possible to store application data such as tables, shared preferences etc., to a google account from an Android app

The Drive API lets you save any type of file to a hidden folder on the user's Google Drive account. You could save a database, a JSON file, or whatever else you want.

what advantages does this offer over a normal account creation feature inside an app?

Here are a few advantages to allowing your user to use a Google account to sign in to your app:

*

*Security- Google spends a lot of time and energy ensuring that Google accounts are secure. If you use Google accounts in your app, you don't need to spend time and energy making sure your custom solution is secure.

*Convenience- Assuming your users are running standard Android, they are guaranteed to have a Google account already. They don't need to create a new account and they don't need to remember another password.

*Access to Google APIs- If you are trying to sync to the cloud, you can use existing APIs from Google to sync data. You don't need to implement this yourself using your own servers.
If you are only doing local storage (you don't need to save to the cloud or sync between devices), then you don't need the Drive APIs, but you still get the other benefits of using a Google account.


text:
Q: getting zero for special positions in a matrix Here is a list:
list = {{1, 2, 3, 2, 3}, {3, 1, 1, 2, 3}, {3, 2, 1, 3, 2}, {1, 2, 1, 1, 1}};

I wish to have all elements be zero except the first and the fourth in each row: desired:
list={{1, 0, 0, 2, 0}, {3, 0, 0, 2, 0}, {3, 0, 0, 3, 0}, {1, 0, 0, 1, 0}};

I have written:
Do[
  Do[
     If[Position[list, list[[i, j]]] != {i, 1} &&
      Position[list, list[[i, j]]] != {i, 4}, list[[i, j]] = 0]
     , {i, 1, 4}]
    ,{j, 1, 5}]

But it doesn't work correctly. Is there any way to reach this goal?

A: list.DiagonalMatrix[{1, 0, 0, 1, 0}]

or
Inner[Times, list, {1, 0, 0, 1, 0}, List] // MatrixForm

$$\left(
\begin{array}{ccccc}
 1 & 0 & 0 & 2 & 0 \\
 3 & 0 & 0 & 2 & 0 \\
 3 & 0 & 0 & 3 & 0 \\
 1 & 0 & 0 & 1 & 0 \\
\end{array}
\right)$$
Edit
It may also be done as follows using Inner (see here):
Inner[Times, list, DiagonalMatrix[{1, 0, 0, 1, 0}]] // MatrixForm

With Dot and SparseArray:
list.SparseArray[{ {1, 1} -> 1, {4, 4} -> 1}, {5, 5}] // MatrixForm

In 'pseudocode':
newmat = oldmat.SparseArray[{ {<col-position-old>, <col-position-new>} -> 1,
          ...}, {< total-cols-old >, <total-cols-new>}]

For example, to create a new list with col-1-old -> col-4-new, col-4-old -> col-1-new, col-3-old -> col-2-new, and entries in all other columns equal to zero:
list1 // #.SparseArray[{ {1, 4} -> 1, {4, 1} -> 1, {3, 2} ->
   1}, {Dimensions[#][[2]], 5}] & // MatrixForm

$$
\left(
\begin{array}{ccccc}
 2 & 3 & 0 & 1 & 0 \\
 2 & 1 & 0 & 3 & 0 \\
 3 & 1 & 0 & 3 & 0 \\
 1 & 1 & 0 & 1 & 0 \\
\end{array}
\right)$$

A: To preserve the original list you could do
 res = list;
 res[[All, {2, 3, 5}]] = 0;
 res // MatrixForm

Or
MapAt[0&, list, {All, {2, 3, 5}}] // MatrixForm

Or (thanks @kglr)
ReplacePart[list, {{_, 2 | 3 | 5} -> 0}] // MatrixForm

All give


text:
Q: DateTime format in the template I am using mustache templates in my application. The datetime values in JSON are shown below:
How do I convert them in a proper format?
Created
"/Date(1335232596000)/"

Submitted
"/Date(1335214659000)/"

A: You need to isolate the number with subString() and use that as the milliseconds input of a new date.
var a = "/Date(1335214659000)/";
var b = parseInt(a.substring(a.indexOf('(')+1,a.indexOf(')')));
var x = new Date(b);
alert(x);

Even better make it a function.
function GetDateFromJSONData (a) {
  var b = parseInt(a.substring(a.indexOf('(')+1,a.indexOf(')')));
  return new Date(b);
}
var x = GetDateFromJSONData("/Date(1335214659000)/");

A: Found the following solution at
http://weblogs.asp.net/hajan/archive/2010/12/13/jquery-templates-in-asp-net-introduction.aspx
. Hope it helps others

   <title>...</title>

   <form id="form1" runat="server">

   </form>

A: I know this question is old, but the solution for handlebars in 2014 would be to use a helper. For example:
Handlebars.registerHelper("formatDate", function (datetime) {
    var d = parseInt(datetime.match(/\d+/));
    return new Date(d);
});

Then use it in your handlebars template:
{{formatDate Created}}

or
{{formatDate Submitted}}

Hope this helps


text:
Q: MVC3 MapRoute problem I created the following route:
routes.MapRoute(
    "TestRoute4", // Route name
    "Report {ref_id} Test Board", // URL with parameters
    new { controller = "stats", action = "index" } // Parameter defaults
);

public ActionResult index(string ref_id)
{
}

This works good but I would now like my controller to know that it's been called from a route that matched Report 25 Test Board. Is there a way in MapRoute that I can also pass other things to the controller? I don't even mind hardcoding. I just just want to pass the words Report and Test Board.
Hope you can help,
Mandy

A: Use DataTokens:
Route route = routes.MapRoute(
    "TestRoute4", // Route name
    "Report {ref_id} Test Board", // URL with parameters
    new { controller = "stats", action = "index" } // Parameter defaults
);

route.DataTokens["YourKey"] = "your value";

On your controller you can do this:
public ActionResult Index() {

   // check if matched route is TestRoute4 (optional)
   if (this.RouteData.Route == RouteTable.Routes["TestRoute4"]) {
      // do something

      var val = this.RouteData.DataTokens["YourKey"];
   }

}


text:
Q: How can I add method to StatefulWidget in flutter? I want to call this method but can not. My purpose is to
take the string from text variable
make a list using the word from string
show the list.
I was hoping to done it by this. Is there any other way or can I do it in this way?
class SecondRoute extends StatefulWidget {
  String text;
  //const SecondRoute({Key? key}) : super(key: key);
  SecondRoute({Key? key, required this.text}) : super(key: key);

  @override
  _SecondRouteState createState() => _SecondRouteState();

}

class _SecondRouteState extends State<SecondRoute> {
  String newT ="";

  List breakText(){
   newT = widget.text;
    var x = newT.split(" ");
    print(x);
    bool res = x.remove("");
    while(res == true){
      res = x.remove("");
    }
    print(x);
    return x;

  }
  List wordlist = breakText();// can not call this method
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Route"),
      ),
      body: Center(
        child: Text(
          "hhhh",
          // text,
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

A: You should move "List wordlist = breakText();" into initState() or build() method.

A: 1-Define List:
List wordlist ;

2-Initialize:
 @override
  void initState(){
wordlist = breakText();
}

A: you need to initialize your data when call _SecondRouteState
class SecondRoute extends StatefulWidget {
  String text;
  //const SecondRoute({Key? key}) : super(key: key);
  SecondRoute({Key? key, required this.text}) : super(key: key);

  @override
  _SecondRouteState createState() => _SecondRouteState();

}

class _SecondRouteState extends State<SecondRoute> {
  String newT ="";

  List breakText(){
   newT = widget.text;
    var x = newT.split(" ");
    print(x);
    bool res = x.remove("");
    while(res == true){
      res = x.remove("");
    }
    print(x);
    return x;

  }
  List wordlist; // declare your list
  @override
  void initState() {
    super.initState();
    wordlist = breakText(); // initialize from here

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Route"),
      ),
      body: Center(
        child: Text(
          "hhhh",
          // text,
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}


text:
Q: How to perform PCA in Matlab when number of dimensions is larger than number of observations? I have a data matrix of say, $3000 \times 200$, i.e. I have $3000$-dimensional observations from $200$ subjects. How can I reduce the dimensionality to $1000$ in MATLAB?
With bigger numbers, princomp() function causes an out of memory error.
I tried princomp(data, 'econ'); but it only returns a $199$-by-$199$ matrix, so am I limited to the number of observations?
I would appreciate an example of how to get the reduced data, if possible.

A: First, function princomp is deprecated, you should use pca instead.
Second, as @ttnphns said, if you only have $200$ subjects, then there is no way you can get $1000$ principal components; maximum number is $199$. See here for an explanation: Why are there only $n-1$ principal components for $n$ data points if the number of dimensions is larger or equal than $n$?
Third, as @Aksakal wrote, Matlab's pca assumes that rows in the data matrix correspond to samples, not variables. So you need to transpose your matrix.
Having all of that in mind, here is the code:
X = randn(3000,200);
[eigenvectors, PCs, eigenvalues] = pca(X');

%// eigenvalues is an array of length 199

A: It appears that you are not calling pca function properly. Your array's must be X(200,3000), while you provide X(3000,200).
This is from the description of princom function:

the n-by-p data matrix X, and returns the principal component
  coefficients, also known as loadings. Rows of X correspond to
  observations, columns to variables.

It seems that you mixed up the rows and the columns of your input matrix.


text:
Q: Undefined reference to `_yyerror' when compiling with Flex and Bison I'm trying to make a compiler for a mini Pascal-like language. I'm using Flex and Bison for this and I came up with this error.
My Flex file:
%{
#include "y.tab.h"
#include <stdlib.h>
#include <string.h>
#include <math.h>
void yyerror(char *);
%}

%%

[1-9][0-9]*     {
                yylval.i = atoi(yytext);
                return INT;
}

program     return PROGRAM;
or          return OR;
and         return AND;
not         return NOT;
if          return IF;
else        return ELSE ;
while       return WHILE;
"+"         return PLUS;
"-"         return MINUS;
"*"         return MUL;
"/"         return DIV;
"["         return LSB;
"]"         return RSB;
"{"         return LCB;
"}"         return RCB;
"("         return LEFTPAR;
")"         return RIGHTPAR;
":="        return ASSIGN;
"=="        return ISEQUAL;
"<"         return LTHAN;
">"         return GTHAN;
"<>"        return NOTEQUAL;
"<="        return LESSEQUAL;
">="        return GREATEREQUAL;

[a-zA-z][a-z0-9]*   {
                    yylval.s = (char*)malloc(strlen(yytext)*sizeof(char));
                    strcopy(yylval.s,yytext);
                    return ID;
}

[ \t\n]+                            /* eat up whitespace */

.                                   yyerror("Unknown Character");

%%
int yywrap(void) {
    return 1;
}

My Bison file:
%{
    #include <stdio.h>
    #include <string.h>
    int yylex(void);
    void yyerror(char *s);
%}

%union {
    int i;
    char *s;
};

%token <i> INTEGERNUM

%token PROGRAM;
%token OR;
%token AND;
%token NOT;
%token IF;
%token ELSE;
%token WHILE;
%token PLUS;
%token MINUS;
%token MUL;
%token DIV;
%token LSB;
%token RSB;
%token LCB;
%token RCB;
%token LEFTPAR;
%token RIGHTPAR;
%token ID;
%token INT;
%token ASSIGN;
%token ISEQUAL;
%token LTHAN;
%token GTHAN;
%token NOTEQUAL;
%token LESSEQUAL;
%token GREATEREQUAL;

%%

program:
        PROGRAM ID block
        ;

block:
        LCB sequence RCB
        ;

sequence:
        statement ';' sequence
        | statement ';'
        ;

bracketsSeq:
        LCB sequence RCB
        ;

brackOrStat:
        bracketsSeq
        | statement
        ;

statement:
        assignmentStat
        |ifStat
        |whileStat
        |
        ;

assignmentStat:
        ID ':=' expression

ifStat:
        IF LEFTPAR condition RIGHTPAR brackOrStat elsepart
        ;

elsepart:
        ELSE brackOrStat
        |
        ;

whileStat:
        WHILE LEFTPAR condition RIGHTPAR brackOrStat
        ;

expression:
        optionalSign expression
        |expression addOper expression
        |term
        ;

term:
        term mulOper term
        |factor
        ;

factor:
        INT
        |LEFTPAR expression RIGHTPAR
        |ID
        ;

condition:
        condition AND condition
        |boolterm
        ;

boolterm:
        boolterm OR boolterm
        |boolfactor
        ;

boolfactor:
        NOT LSB condition RSB
        |LSB condition RSB
        |expression relationalOper expression
        ;

relationalOper:
        ISEQUAL
        |LTHAN
        |GTHAN
        |NOTEQUAL
        |LESSEQUAL
        |GREATEREQUAL
        ;

addOper:
        PLUS
        |MINUS
        ;

mulOper:
        MUL
        |DIV
        ;

optionalSign:
        addOper
        |
        ;

%%

int main( int argc, char **argv )
             {
             printf("TEST\n");

             }

The series of steps I executed was:
$ ./bison.exe -dy comp.y
$ ./flex.exe comp.l
$ gcc -c -w lex.yy.c
$ gcc -c -w comp.tab.c
$ gcc comp.tab.o lex.yy.o -o ex
comp.tab.o:comp.tab.c:(.text+0x4cd): undefined reference to `_yyerror'
comp.tab.o:comp.tab.c:(.text+0x61c): undefined reference to `_yyerror'
lex.yy.o:lex.yy.c:(.text+0x34a): undefined reference to `_strcopy'
lex.yy.o:lex.yy.c:(.text+0x362): undefined reference to `_yyerror'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/bin/ld: lex.yy.o: bad reloc address                0x828 in section `.rdata'
/usr/lib/gcc/i686-pc-cygwin/3.4.4/../../../../i686-pc-cygwin/bin/ld: final link failed: Invalid                operation
collect2: ld returned 1 exit status
$

Any advice as to what to declare and where cause there seems to be that I have declared something the wrong way!

A: It's not enough to declare yyerror. You must provide a definition.
The bison manual suggests the following as a minimal implementation:
 void yyerror (char const *s) {
   fprintf (stderr, "%s\n", s);
 }

The other problem you have is that you misspelled strcpy in your flex file.
More accurately, the other problem revealed by the linker errors is the misspelled strcpy, because your copying code is incorrect. It does not account for the NUL byte which must terminate strings. strcpy will copy that byte, with the result that it will write a 0 in unallocated storage. You'll find it much simpler to use strdup. (And don't forget that you need to free the strings when you're finished with them.)


text:
Q: Distance between icon and text in the Button I have a button defined in the XML shown below:
<Button
    android:layout_width="@dimen/logo_menu_width"
    android:layout_height="@dimen/logo_menu_height"
    android:layout_margin="@dimen/logo_menu_margins"
    android:gravity="left|center_vertical"
    android:background="@drawable/selector_blue"
    android:drawableStart="@drawable/ic_action_settings"
    android:paddingStart="6dp"
    android:text="Options"
    android:textColor="@color/blue_light"
    android:textSize="@dimen/logo_menu_text"
    android:id="@+id/buttonOptions"
    android:layout_gravity="center_horizontal" />

How to increase distance between icon (set with drawableStart) and text? Text alignment is set to left. paddingStart is set to 6dp, but it applies to icon only, not the text.
Is it possible to set it with XML file?
I know I can do this using LinearLayout - containing both ImageView and TextView, but I am trying to limit nesting of the views.

A: Use the android:drawablePadding attribute.


text:
Q: How to get the properties of json object in C#? I am getting the json (objArr) object using the following code:
var objArr = (object[])record.Value;

The code at runtime looks like this:

The json object objArr contains the list of rows, how can I retrieve the properties of rows?
I am able to list the properties with the following loop:
 foreach (var obj in objArr)
 {
      foreach(var item in (Dictionary<string, object>)obj)
      {

      }
 }

but I want to retrieve the properties directly from objArr

A: try this according to your onject specification
JavaScriptSerializer js = new JavaScriptSerializer();
BlogSites blogObject = js.Deserialize<BlogSites>(jsonData);
string name = blogObject.Name;
string description = blogObject.Description;

// Other way to whithout help of BlogSites class
dynamic blogObject = js.Deserialize<dynamic>(jsonData);
string name = blogObject["Name"];
string description = blogObject["Description"];

you can refer this


text:
Q: How to use multiple databases in Hibernate? I have a requirement that I need to create the more than one database to my application,when user login based on there ID need to pick the username and password from the corresponding database and Login.(With out using more than one sessoinfactory).only by creating hibernate cfg.
SessionFactory sessionFactory1 = new  Configuration().configure("oracleconfig.cfg.xml").buildSessionFactory();
    SessionFactory sessionFactory2 = new Configuration().configure("derbyconfig.cfg.xml").buildSessionFactory();

here its herd coded the cfg file how i can give dynamically.

A: For generating and changing a hibernate connection you may like this link: Hibernate Documentation - Chapter 3: Configuration


text:
Q: Chaincode shim: more values for a key or allowing non-integer in the value During the chaincode init, One can deploy key-value pair such as: ["a","100", "b", "200"]
However, I would like to deploy key-value pairs such as: ["a", "100, v1, v2"]
Such that 100, v1, v2 are values of a. Two notes:
1. The values are non-integer
2. The values are separated by comma ","
Is this possible?
I check the chaincode shim: /home/standards/go/src/github.com/hyperledger/fabric/core/chaincode/shim/chaincode.go
The function:
// PutState writes the specified `value` and `key` into the ledger.
func (stub *ChaincodeStub) PutState(key string, value []byte) error {
    return handler.handlePutState(key, value, stub.UUID)

Which invokes handlePutState (key, value, stub.UUID). Any lights on how to modify it so it works as desired? Thanks,

A: In the chaincode, each state can have only a single value associated with it. However multiple values can be simulated by making that "one value" a list. So you could do something like this
stub.PutState("a",[]byte("100,v1,v2"))

The state for "a" is now a comma separated list. When you want to retrieve these values, do the following:
Avals, err := stub.GetState("a")
AvalsString := string(Avals)
fmt.Println(AvalsString)

which should print the following string

100,v1,v2

If you need the individual arguments from there, just split the string on the commas, and convert to appropriate types. Bam, you can store and retrieve elements now.
Alternatively, if you data structure is more complicated than that, it might be worth it to put your data into a json object. You can then use marshaling and unmarshaling to convert back and forth from []byte (which can be stored in the state directly) and object (which is likely easier to use).
Example with Json, using init method because it's the one you mentioned
type SomeStruct struct {
    AVal   string            `json:"Aval"`
    BVal   []string            `json:"Bval"`
}

func (t *MyChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
    //recieve args ["someStringA","BVal1","Bval2","Bval3"]

    //constructing and storing json object
    myStruct := SomeStruct{
        AVal: args[0],
        BVal: []string{args[1],args[2],args[3]},
    }
    myStructBytes, err := json.Marshal(myStruct)
    _ = err //ignore errors for example
    stub.PutState("myStructKey",myStructBytes)

    //get state back to object
    var retrievedStruct SomeStruct
    retrievedBytes, err := stub.GetState("myStructKey")
    json.Unmarshal(retrievedBytes,retrievedStruct)

    //congratulations, retrievedStruct now contains the data you stored earlier
    return nil,nil
}


text:
Q: результат Ajax запроса присвоить в php переменную Есть два файла
index.php, server.php
В файле index.php
Есть список
<select size="3" name="abonents" id="abonents">
    <option  value="2938">2938</option>
    <option  value="3781">3781</option>
    <option  value="3591">3591</option>
</select>

Блок

Ajax запрос

При клике на список пердается значение методом POST в файл server.php и
    в блок поставляется данные из Ajax запроса
Файл server.php
<?php
if (isset($_POST['id'])){

// ...
// Запрос к БД, возвращет массив $result
// ...

echo print_r($result);
}
?>

На данный момент выводятся данные виде текста
Как мне передать данные Ajax запроса (значение Data) в PHP массив для дальнейшей обработки в файле index.php?

A: массив $result, который вы выводите с помощью функции print_r() необходимо преобразовать в JSON, или XML, либо в любой другой формат по вашему желанию и вывести.
echo json_encode($result);

Возможно, вам потребуется указания и других параметров функции json_encode().
Также перед этим неплохо будет указать, что возвращаете вы json данные, для этого использовать заголовки:
header('Content-Type: application/json');

На стороне index.php результат ajax запроса преобразуете обратно в массив с помощью JSON.parse().
$.post('server.php', {id:a}, function(data){
    var arrayData = JSON.parse(data);
    // и далее обработать массив значений.
});

Вернуть результат и передать его для дальнейшей обработки в PHP-код файла index.php не получится. Так как файл этот код уже выполнен,  и показанная страница является непосредственным результатом его работы. Поэтому у вас есть два пути. Реализовать логику полученных данных с помощью JS. Либо обращаться к server.php непосредственно в коде самого index.php. Тут может быть несколько вариантов решения проблемы в зависимости от того, где находятся данные файлы. Возможно если на одном сервере, то вы сможете сделать include нужного файла, либо если такой вариант не подходит, то сформировать GET запрос с помощью функций curl либо file_get_contents() выполнить и дождаться его непосредственно во время выполнения index.php.
в последнем случае вы получаете тот-же кодированный в JSON формат массив значений, и раскодируете его обратно:
$result = json_decode(file_get_contents('/server.php',.....));
foreach($result as $r){
   ...
}

Относительно формирования остальных параметров file_get_contents для передачи POST запроса и подстановки параметро это отдельный вопрос, который тут обсуждался совсем недавно.
Осталось заметить, очевидный вариант, когда файл server.php отдает вам не массив данных, а сформированный html-код, который вы и отображаете на своей странице. Это и есть самый обычный способ работы с ajax-ом

A:     <?php
    header('Content-type: application/json');
    if (isset($_POST['id'])){
     ///
      echo json_encode($result);
    }
    ?>
  js:
    var values = JSON.parse(data)


text:
Q: Android - JSON get single value I have a single JSON object like this
"stringData"

with no column names or anything just a single string
I'm confused how to get that value with no column names
edit the following code to get that single value ?
private void showJSON(String response){
    String value="";
    try {
        JSONObject jsonObject = new JSONObject(response);
        value = jsonObject. ??????
    } catch (JSONException e) {
        e.printStackTrace();
    }
    textViewResult.setText("Value:\t"+value);
}

A: your response is a string but not in json form. so convert this string into jsonObject give JSONException. So. you can do two things 1. first use this string without making jsonobject OR 2. send string in json form from server than convert the string into jsonobject and use.


text:
Q: PowerBuilder application bundle. Hiding database info I am looking at a folder full of files.

*

*Which file format is necessary should I decide to move to a new folder (client's computer).

exe
dll
ini
pbd
pbl
pbr
pbt
pbw

As i know, when deploying a project, PB will create exe, dll, pbr and pbd according to what we've set. So I'm pretty sure these four file formats is necessary.
  I also know that pbl and pbw are two files we use when working on a project. So these two file formats is unnecessary for the client (I assumed, correct me if I'm wrong).
  I don't know about these two: pbt and ini.

*I do know that this ini file, namely klinik.ini is containing
  private information. I don't know how to hide this file (I mean to
  make the program to not depend on this file.) Any suggestion?

A: *

*What you're asking isn't as generic as you're hoping. A lot of these extension types (including PBLs, which you are already thinking can be ruled out) can be answered "It depends on the app." The only ones I'd rule out as development only (and maybe it's just my lack of imagination; I never thought of a need to deploy PBLs until someone told me about their app) would be PBR, PBT and PBW. As for the rest, I'd look at the Application Techniques manual, which is distributed with PB and is also available at the Sybase manuals site.

*The only dependency on this INI is coded into your application; it is not a PowerBuilder INI. If you want an alternate means of deploying this information, you'll need to change your application code.
Good luck,
Terry.


text:
Q: How to derive the sine formula from the cross product Use the cross product to show that sinthetaA÷vector BC = Sin thetaB÷vector AC

A: Equate the area of triangle
$$\lvert\vec{AC}\times\vec{AB}\rvert=\lvert\vec{BA}\times\vec{BC}\rvert\\
\lvert\vec{AC}\rvert\ \lvert\vec{AB}\rvert \sin{\theta_{A}}=\lvert\vec{BA}\rvert\ \lvert\vec{BC}\rvert \sin{\theta_{B}}\\
\lvert\vec{AC}\rvert\ \sin{\theta_{A}}= \lvert\vec{BC}\rvert \sin{\theta_{B}}$$


text:
Q: Probability of area in a region being less than S Consider rectangular coordinate system and point $L(X,Y)$ which is randomly chosen among all points in the area $A$ which is defined in the following manner:
$A=\{(x,y)\,|\,x\in[-10,10],y\in[-5,5]\}$.
What is
the probability $P$ that the area of a rectangle that is defined by points $(0,0)$ and $(X,Y)$ will be greater than $20$?
Can it be generalized for any values of the region and given area?

A: Hint: Can you draw a region of points $(x,y)$ such that the area of the rectangle from $(0,0)$ to $(x,y)$ is $>20$?

A: I have given the image of the figure where the area is greater than 20 and the total rectangle A. Thus the probability is $\boxed{\dfrac{\left(30-20ln(\frac{10}{4})\right)}{50}} = 0.2335$

Generalizations:
$A=\{(x,y)\,|\,x\in[-x_0,x_0],y\in[-y_0,y_0]\}$.
Let the area $20$ be "a"
Then area of (0,0) and (x,y) $= 4\times \left[y_0\times(x_0-\frac{a}{y_0})-aln(\frac{x_0y_0}{a})\right]$ =C
Thus the probability $= \frac{C}{4x_0y_0}$


text:
Q: Problems extend change_form.html in django admin I'm trying to extend the change_form.html template of one of my models to include some information on the page. I've read the django documentation in
https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#overriding-vs-replacing-an-admin-template
The problem is that is occurring:

NoReverseMatch at /contas_pagar/pagamento/2/
  Reverse for 'app_list' with arguments '()' and keyword arguments '{u'app_label': ''}' not found. 1 pattern(s) tried: ['(?P\w+)/$']

I'm using Django 1.6.5 with Django-Suit 0.2.12
The error image:
https://dl.dropboxusercontent.com/u/80415688/error_app_django.PNG
in my_project/my_app/templates/admin/my_app/my_model/change_form.html
{% extends "admin/change_form.html" %}

in my_project/urls.py
urlpatterns = patterns('',
    url(r'^contas_pagar/pagamento/(?P<id_parcela>\d+)/$',
                             'contas_pagar.views.retorna_pagamentos_parcela'),
    # django urls
    url(r'^doc/', include('django.contrib.admindocs.urls')),
    url(r'', include(admin.site.urls)),)

in my_project/views.py
def return_id(request, id):
    data = { 'test': 'test', }
    return render_to_response('admin/my_app/my_model/change_form.html', data,
                              context_instance=RequestContext(request))

Does anyone have any idea how to solve?

UPDATE:
I made some changes to the code.
The view is in my class ModelAdmin.
in my_project/my_app/templates/admin/my_app/my_model/change_form.html:
{% extends "admin/change_form.html" %}
{% block after_field_sets %}{{ block.super }}
    <h2>{{ test }}</h2>
{% endblock %}

in my_project/my_app/admin.py:
class PagamentoAdmin(admin.ModelAdmin):
form = PagamentoForm
model = Pagamento
list_display = ('id', 'parcelas_contas_pagar', 'data', 'valor')

def get_urls(self):
    urls = super(PagamentoAdmin, self).get_urls()
    my_urls = patterns('',
        (r'(?P<id_parcela>\d+)/$', self.admin_site.admin_view(self.retorna_pagamentos_parcela)),
    )
    return my_urls + urls

def retorna_pagamentos_parcela(self, request, id_parcela):
    data = {
        'test': test,
        'opts': self.model._meta,
        'app_label': self.model._meta.app_label,
        'change': True,
        'add': False,
        'is_popup': False,
        'save_as': False,
        'has_delete_permission': False,
        'has_add_permission': False,
        'has_change_permission': True
    }
    return render_to_response('admin/contas_pagar/pagamento/change_form.html', data, context_instance=RequestContext(request))

Not appear more errors. Just is not displaying the fields of my class Admin.

A: change_form.html contains the following url tag:
{% url 'admin:app_list' app_label=opts.app_label %}

So you should pass the opts variable to the template context:
data = {'test': 'test',
        'opts': MyModel._meta}

UPDATE: The change_form.html template uses the {% submit_row %} template tag which requires some other context variables so the data dictionary should be like this:
data = {'test': 'test',
        'opts': MyModel._meta,
        'change': True,
        'is_popup': False,
        'save_as': False,
        'has_delete_permission': False,
        'has_add_permission': False,
        'has_change_permission': False}

A: This is caused most likely because you have a {% url %} tag that is trying to link to the app_list. It could be in your admin/form_change.html or in some other included/extended template.
This is usually caused by context that is not passed correctly such as if you have a tag that looks like {% url 'app_list' %} or {% url 'app_list' var %} and the var is empty.

A: I know it is late answer but for those who is struggle with that now like me, it is because of {% for fieldset in adminform %} adminform - is a form passed as context in change_form.html, however I currently have no idea how to pass it in my extension... Appreciate any comments.


text:
Q: Can't deploy firebase cloud function I'm trying to deploy a firebase cloud function with cors but it doesn't work. This is my code bellow, can someone help me with this ?
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as cors from 'cors'

admin.initializeApp()

const corsHandler = cors({origin: true})

export const getUser = functions.https.onRequest((request, response) => {

    corsHandler(request, response, () => {})

    admin.firestore().doc("profiles/T0XCPHPkrJM4I10okb9KSHyukqn1").get()
    .then(snapshot => {
        const data = snapshot.data()
        console.log(data)
        response.send(data)
    })
    .catch(error => {
        console.log(error)
        response.status(500).send(error)
    })

})

A: The following should work. You have to include the code of your asynchronous Firebase call inside the function.
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as cors from 'cors'

admin.initializeApp()

const corsHandler = cors({origin: true})

export const getUser = functions.https.onRequest((request, response) => {

    corsHandler(request, response, () => {

        admin.firestore().doc("profiles/T0XCPHPkrJM4I10okb9KSHyukqn1").get()
        .then(snapshot => {
            const data = snapshot.data()
            console.log(data)
            response.send(data)
        })
        .catch(error => {
            console.log(error)
          response.status(500).send(error)
        })

    })

})


text:
Q: Users with 10 reputation points hop the fence of protected questions while one with less than 15 can't even upvote an answer Users with 10 reputation points hop the fence of protected questions while one with less than 15 can't even upvote an answer
"Questions should be protected when they are attracting poor answers from new users that exceed the volume which can be moderated in a timely manner."
Although the tool of protected questions is probably rarely used (I have never seen it used), its existence in the current form is implemented in a rather unthoughtful way — it either should go or be fixed. I will argue as to how the latter could be achieved.
One may already answer questions specifically fenced away to protect from poor answers including from new users, but with the same reputation one is not even considered sufficiently qualified to even judge the quality of other questions. A great divide is palpable in the level of carefulness exercised in these two situation.
If one cannot judge the reasonability, soundness or validity of information presented to them to cast a vote under 15 reputations how could they formulate a reasonable answer as that requires to first read and judge information based on which one would provide such an answer also, the same process necessary for casting a positive vote, plus the process to compose it into an answer. Clearly, casting a positive vote requires less competence as providing an answer that is not targeted by the protected question tool.
In fact, the privilege to downvote an answer is further down the road, at 125 reputations.
Since the protected question tool supposes that a lot of answers will come in for its questions targeted, there is no presumption of by heightening the fence, a question would be risked to not receive an answer. We can presume that when answers are present, one may only want to submit an answer when they believe the answers are partly or completely wrong including in missing correct information. If one is unable to judge below 125 reputations, it is unreasonable to assume that one with 10 or 11 reputations, just hopping the protected question fence, is able to judge based on the quality of other questions whether their answer is necessary when a question was protected from a potential flood of poor answers.
Since not only is one presumed to be required to be able to judge whether presumptive previous answers on a poor-answer-prone question are also poor to merit writing an answer, but also to be able to adequately compose such an answer based on a series of positive and negative judgements during their learning process necessary for giving the answer. Therefore, it seems clear to me that the fence has to be set at least >125 reputations, or the repetitional bar presumptively giving the privilege to a user to negatively judge other answers.
In fact, there are certain privileges suggesting that a lack of competence in judging questions and answers exists all the way up to 1000 reputations, the privilege to edit, inter alia answers.
How much higher may be the proper subject of debate, but I see no reason behind allowing any where lower than at least a 126 reputations.
I would argue that in the apparent rarest scenarios the tool needs to be used, it would be appropriate to allow only those to submit an answer who are presumed to be competent to submit edits without community approval.

A: Generally, questions are protected when they start to attract lots of spam answers. Spammers are not known to judge the reasonableness of questions; they just want to post spam.
Protecting questions is set at the lowest possible level to prevent that and usually kicks in automatically. It's also invokable by anyone with the Protect Questions privilege, which for graduated sites you get at 15K.
In fact, you can't protect questions at all if you're not a moderator unless they already have deleted answers by low reputation users.
You say it's not used much on Law, but there are more than 300 protected questions there and around 50,000 protected questions on Stack Overflow for instance. If you don't have at least 10 earned reputation on a site you can't see whether a question is protected on the site itself, you'd have to use a SEDE query to count (or view) them. If you have enough rep to protect questions yourself you can see them all in a list.
Generally, we don't want to put in barriers to answering unless we have to, and if we up the privilege required to answer a protected question, there would be calls to restrict that to moderators and that would defeat a lot of the purpose of protection, i.e., to allow a high reputation user to stop a question getting spammed until a moderator can step in and nuke the spammer's accounts.


text:
Q: How can i put the title of the meme and the upvotes and the link to the meme in the embed discord.py @client.command(pass_context=True)
async def meme(ctx):
    embed = discord.Embed(title="", description="")

    async with aiohttp.ClientSession() as cs:
        async with cs.get('https://www.reddit.com/r/dankmemes/new.json?sort=hot') as r:
            res = await r.json()
            embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
            await ctx.send(embed=embed)

so that is my meme command rn i need help to put the title and amount of upvotes in the embed

A: You can set those attributes via
embed.title = "<your-title>"
embed.url = "https://<your-url>"

And for the upvotes you could add a field
embed.add_field(name = "Upvotes", value = "<your upvotes>")


text:
Q: Build custom error messages in model files (example: using the 'pluralize' method) I am using Ruby on Rails 3.0.7 and I would like to use the pluralize method in a my model file in order to properly build custom error messages.
For example, I would like to do something like the following:
NAME_MIN_LENGHT = 2 # the value is '2' but I plan to change that (maybe dynamically... if it is possible) in future development

validates :name,
  :length     => {
    :minimum        => NAME_MIN_LENGHT,
    :too_short      => "is too short (minimum is #{pluralize(NAME_MIN_LENGHT, 'character')})",
  },

How can I do that? Is it advisable? Why?

A: I'm inclined to agree with Wukerplank that this looks a bit overengineered, but it's still an interesting question.  According to this post you can use helpers in controller methods:
Put this in the class ApplicationController:
 def help
    Helper.instance
  end

  class Helper
    include Singleton
    include ActionView::Helpers::TextHelper
  end

Then you can just use it like so:
def check_for_max_donkeys
    if Donkey.find_fit_donkeys.size == APP_SETTINGS['max_fit_donkeys']
      flash_error "The maximum of #{help.pluralize(APP_SETTINGS['max_fit_donkeys'], 'donkey')} has been reached."
      redirect_to_index
    end
  end

I think something similar should work inside your validation method, but I've not tried it out - do leave a note if it works please :-)


text:
Q: Como testar service worker localmente? Na minha tentativa de entender o funcionamento dos services workers estou tentando implementar o mesmo numa aplicação básica que estou servindo localmente, o problema é que o service worker falha ao se registrar, olhando mais atentamente a documentação percebo que os mesmos necessitam de HTTPS o que me leva a pergunta é possível testar um service worker localmente ou somente no server em produção? Eis meus scripts:
Meu app implementado com express.
# app.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.listen(8080, () => {
  console.log('Application running...');
});

Minha página inicial(e única) que quero cachear.
# index.html

<!DOCTYPE html>

  <title>Welcome to Vue</title>

{{ greeting }}

        To learn more about Vue, visit

          {{ humanizeURL(docsURL) }}

        For live help with simple questions, check out

          the Discord chat

        For more complex questions, post to

          the forum

Meu arquivo referente ao service worker.
# sw.js

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll([
        '/basic-pwa/',
        '/basic-pwa/index.html'
      ]);
    });
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(resp) {
      return resp || fetch(event.request).then(function(response) {
        caches.open('v1').then(function(cache) {
          cache.put(event.request, response.clone());
        });
        return response;
      });
    }).catch(function() {
      return caches.match('');
    })
  );
});

A: Service worker precisa de um ambiente seguro, e "localhost" na porta 80 é considerado um ambiente seguro.
Caso você precise realizar um teste em um ambiente não seguro, pode ligar uma flag no chrome: Insecure origins treated as secure e cadastrar o url.
chrome://flags/#unsafely-treat-insecure-origin-as-secure

obs.: lembre que não adiante apenas cachear o index.html. Precisa cachear qualquer arquivo linkado além das imagens inclusive o favicon.ico...
Nos seus exemplos acima, existe um erro no ws.js, segue arquivo sem erro...
self.addEventListener(
  'install',
  event => {
    event.waitUntil(
      caches.open('v1')
      .then(
        cache => {
          return cache.addAll(
            [
              '/',
              '/index.html'
            ]
          )
        }
      )
    );
  }
);


text:
Q: How can I fix the name error uglifyjs is giving me creating a bundle? I'm using Uglifyjs to create a bundle of old javascript (pre ES2015) files, like this:
uglifyjs *.js -o bundle.js

It works well for a part of the project, but one file contains the new three dots syntax and I get the following error
that.cmd = function(cmd, ...args) {
                         ^
ERROR: Name expected

Does Uglifijs work only with the old javascript syntax? How can I fix the problem?
Edit: I had two different versions installed, using uglify-js-es6 2.8.9 it's all ok!

A: Ensure your --parse options are specifying your intended bundle output and ensure you are using the version or variant that includes ES6 capability.
Looks like uglify-js-es6 works for the above TC-39 Call constructor feature


text:
Q: giving a name to a composite type in Rascal (a la typedef) In Rascal, how do I introduce a name for a composite type (that's constructed from built-in basic types and type constructors like list and map)?
E.g. I'd like to do something like
typedef IntList = list[int];
typedef StrToIntList = map[str,IntList];
StrToIntList mymap = ();

A: Instead of typedef you can use alias. For instance:
rascal>alias IntList = list[int];
ok
rascal>alias StrToIntList = map[str,IntList];
ok
rascal>StrToIntList mymap = ();
StrToIntList: ()

You can use alias to give alternate names to existing basic types as well, so you could also do something like:
alias ID = int;

And, you can include type parameters if needed, so a graph over an arbitrary type could be defined as:
alias Graph[&T] = rel[&T,&T];

Note that an alias introduces a type equivalence and not just a sub-type. So for any function that accepts the alias as argument type, you can also provide a value of the type that it aliases, or any of its sub-types.


text:
Q: Slicing Numpy Array by Array of Indices I am attempting to slice a Numpy array by an array of indices. For example,
 array = [10,15,20,25,32,66]
 indices = [1,4,5]

The optimal output would be
[[10][15,20,25,32][66]]

I have tried using
 array[indices]

but this just produces the single values of each individual index rather than all those in between.

A: Consider using np.split, like so
array = np.asarray([10, 15, 20, 25, 32, 66])
indices = [1, 5]

print(np.split(array, indices))

Produces
[array([10]), array([15, 20, 25, 32]), array([66])]

As split uses breakpoints only, where the index indicates the points at which to break blocks. Hence, no need to indicate 1:4, this is implicitly defined by breakpoints 1, 5.

A: According to your comment this generator produces the desired result:
def slice_multi(array, indices):
    current = 0
    for index in indices:
        yield array[current:index]
        current = index

array = [10,15,20,25,32,66]
indices = [1,4,5]
list(slice(array, indices)) # [[10], [15, 20, 25], [32]]


text:
Q: Series first Vs Shunt First Filter Design Im reading Practical Electronics for Inventors by Paul Scherz and Simon Monk and it says that when designing a LPF Butterworth (passive), when the output impedance seen by the filter is greater than the input impedance, it is best to use a T-configuration (series first) filter.
Why is this? What advantages does the T series first configuration have in this scenario?

A:
when the output impedance seen by the filter is greater than the input impedance, it is best to use a T-configuration (series first) filter.

No, this is not the case.
In a 'normal' filter, both terminations are resistive, you can use either a Tee or a Pi configuration.
When one of the terminations is designed to be either open circuit or short circuit, then you must use the correct configuration. Note the other termination of one of these filters must be resistive.
There may be practical reasons to choose Pi or Tee in a normal filter, whether it's between identical impedances or different resistive ones. Usually, we try to minimise inductors if there's a choice, as they tend to be bigger, more expensive, less 'ideal', available in fewer options, than capacitors. This means Low Pass filters tend to be Pi filters. The shunt Cs will often give us useful stop-band zeroes with their SRF, and you might as well have two of these rather than one. We might choose a Tee filter where it's intended as an isolating filter in a power distribution network, and the series elements are lossy ferrite beads. In that circumstance it's good to have HF power absorption on both sides of the filter.
Where the filter is intended to work into an open or short circuit however, the choice of Pi or Tee is forced. If one port of a filter is loaded with a short circuit, then any shunt component on that port is shorted, and so ineffective. A filter with a zero-ohm port, so driven from a voltage source, or into a short circuit, must have a series component to that port.
Similarly a filter working with an open circuit, either a current drive or a high impedance load, must have a shunt component there, as a series component would be ineffective. This configuration often occurs when we have a large capacitance to drive at high frequencies, for instance a piezo transducer or a Kerr cell. We design a filter to drive an open circuit, at an impedance level where the final shunt filter C is bigger than the load C, then reduce the filter C to 'absorb' the load C into it.
An unexpected case of short-circuit operation occurs in the case of diplexers. Here, the common port maintains a constant voltage regardless of input frequency, so it is in fact a zero impedance point. The highpass and lowpass legs of the filter are then designed to work between a short circuit and the system impedance. As they are short circuit filters, they have series components on that port, which makes sense as those two ports are paralleled together to make the diplexer common port.


text:
Q: Find missing values in a range across a partition, then forward fill values? I'm looking to find missing entries in a field, grouped by two columns as a partition, then forward fill the missing entries.
Table I have:
England    Q1        1     Dogs
England    Q1        2     Dogs
England    Q1        3     Dogs
Germany    Q1        1     Dogs
Germany    Q2        1     Cats
Germany    Q2        2     Cats
France     Q1        1     Cats
France     Q2        1     Cats

So let's say my range is 1 - 3, for every unique [Country][Quarter] combo, I want a full 1,2,3 in the [Number] column, with the [Animal] column forward filling the previous entry.
Table I want:
England    Q1        1     Dogs
England    Q1        2     Dogs
England    Q1        3     Dogs
Germany    Q1        1     Dogs
Germany    Q1        2     Dogs
Germany    Q1        3     Dogs
Germany    Q2        1     Cats
Germany    Q2        2     Cats
Germany    Q2        3     Cats
France     Q1        1     Cats
France     Q1        2     Cats
France     Q1        3     Cats
France     Q2        1     Cats
France     Q2        2     Cats
France     Q2        3     Cats

Let me know if this doesn't make sense!

A: Use cross join to generate the rows.  Then use left join to bring in a value and a window function to fill in the missing values:
select cq.country, cq.quarter, n.number,
       max(t.animal) over (partition by cq.country, cq.quarter) as animal
from (select distinct country, quarter from t) cq cross join
     (select distinct number from t) n left join
     t
     on t.country = cq.country and t.quarter = cq.quarter and t.number = q.number;

Note:  This does rely on all example of the numbers being in the table.  It is easy enough to use:
from (select distinct country, quarter from t) cq cross join
     (select 1 as number union all
      select 2 as number union all
      select 3 as number
     ) n left join
     . . .


text:
Q: how can i find specific strings in string lines using regular expression in JAVA? I have three string lines here.

line 1 :
  56,C0348|23064,C0319|23182,C0127|1476,C0378|2004,C0260|3306,C0091|23179,C0525|
line 2 : 8966,T4992|4446,T4992|4445,E|8965,E;T4992|8964,E;C0163|
line 3 : 920,M128;C0323|

Now, my goal is to remove strings that have a form of "Tnumber|","Cnumber|" , "Mnumber|".
For example, in the first line, i want to delete "C0348|", "C0319|", "C0127|", "C0378|", "C0260|", "C0091|", "C0525|
In the second line , T4992|, T4992, T4992|, C0163|
In the third line, M128; C0323|
How can i remove those strings from each string line?
I think i need to use regular expression, right?
but, i still can not solve this problem.
Could you please help me?

A: You can use Regular expression, like this
import java.util.regex.Pattern;

public class Test {

    private static final String REGEX = "(T|M|C)\\d+(;|\\|)?";
    private static final Pattern p = Pattern.compile(REGEX);

    public static String filterer(String inputString) {
        String result = "";
        for(String s : p.split(inputString)) {
            result += s;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(filterer("56,C0348|23064,C0319|23182,C0127|1476,C0378|2004,C0260|3306,C0091|23179,C0525|"));
        System.out.println(filterer("8966,T4992|4446,T4992|4445,E|8965,E;T4992|8964,E;C0163|"));
        System.out.println(filterer("920,M128;C0323|"));
    }
}

Output
56,23064,23182,1476,2004,3306,23179,
8966,4446,4445,E|8965,E;8964,E;
920,

RegEx Demo

Debuggex Demo
Of course, instead of having capture groups, we can use character classes like this

Debuggex Demo

A: You may try a regexr of [TCM]\d+[\|;], http://regexr.com/v1?38ls3. And as java source:
String reg= "[TCM]\\d+[\\|;]";
String line = "56,C0348|23064,C0319|23182,C0127|1476,C0378|2004,C0260|3306,C0091|23179,C0525|";
line = line.replaceAll(reg, "");
System.out.println(line);
line = "8966,T4992|4446,T4992|4445,E|8965,E;T4992|8964,E;C0163|";
line = line.replaceAll(reg, "");
System.out.println(line);
line = "920,M128;C0323|";
line = line.replaceAll(reg, "");
System.out.println(line);

output:
56,23064,23182,1476,2004,3306,23179,
8966,4446,4445,E|8965,E;8964,E;
920,

A: as these are comma delimitered values you can split them as
String arr[] = line.split (",");

// iterate over them
int index = arr[0].indexOf ("|");
if (index != -1) {

   // do substring
}


text:
Q: CSS 3: When using image in Column-count the top of the columns no longer align I am using CSS3 column-count. When I insert a image into the column text, the top of the columns no longer align.
I cannot make it work in IE 10, Firefox, Opera and Chrome in Windows 8.
I have searched but could not find anything on the subject. What can I do?
Kinde Regards
http://jsfiddle.net/lassebjensen/KeWX8/
Html:

 Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed nibh sapien, adipiscing non arcu vel, pulvinar pretium mi. Proin porta, lectus id bibendum condimentum, magna massa tincidunt lorem, non dictum justo leo at purus. Morbi ultricies cursus diam ac pretium. Curabitur auctor, justo sit amet volutpat auctor, mauris tortor vehicula urna, in dignissim enim sapien eu tortor. Donec tincidunt mauris purus, vel volutpat nibh convallis at. Pellentesque condimentum nec purus eu rutrum. Duis elementum faucibus ante eget imperdiet. Aenean lacinia mauris et blandit hendrerit. Vivamus arcu risus, tincidunt non sapien sit amet, tempor laoreet mi. Sed at imperdiet mi, in ornare nibh. Pellentesque a laoreet orci, posuere volutpat diam. Aenean auctor odio sed vulputate condimentum. Vestibulum eu nibh nec lacus mollis placerat. Suspendisse suscipit ut lacus ornare eleifend. Sed faucibus velit id nulla vestibulum, quis suscipit augue eleifend.

        Donec rutrum mauris quis faucibus consequat. Praesent pulvinar commodo facilisis. Duis id eros id sapien mattis vestibulum quis nec est. Sed eleifend feugiat vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ac hendrerit est. In a purus velit. Aliquam a diam placerat, dignissim ipsum ut, viverra lorem. Donec ut egestas justo, in aliquam dolor. Sed a malesuada mi. Integer nec fringilla justo. In at laoreet mauris. Proin adipiscing mollis ullamcorper.

Css:
.two-columns-article{
    -webkit-column-count: 2;
    -webkit-column-gap: 34px;
    -webkit-column-rule: 1px dotted #d5d5d5;
    -moz-column-count: 2;
    -moz-column-gap: 34px;
    -moz-column-rule: 1px dotted #d5d5d5;
    column-count: 2;
    column-gap: 34px;
    column-rule: 1px dotted #d5d5d5;
}

img{ width:300px; float:right;}

A: I've updated your fiddle. My changes include adding:
.two-columns-article p { margin:20px 0; }
.two-columns-article > p:first-child { margin-top:0; }
img{ display:block; width:300px; }

This:

*

*Sets a margin on paragraphs to be 20px in the y direction

*Removes any top margin on the first paragraph

*Removes the float on your image, and set it to be block.

The columns seem to be well aligned to me :)
Edit: I also moved the image deeper into the paragraph to see if it would still look OK there. It does
Edit 2: I think that styling it this would look pretty kick-ass
.two-columns-article > p {
    margin:20px 0;
    text-align:justify;
}
.two-columns-article > p:first-child { margin-top:0; }
.two-columns-article img {
    display:block;
    width:100%;
    margin:10px 0;
}

A: I've had a look at your fiddle and, for me, in Chrome adding the image makes no difference.
The issues is being caused by the margin on the first paragraph pushing the text down but, due to the way margin works with CSS3 columns, subsequent margin on columns does not push the them down from the top of the container but instead add spacing between them. It does make sense - as the content is now part of the 'column flow' rather than the 'block' flow.
The simple fix for your issue is:
.two-columns-article p:first-child {
    margin-top: 0;
}

http://jsfiddle.net/KeWX8/1/

A: Try this one:
[Demo]
In this i just removed the p tag.


text:
Q: How to support workday app with multiple docusign esignature accounts? Workday supports the use of only 1 Docusign esignature Account Integration key to be configured in their system/tenant. However I need to understand from DocuSign community if there is a way to link multiple docusign integration key/account to the same Workday tenant using a custom integration. This way the documents from workday can be published into the respective docusign accounts for e signature (based on the geographic location)... Any ideas and experience on this ?

A: For your benefit and everyone else, there's a confusion I'd like to make sure is cleared.
DocuSign has Accounts and Integrations Keys.
Accounts
Represents a tenant in the DocuSign cloud with one or more users. Users of the account can use many apps that each have a different integration key if they consent to them.
Integration Key
Represent an integration (or an app) and while the developer who created it had to use an account to get it going - any DocuSign account can use it as long as they consent.
So it's a many-to-many relationship and a completely different thing. The workday app has a single Integration Key but it can be used with many different accounts.


text:
Q: Difference between static variable inside and outside of a function? static int count;

int main()
{

 static int count;

}

Is there any difference between static variables declared inside and outside any function?
(I mean the scope and visibility of the variable count)

A: When you declare outside of method it will be available to all static method functions written after its declaration. While declaring static variable in method will be accessible by only that method.

A: There's also a difference in dynamic initialization of globals (see here).  To summarize, if you had:
static int count = bar();

int main ()
{
  static int count = foo ();
}

The call to 'foo' will take place when main is executed, but the standard (C++ '03) doesn't require a call to 'bar' at all!

A: Your first count is only accessible within the module (code in that file). Your second count is only accessible within main.


text:
Q: JMH Benchmark get NullPointerException with Autowired field in Spring(with maven) project I try to benchmark some of the methods of my Spring (with maven) project. I need to use @Autowired and @Inject on several fields in my project. While I run my project, it works well. But JMH always gets NullPointerException with @Autowired/@Inject fields.
public class Resources {

    private List<Migratable> resources;

    @Autowired
    public void setResources(List<Migratable> migratables) {
        this.resources = migratables;
    }

    public Collection<Migratable> getResources() {
        return resources;
    }
}

My Benchmark class
@State(Scope.Thread)
public class MyBenchmark {

    @State(Scope.Thread)
    public static class BenchmarkState {

        Resources res;

        @Setup
        public void prepare() {
            res = new Resources();
        }
    }

    @Benchmark
    public void testBenchmark(BenchmarkState state, Blackhole blackhole) {
        blackhole.consume(state.res.getResources());
    }
}

When I run my benchmark, it get NullPointerException at Resources.getResources()
More specifically at resources.
It cannot Autowire setResources(). But if I run my project(exclude benchmark), it works fine.
How can I get rid of this NullPointerException with Autowired field while benchmarking?

A: Here is an example of how to run Spring-based benchmarks: https://github.com/stsypanov/spring-boot-benchmark.
Basically what you need is to store a reference to your application context as a field of benchmarks class, initialize the context in @Setup method and close it in @TearDown. Something like this:
@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@BenchmarkMode(value = Mode.AverageTime)
public class ProjectionVsDtoBenchmark {

  private ManyFieldsRepository repository;

  private ConfigurableApplicationContext context;

  @Setup
  public void init() {
    context = SpringApplication.run(Application.class);
    context.registerShutdownHook();

    repository = context.getBean(ManyFieldsRepository.class);
  }

  @TearDown
  public void closeContext(){
    context.close();
  }
}

The logic that you are going to measure must be encapsulated in a method of Spring component called from @Benchmark annotated method. Remember general rules of benchmarking to make sure your measurements are correct, e.g. use Blackhole or return value from the method to prevent compiler from DCE.

A: Try to use
@RunWith(SpringJUnit4ClassRunner.class) and @ContextConfiguration(locations = {...}) on the test class. This should initialize Spring TestContext Framework and let you autowire dependencies.
If this doesn't work, then you have to start Spring ApplicationContext explicitly as a part of you @Setup annotated method, using either of

ClassPathXmlApplicationContext, FileSystemXmlApplicationContext or
  WebXmlApplicationContext  and resolve beans from that context:

ApplicationContext context = new ChosenApplicationContext("path_to_your_context_location");
res = context.getBean(Resources.class);


text:
Q: No URL Shorteners? Are URL shorteners banned on SO? I have had several of my questions edited and the URL shortener removed. (I am using TinyURL.com.) Are there reasons for this or is it solely so a person can edit the question?
I am using the URL shorteners because the site is in development and I do not want any links pointing to it for a few different reasons.

A: They're not banned.
We just hate them.
We really, really hate them.
Persistent use of short URLs in your posts is a good way to get the attention of editors and moderators. Editing to replace them with canonical URLs is both acceptable and encouraged.

A:
I am using the URL shortners because the site is in development and I do not want any links pointing to it for a few different reasons.

Most people hate them, because they can't actually know what that link is. Everytime you post link here on Stack Exchange network, link contains rel="nofollow" attribute which most good crawlers honor. And, I think you forget that crawlers follow links, which means that if Google goes to the tinyurl page, it is, after all, redirected to the original url..


text:
Q: does the order on the Where statement hits the performance? Does the order you specify when constructing your query affects the performance? Or SQL does smart filtering.
For example assume I have a table Employee with 2 million records:
Employee( emp_id, name, dept_id, country_id )

not let's say I want  to get the id and name for those employees in  country id 500 and dept id 17.
Not lets say there about 300k  in that dept and about 1million in that country, however the result of those that met both criterions isw 50k.
Would it make a perfomance difference if I do:
SELECT *
FROM employees
where dept_id = 17 and country_id= 500

than if I do:
    SELECT *
    FROM employees
    where  country_id= 500 and dept_id = 17

Assuming the latter will cut down the table to 1 million then do the rest from there  and
the first query will cut down to 300k and do the 2nd filter from there.
However as mentioned before I'm unsure this is how the SQL motor handles the query.

A: Most modern RDMBS won't have a problem with the order of values in the WHERE-part of the statement, their query optimizers will in most cases sort it out the way you've described it to maximize the performance.
I know of a few older RDBMS who actually will be affected quite significant if you choose the "wrong" order, but those should be out of fashion for the last decade.

A: In the above table,
if non-clustered index is there for -
(country_id,dept_id,employee_id) in the table,
then the query -
SELECT *
    FROM employees
    where  country_id= 500 and dept_id = 17

will have better performance.
and
if non-clustered index is there for -
(dept_id,country_id,employee_id) in the table,
then the query -
SELECT *
    FROM employees
    where  dept_id = 17 and country_id= 500

will have better performance.
If no non-clustered index is there,
then the query -
SELECT *
    FROM employees
    where  dept_id = 17 and country_id= 500

will have better performance for 2nd filtering subset is lower in number.
Also to mention,
If both the non-clustered index are there,
then the query -
SELECT *
    FROM employees
    where  dept_id = 17 and country_id= 500

will have better performance for 2nd filtering subset is lower in number.

A: It does affect, especially when you have residual predicates on your execution plan, but most of the time the query optimizer will do the job of reordering the predicates for you.
That assumes, of course, that your indexes and statistics are well-maintained and updated, so it's something to account for.
Further reading: http://sqlserverpedia.com/wiki/Index_Selectivity_and_Column_Order


text:
Q: Clean up data with PHP by moving position of specific words I have some data I´d like to clean-up. This should be a common problem but I have not found a solution. The data looks like this and should be converted into:

*

*Easiest, The -> The Easiest

*Night, The - Is black -> The Night - Is black

*Trip,A - Go west -> A Trip - Go west

*Muse, La: 3 chansons -> La Muse: 3 chansons

*Passion, La (OMG) -> La Passion (OMG)

*Johnny - One to go for, The -> Johnny - The One to go for

*Peace, The "Great one" -> The Peace "Great one"

A special situation is a double occurrence:

*

*Internet Generation, The - Dream, A -> The Internet Generation - A Dream

Leave as is as there is no "stop" character and the word "the" is not at the end:

*

*Chuck, the fighter -> Chuck, the fighter

So there are multiple words that need to be moved (the, a, la) to the beginning and several "stop" characters [:,-,(,",end of string]. There can be a whitespace before the comma or not.
I tried to solve the problem with preg_replace but could not come up with a working solution. I am sure it is possible for someone more experienced. I´d very much appreciate your help on this!
Final solution I am using based on elclanrs´ answer:
$tests = array(
    "Easiest, The",
    "Heaviest,The",
    "Night, The - Is black",
    "Trip,A - Go west",
    "Muse, La: 3 chansons",
    "Passion, La (OMG)",
    "Johnny - One to go for, The",
    "Peace, The \"Great one\"",
    "Chuck, the fighter",
    "Mason, the hero ",
    "Internet Generation, The - Dream, A",
);

$patt = '/([^,:"(-]+)\s*?,\s*?([^,:"(-]+)/';

foreach ($tests as $test) {
    if (preg_match('/(([:"(-]+)\s*?)|,\s*?\w+\s*?$/', $test)) {
        echo trim(preg_replace('/\s+:/', ':', preg_replace('/\s+/', ' ', preg_replace($patt, '$2 $1 ', $test)))) . PHP_EOL;
    } else {
        echo "Not modified: " . $test . PHP_EOL;
    }
}

which will give:
The Easiest
The Heaviest
The Night - Is black
A Trip - Go west
La Muse: 3 chansons
La Passion (OMG)
Johnny - The One to go for
The Peace "Great one"
Not modified: Chuck, the fighter
Not modified: Mason, the hero
The Internet Generation - A Dream

So I am just skipping the strings which do not need to be modified and removing all unnecessary spaces.

A: Here's a possible solution:
$tests = array(
    "Easiest, The",
    "Night, The - Is black",
    "Trip,A - Go west",
    "Muse, La: 3 chansonss",
    "Passion, La (OMG)",
    "Johnny - One to go for, The",
    "Peace, The \"Great one\""
);

$patt = '/([^,:"(-]+)\s*?,\s*?([^,:"(-]+)/';

foreach ($tests as $test) {
    echo preg_replace($patt, '$2 $1 ', $test) .'<br>';
}

This will print out:
The Easiest
The Night - Is black
A Trip - Go west
La Muse : 3 chansonss
La Passion (OMG)
Johnny - The One to go for
The Peace "Great one"

You'd have to update the tokens if you have more rules [^,:"(-]. It's not perfect as you can see there's a space before the :, but I'll leave that and the special cases up to you...


text:
Q: Detecting when modal view has been displayed This is a fun one...  I have an application that has a help screen and is displayed as a modal view.  The main view has an action that occurs when the device is shaken.  I do not want the action to occur (sounds are played) when the help screen has been displayed.
I have tried a few things... here is my code:
To display the help screen:
- (IBAction)helpButtonPressed:(id) sender {
    helpViewController = [[HelpViewController alloc] init];
    [self presentModalViewController:helpViewController animated:YES];
}

To release the help screen:
- (IBAction)buttonPressed:(id) sender {
    [self dismissModalViewControllerAnimated:YES];
}

I tried the following with no success:
if ([helpViewController.view isHidden ]) {
    NSLog(@"Shake -- helpView is loaded");
} else {
    NSLog(@"Shake -- helpView is not loaded");
}

if ([helpViewController isViewLoaded]) {
    NSLog(@"Shake -- helpView is loaded");
} else {
    NSLog(@"Shake -- helpView is not loaded");
}

if ([self isViewLoaded]) {
    NSLog(@"Shake -- helpView is loaded");
} else {
    NSLog(@"Shake -- helpView is not loaded");
}

What I was thinking is if there is a function to allow me to detect if the help view is showing, I will return without playing the sounds when the device is shaken....
Any ideas?

A: I'm assuming that the view controller which loads the modal controller is also the view controller that responds to the shake action. If that's the case, then you can use the parent view controller's modalViewController property to see whether the modal controller is active:
if(self.modalViewController != nil) {
    // Modal view controller is active; do nothing
    NSLog(@"Shake -- helpView is loaded");
    return;
} else {
    // No modal view controller; take action
    NSLog(@"Shake -- helpView is not loaded");
    [self performSomeAction];
}


text:
Q: Does this mean i have two installations of python? Should i delete the global one? I only use conda enviroment This is very confusing for a newbie

A: Everything here looks normal. That global one appears to be the macOS system installation - leave it alone, don't use it or try to delete. For each project or project-type create a Conda environment.


text:
Q: Python: How to delete multiple files from server at once using OVH cloud API ( I am using Python Request Delete method) I want to delete files from the server using the Pycurl or Python request method. I have a list of file names and I want to delete all files from OVH server by comparing name with the List items. I am using OVH cloud API.
this is the code for delete one file from the server. I want to delete multiple files. how do do this ?
file_path = '/home/u_file.txt'

url url ='https://'+OVH_ENDPOINT+'+filename

headers = {
    'content-type': "multipart/form-data; boundary=----
WebKitFormBoundary7MA4YWxkTrZu0gW",
    'X-Auth-Token': ""+ovhToken+"",
    'Cache-Control': "no-cache"
    }
r = requests.delete(url, headers=headers)
n = os.write(sys.stdout.fileno(), r.content)


text:
Q: Where does wordpress store emails user enters when writing comments? I'd like to do some kind of newsletter.
My idea is to get emails users entered when they were commenting my blog and send daily email to them all.
Where does wordpress keep that emails?
Is there  any recommendation for doing some kind of newsletter/subscription?
Which plugins do you recommend?

A: The email address associated with comments is kept in the $wpdb->comments table. Strictly speaking, that is the answer to the primary question.
I'd be cautious culling email from comments as posting a comment is not clearly giving permission for you to send email.

Is there any recommendation for doing some kind of
  newsletter/subscription?

Use a third party service like MailChimp or Constant Contact (not affiliated with either). Many hosts do not allow mass email through their mail servers. (Check your terms of service.) And, while I am not a lawyer, it seems to me that complying with the legal requirements for sending mass email can be tricky-- especially since I am not a lawyer. A decent service will deal with most of that for you.
Plugin recommendations are off-topic but you can search the plugin directory. There are a lot of plugins related to this subject, including plugins that interface with the services mentioned, and others not mentioned.


text:
Q: number of bound variables does not match number of token I created a php page which gonna save a record into a database, this is the code I wrote :
try
    {
        $bdd = new PDO('mysql:host=localhost;dbname=tp_js_php','root','');
    }
    catch(PDOException $e)
    {
        die($e->getMessage());
    }

    //Selectionner la table de clients
          $reponse = $bdd->query('Select * from client');
          $clients = $reponse->fetchAll();

try
            {
            $req = $bdd->prepare('INSERT INTO client(nomClient,PrenomClient,Adresse,Télephone,Email,Pseudo,MotDePasse) VALUES (:nom, :prenom, :adresse, :tel, :email, :pseudo, :mdp)');
            $req->execute(array(
                    ':nom' => $_POST['nom'],
                    ':prenom', $_POST['prenom'],
                    ':adresse', $_POST['adresse'],
                    ':tel', $_POST['telephone'],
                    ':email', $_POST['email'],
                    ':pseudo', $_POST['pseudo'],
                    ':mdp', sha1($_POST['mdp'])));
        }
        catch(PDOException $e)
        {
            die($e->getMessage());
        }

this is the error I got :
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in C:\xampp\htdocs\tp_fomulaire_js\insertion.php on line 21

the line 21 is : ':mdp', sha1($_POST['mdp'])));
I count all the parametres an no one is messing except the idClient which is incremental.

A: use this code, you have to use => , but you used ,.
$req->execute(array(
                ':nom' => $_POST['nom'],
                ':prenom' => $_POST['prenom'],
                ':adresse' => $_POST['adresse'],
                ':tel' => $_POST['telephone'],
                ':email' => $_POST['email'],
                ':pseudo' => $_POST['pseudo'],
                ':mdp' => sha1($_POST['mdp'])));


text:
Q: Subquery returning multiple columns I am writing a select subquery that returns a COUNT. However, I need to use a HAVING clause in the subquery and as a result need to specify that column in my subquery SELECT.  So the result is that I have 2 columns:  COUNT and column_for_having_clause.
Is there any way that i can tell SQL to take just the first column.  I get an error saying
"Operand should contain 1 column(s)". I figure this must be a common problem, does anyone know a way around it?
Also, is there a way you can execute a HAVING clause without specifying the column in your SELECT query?
Thanks!

A: You could do
SELECT blah FROM foo WHERE bar = (SELECT cnt FROM (SELECT cnt, column_for_having_clause FROM table .... HAVING ... LIMIT 1))

Quite ugly however.

A: Sure, you can specify virtually any expression you want in the HAVING clause.  It doesn't have to be a column from the select-list.
SELECT ...
FROM foo
WHERE x = (SELECT COUNT(*) FROM bar
           GROUP BY y HAVING y = MAX(y));

But you can also, if you're comparing the count to something in the outer query, compare tuples.
SELECT ...
FROM foo
WHERE (x, 1) = (SELECT COUNT(*), y = MAX(y) AS is_max FROM bar
                GROUP BY y HAVING is_max = 1);


text:
Q: Android Studio: "cannot resolve symbol R" after importing Project from Github and rebuilding/cleaning/syncing with gradle files I imported a project from github ("https://github.com/londonappbrewery/I-Am-Poor-Android") and my Main class cannot resolve the symbol R. I googled and tried the following solutions:

*

*Clean Project

*Rebuild Project

*Invalidate Caches and Restart

*Sync Project with gradle files

I am new to Android Studio and currently following a tutorial on Udemy. If somebody could help me understand why it is not working and helping to find a solution, I would be very thankful!

A: Brotherrrrrr, your project uses the 3.3.1 release of the Android Gradle plugin.
Make sure you are using Android Studio 3.3.1 aswell.
Greetings,
Your brotherrrrr


text:
Q: Joins not working due to missing properties in Neo4J I imported data into the neo4j database and there were some blank values as well so while importing the data, the property didn't create into the nodes which have blank values. i.e.
Student
Name | City
Amit | Delhi
Akshay |
So 2 nodes are being created. 1 node has 2 properties and another node has a single property.
I created a relationship something like:-
LOAD CSV WITH HEADERS FROM "file:///Student.csv" AS row
MATCH (e:College {College_ID: row.College_ID})
MATCH (c:Student {Name: row.Name,City: row.City})
MERGE (c)-[:REQ_TestedBy_TC]->(e);

Now when I'm going to join these nodes like:-
(c:College)-[r:CollegeHaveStudent]->(s:Student)

Then it is returning only the first row because the second student doesn't contain the City property so Join is not working.
I need help with what can be a workaround for that situation.


text:
Q: Add values when JCheckBox clicked My program contains a label with the caption "Choose a coffee" and four check boxes – Americano, Espresso, Double Espresso and Latte. Note: A JCheckBox array is recommended here)
I need to add event handling code to allow the user to purchase one or more items. The bill amount is displayed in a label after the user has made their selections.
The prices are  Americano €3.75, Espresso €4.00, Double Espresso €4.50 and Latte €3.50. An array is suitable here also.
As the user makes a choice a label is displayed showing the bill.
I cant figure out how to add the cost when the check box is selected and remove the cost when it is de selected using the arrays.
Any help appreciated.
This is my code so far:
package Lab4EventHandling;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Frame3 extends JFrame implements ActionListener {

    private Container cPane;
    private JLabel tMsg, bMsg;

    private JCheckBox americano, espresso, doubleEspresso, latte;
    JCheckBox[] boxes = new JCheckBox[]{americano, espresso, doubleEspresso, latte};

    private JPanel checkPanel = new JPanel(new GridLayout(0,1));
    private Color cl;

    private double cost = 0;

    private final int WINDOW_WIDTH = 200;
    private final int WINDOW_HEIGHT = 200;
    private final int x = 550;
    private final int y = 400;

    public Frame3()
    {
        cPane = getContentPane();

        cl = new Color(150, 150, 250);
        cPane.setBackground(cl);
        this.setLayout(new BorderLayout(0,1));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocation(x,y);

        this.add(checkPanel, BorderLayout.CENTER);

        tMsg = new JLabel("Choose a coffee:" ,SwingConstants.CENTER);
        tMsg.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));

        this.add(tMsg, BorderLayout.PAGE_START);

        americano = new JCheckBox("Americano", false);
        checkPanel.add(americano);
        americano.addActionListener(this);

        espresso = new JCheckBox("Espresso", false);
        checkPanel.add(espresso);
        espresso.addActionListener(this);

        doubleEspresso = new JCheckBox("Double Espresso", false);
        checkPanel.add(doubleEspresso);
        doubleEspresso.addActionListener(this);

        latte = new JCheckBox("Latte", false);
        checkPanel.add(latte);
        latte.addActionListener(this);

        bMsg = new JLabel("Bill is ");
        bMsg.setHorizontalAlignment(SwingConstants.CENTER);
        bMsg.setBorder(BorderFactory.createEmptyBorder(4,4,4,4));
        this.add(bMsg, BorderLayout.SOUTH);

        this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        this.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {

        Double[] array = {3.75, 4.00, 4.50, 3.50};

        for (JCheckBox box : boxes) {

        if(americano.isSelected())
        {
            cost += 3.75;
            String r = String.valueOf(cost);
            bMsg.setText(r);
        }

        if(espresso.isSelected())
        {
            cost += 4.00;
            String r = String.valueOf(cost);
            bMsg.setText(r);
        }

        else if(doubleEspresso.isSelected())
        {
            cost = 4.50;
            String r = String.valueOf(cost);
            bMsg.setText(r);
        }

        else  if(latte.isSelected())
        {
            cost = 3.50;
            String r = String.valueOf(cost);
            bMsg.setText(r);
        }
    }

}

public class Frame3Test{

    public static void main(String [] args)
    {
        Frame3 f = new Frame3();
        f.setVisible(true);

    }
}

A: Your first problem (which you may or may not have noticed) is your array of JCheckBoxes only contains null elements:
// check boxes are null here
private JCheckBox americano, espresso, doubleEspresso, latte;

// array created with only null elements
JCheckBox[] boxes = new JCheckBox[]{americano, espresso, doubleEspresso, latte};

So you need to create the array after instantiating the actual check boxes.
...

americano = new JCheckBox("Americano", false);
checkPanel.add(americano);
americano.addActionListener(this);

espresso = new JCheckBox("Espresso", false);
checkPanel.add(espresso);
espresso.addActionListener(this);

doubleEspresso = new JCheckBox("Double Espresso", false);
checkPanel.add(doubleEspresso);
doubleEspresso.addActionListener(this);

latte = new JCheckBox("Latte", false);
checkPanel.add(latte);

boxes = new JCheckBox[] {
    americano, espresso, doubleEspresso, latte
};

Then the assignment is suggesting to use arrays because you can create another parallel array of prices (which you did). But since you need these prices in parallel you cannot use a for each loop. You need the index. Then you need to recalculate the entire cost every time anything is selected or deselected.
final double[] prices = {
    3.75, 4.00, 4.50, 3.50
};

...

double total = 0.0;

for(int i = 0; i < boxes.length; i++) {
    if(boxes[i].isSelected()) {
        total += prices[i];
    }
}

There's two other notes that seem to be outside the scope of the assignment:

*

*You should always make a class for this kind of association.

*You should never use double for money. Use BigDecimal or something like it.

Using a class makes logic simpler and not using double makes the calculation not incur error for this decimal addition.
class PricePair {
    JCheckBox jCheckBox;
    BigDecimal price;
}

BigDecimal total = new BigDecimal("0.00");

for(PricePair option : options) {
    if(option.jCheckBox.isSelected()) {
        total = total.add(option.price);
    }
}

A: First of all, you're not handling all the checkboxes the same way. For the first two choices, you add the price to the cost:
cost += 3.75;

whereas for the last two choices, you replace the cost:
cost = 4.50;

The first way is the correct way.
Second, there's no reason to have the cost as a field. You should recompute the cost, and it should always start with 0, every time a checkbox selection changes. So cost should be a local variable of the actionPerformed() method.
Third, there's no reason to change the label value before you know the final cost. So the lines
String r = String.valueOf(cost);
bMsg.setText(r);

should only be there once, at the end of the actionPerformed() method, when the final cost is known.
Finally, you want to use it us an array instead of handling each checkbos separately. It's quite easy, you just need to loop over the checkboxes:
double prices = {3.75, 4.00, 4.50, 3.50};
double cost = 0.0;
for (int i = 0; i < boxes.length; i++) {
    if (boxes[i].isSelected()) {
        double price = prices[i];
        cost += price;
    }
}
// now display the cost in the label

A: Although both answers posted here are very helpful I'm adding this one because IMHO arrays are the less Object Oriented thing ever. You can achieve a more robust and OO solution following this hints:

*

*Use
putClientProperty()
method inherited from
JComponent
to hold the prices in the check boxes.

*Implement an ActionListener to  add/substract the check box price to the total depending on the check box state. Use getClientProperty() method to retrieve the value stored in the check box.

See the example below:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Demo {

    BigDecimal total = new BigDecimal(BigInteger.ZERO);

    private void createAndShowGUI() {

        final JLabel totalLabel = new JLabel("Total: ");

        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JCheckBox checkBox = (JCheckBox)e.getSource();
                BigDecimal value = (BigDecimal)checkBox.getClientProperty("price");
                total = checkBox.isSelected() ? total.add(value) : total.subtract(value);
                StringBuilder sb = new StringBuilder("Total: ").append(total);
                totalLabel.setText(sb.toString());
            }
        };

        JCheckBox americano = new JCheckBox("Americano");
        americano.addActionListener(actionListener);
        americano.putClientProperty("price", new BigDecimal("3.75"));

        JCheckBox espresso = new JCheckBox("Espresso");
        espresso.addActionListener(actionListener);
        espresso.putClientProperty("price", new BigDecimal("4.00"));

        JCheckBox doubleEspresso = new JCheckBox("Double Espresso");
        doubleEspresso.addActionListener(actionListener);
        doubleEspresso.putClientProperty("price", new BigDecimal("4.50"));

        JCheckBox latte = new JCheckBox("Latte");
        latte.addActionListener(actionListener);
        latte.putClientProperty("price", new BigDecimal("3.50"));

        JPanel content = new JPanel();
        content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
        content.add(americano);
        content.add(espresso);
        content.add(doubleEspresso);
        content.add(latte);
        content.add(totalLabel);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Demo().createAndShowGUI();
            }
        });
    }
}

This way you can forget about mapping every check box with a value using arrays or maps. If you need to add a new sort of coffee you should simply add 4 lines like this:
JCheckBox newCoffee = new JCheckBox("New Coffee");
newCoffee.addActionListener(actionListener);
newCoffee.putClientProperty("price", new BigDecimal("4.00"));

content.add(newCoffee);