问:
Place imageview next to textview - (image view get repeated) CHAT UI
I would like to place imageview next to textview.

Here is my XML:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    >
    <RelativeLayout
        android:id="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
    <TextView
        android:id="@+id/leftText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_margin="10dp"
        android:background="@drawable/rounded_corner"
        android:elevation="2dp"
        android:fontFamily="@font/maven_pro_black"
        android:padding="16dp"
        android:layout_marginTop="10dp"
        android:layout_weight="6"
        android:text="Hello this is me!!"
        android:textSize="14sp"
        android:textColor="#212121"
        />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/leftText"
            android:layout_weight="3"
            android:src="@drawable/user_2"
            android:layout_toRightOf="@+id/leftText"/>

     </RelativeLayout>

   <RelativeLayout
        android:layout_below="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/relativeLayout">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toStartOf="@+id/rightText"
            android:layout_weight="3"
            android:src="@drawable/user_1" />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="6"
            android:background="@drawable/rounded_corner1"
            android:elevation="2dp"
            android:fontFamily="@font/maven_pro_black"
            android:padding="16dp"
            android:text="Hi!! How are you!!"
            android:textColor="#fff"
            android:textSize="16sp" />

    </RelativeLayout>
</RelativeLayout>```
</div>
</div>
</p>

<p>This is how it looks like in real world:</p>

<p><img src="https://i.stack.imgur.com/uXGFm.png" alt="In the picture below you can see the repeated images"></p>

<p>p.s. I tried & and not working: </p>

<p>android:layout_alignParentRight="true"</p>

<p>android:layout_toLeftOf="@+id/BLABLA"
and even </p>

<p>android:drawableLeft="@drawable/your_image_name"  </p>

<p>it was good try but not what I want.  HOW CAN I DISABLE THIS REPATABLE IMAGES AS YOU SEE IN SCREENSHOT? Thanks.</p>

<p>EDIT added my massage activity:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>adapter = new FirebaseRecyclerAdapter<ChatMessage, chat_rec>(ChatMessage.class,R.layout.msglist,chat_rec.class,ref.child("chat")) {
            @Override
            protected void populateViewHolder(chat_rec viewHolder, ChatMessage model, int position) {

                if (model.getMsgUser().equals("user")) {

                    viewHolder.rightText.setText(model.getMsgText());

                    viewHolder.rightText.setVisibility(View.VISIBLE);
                    viewHolder.leftText.setVisibility(View.GONE);

                }
                else {
                    viewHolder.leftText.setText(model.getMsgText());

                    viewHolder.rightText.setVisibility(View.GONE);
                    viewHolder.leftText.setVisibility(View.VISIBLE);

                }
            }
        };</code>```

答:
Here is my answer:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    >
    <RelativeLayout
        android:id="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        >
    <TextView
        android:id="@+id/leftText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/rounded_corner"
        android:elevation="2dp"
        android:fontFamily="@font/maven_pro_black"
        android:padding="16dp"
        android:layout_marginTop="10dp"
        android:layout_weight="6"
        android:text="Hello this is me!!"
        android:textSize="14sp"
        android:textColor="#212121"
        />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/leftText"
            android:layout_weight="3"
            android:src="@drawable/user_2"
            android:layout_toRightOf="@+id/leftText"/>

     </RelativeLayout>

   <RelativeLayout
        android:layout_below="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:id="@+id/relativeLayout">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_weight="3"
            android:src="@drawable/user_1" />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="6"
            android:background="@drawable/rounded_corner1"
            android:layout_toEndOf="@+id/imageView3"
            android:elevation="2dp"
            android:fontFamily="@font/maven_pro_black"
            android:padding="16dp"
            android:text="Hi!! How are you!!"
            android:textColor="#fff"
            android:textSize="16sp" />

    </RelativeLayout>
</RelativeLayout>```

There is no attribute orientation for a RelativeLayout. And I've just moved your attribute alignParent from TextView to RelativeLayout (parent of TextView)

Body:
I would like to place imageview next to textview.

Here is my XML:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    >
    <RelativeLayout
        android:id="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
    <TextView
        android:id="@+id/leftText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_margin="10dp"
        android:background="@drawable/rounded_corner"
        android:elevation="2dp"
        android:fontFamily="@font/maven_pro_black"
        android:padding="16dp"
        android:layout_marginTop="10dp"
        android:layout_weight="6"
        android:text="Hello this is me!!"
        android:textSize="14sp"
        android:textColor="#212121"
        />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/leftText"
            android:layout_weight="3"
            android:src="@drawable/user_2"
            android:layout_toRightOf="@+id/leftText"/>

     </RelativeLayout>

   <RelativeLayout
        android:layout_below="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/relativeLayout">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toStartOf="@+id/rightText"
            android:layout_weight="3"
            android:src="@drawable/user_1" />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="6"
            android:background="@drawable/rounded_corner1"
            android:elevation="2dp"
            android:fontFamily="@font/maven_pro_black"
            android:padding="16dp"
            android:text="Hi!! How are you!!"
            android:textColor="#fff"
            android:textSize="16sp" />

    </RelativeLayout>
</RelativeLayout>

This is how it looks like in real world:

p.s. I tried & and not working:

android:layout_alignParentRight="true"

android:layout_toLeftOf="@+id/BLABLA"
and even

android:drawableLeft="@drawable/your_image_name"

it was good try but not what I want.  HOW CAN I DISABLE THIS REPATABLE IMAGES AS YOU SEE IN SCREENSHOT? Thanks.

EDIT added my massage activity:

adapter = new FirebaseRecyclerAdapter<ChatMessage, chat_rec>(ChatMessage.class,R.layout.msglist,chat_rec.class,ref.child("chat")) {
            @Override
            protected void populateViewHolder(chat_rec viewHolder, ChatMessage model, int position) {

                if (model.getMsgUser().equals("user")) {

                    viewHolder.rightText.setText(model.getMsgText());

                    viewHolder.rightText.setVisibility(View.VISIBLE);
                    viewHolder.leftText.setVisibility(View.GONE);

                }
                else {
                    viewHolder.leftText.setText(model.getMsgText());

                    viewHolder.rightText.setVisibility(View.GONE);
                    viewHolder.leftText.setVisibility(View.VISIBLE);

                }
            }
        };

Body:
Here is my answer:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">
    >
    <RelativeLayout
        android:id="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        >
    <TextView
        android:id="@+id/leftText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/rounded_corner"
        android:elevation="2dp"
        android:fontFamily="@font/maven_pro_black"
        android:padding="16dp"
        android:layout_marginTop="10dp"
        android:layout_weight="6"
        android:text="Hello this is me!!"
        android:textSize="14sp"
        android:textColor="#212121"
        />
        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_toEndOf="@+id/leftText"
            android:layout_weight="3"
            android:src="@drawable/user_2"
            android:layout_toRightOf="@+id/leftText"/>

     </RelativeLayout>

   <RelativeLayout
        android:layout_below="@+id/layout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:id="@+id/relativeLayout">

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_weight="3"
            android:src="@drawable/user_1" />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:layout_marginTop="10dp"
            android:layout_weight="6"
            android:background="@drawable/rounded_corner1"
            android:layout_toEndOf="@+id/imageView3"
            android:elevation="2dp"
            android:fontFamily="@font/maven_pro_black"
            android:padding="16dp"
            android:text="Hi!! How are you!!"
            android:textColor="#fff"
            android:textSize="16sp" />

    </RelativeLayout>
</RelativeLayout>

There is no attribute orientation for a RelativeLayout. And I've just moved your attribute alignParent from TextView to RelativeLayout (parent of TextView)


来源: stackexchange

问:
Parameter "unevaluatedValue" cannot be null when saving *.rptproj project
If you have existing Report Server Project in your solution and you upgrade SQL Server Data Tools from version 14.0.61707.300 to 14.0.61709.290, you can get  following message when opening your existing *.rptproj files:

When you confirm upgrade by clicking on "Yes" button, solution could be successfully opened.
When you try to save modified project file, you can get SaveAs... dialog and following confirmation box:

But when you confirm replacing existing project file, you could get an error from Visual Studio:

答:
As I found at Community developer site, the problem is in the content of project files. To solve the situation you have to open existing *.rptproj file and manually add Platform into all build configurations, where it is missing.

After this change, Visual Studio detects that project files has been changed, so you can reload them and therefore you can save them.

ContentLicense: CC BY-SA 3.0


问:
Pointer in for loop in c program
I have the following structure:

```<code>struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
}
</code>```

Also I have the following function:

```<code>void SetRowToZero(Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}
</code>```

I wonder is there any performance slowdown during operation c < (m->numOfColumns)?
Is there any difference if i write function like this:

```<code>void SetRowToZero(Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}
</code>```

And in general, should i even care about performace on such a small scale?

答:
Maxim: Readability wins over performance.

In other words, computers are cheap, programmers are not.

There would be no difference in this case, since the loop conditional is a simple member access.

It could be a different matter if the loop conditional were a function though. But in that case you could run the loop backwards:

```<code>for (int c = <expensive function> - 1 c >= 0; --c)
{
    m->values[rowBegin + c] = 0;
}
</code>```

taking extra care if c was an unsigned type.

Title: Pointer in for loop in c program

Body:
I have the following structure:

struct Matrix
{
    int     numOfRows;
    int     numOfColumns;
    double* values;
    int*    permutationVector;
}

Also I have the following function:

void SetRowToZero(Matrix* m, int row)
{
    int rowBegin = row*(m->numOfColumns);
    for (int c = 0; c < (m->numOfColumns); c++)
    {
        m->values[rowBegin + c] = 0;
    }
}

I wonder is there any performance slowdown during operation c < (m->numOfColumns)?
Is there any difference if i write function like this:

void SetRowToZero(Matrix* m, int row)
{
    // Unpacking structure
    int numOfColumns = m->numOfColumns;
    double* values = m->values;

    int rowBegin = row*(m->numOfColumns);

    for (int c = 0; c < numOfColumns; c++)
    {
        values[rowBegin + c] = 0;
    }
}

And in general, should i even care about performace on such a small scale?

Body:
Maxim: Readability wins over performance.

In other words, computers are cheap, programmers are not.

There would be no difference in this case, since the loop conditional is a simple member access.

It could be a different matter if the loop conditional were a function though. But in that case you could run the loop backwards:

for (int c = <expensive function> - 1 c >= 0; --c)
{
    m->values[rowBegin + c] = 0;
}

taking extra care if c was an unsigned type.


问:
Deploying NodeJS, Puppeteer, and Angular on Google Cloud
I have the following setup:

Angular Front-end

MongoDb database

NodeJS/Express backend for API (+ puppeteer)

steps to deployment:

1. ng build -prod --> creates dist in /server

2. gcloud app deploy (Node.js + Express + Puppeteer + Dockerfile config*)

Because puppeteer is basically chrome; some libraries which aren't given to me, had to be uploaded. No problem, Docker to the rescue.

```<code>FROM node:8-slim

MAINTAINER Eric Bidelman <ebidel@>

RUN apt-get update && apt-get install -y wget --no-install-recommends \
    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
    && apt-get update \
    && apt-get install -y google-chrome-unstable \
      --no-install-recommends \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get purge --auto-remove -y curl \
    && rm -rf /src/*.deb

COPY . /app/
WORKDIR app

# Install deps for server.
RUN yarn

ARG CACHEBUST=1
RUN yarn add puppeteer

RUN groupadd -r pptruser && useradd -r -g pptruser -G audio,video pptruser \
    && mkdir -p /home/pptruser/Downloads \
    && chown -R pptruser:pptruser /home/pptruser \
    && chown -R pptruser:pptruser /app

USER pptruser

EXPOSE 8080

CMD ["yarn", "start"]
</code>```

this was taken from "try-puppeteer" github repo (https://github.com/ebidel/try-puppeteer)

Now the front-end is a private site, max 2 people on. How do I deploy Angular in a way where NodeJS doesn't have to solve it? Someone suggested "Google Cloud Bucket for $0.09/mo" which is cool.

Now the MongoDB instance is using google cloud compute engine. The database has a collection of 400 documents, which are at the size of 11kb each. Still on free resources here.

Functionality on the site:
For all (filtered) documents --> do action which requires us to load pupeteer().then( res.send(results))

This means that there is an average of 200 API requests from the frontend being handled in one blow. Even though NodeJS handles this well (one by one, synchronously) I was thinking about adding more "NodeJS-clones", and maybe I can handle simultaneous requests this way?

--This makes me wonder, if I have a NodeJS server for 300 clients at a time; how are the requests being handled? How don't I feel a "stoppage" between requests? Is there a queue that goes 1 by 1; or is this a limitation on AJAX?

In other words, how can I deploy this in a way that I can handle this waterfall of requests?

I've read up on "nginx" and "forever," but I'm more thinking along the lines of loading perhaps 10 instances of puppeteer (even from the same VM, like tabs or windows) where they can all work concurrently.

Here's where I'm stuck:
I understand I can deploy node clones; but how would I do it with google cloud where I can scale through dividing and conquoring. (200 requests at 2 requests "per tick" is twice as fast as 200 requests at 1 request "per tick".)

Am I doing this the wrong way? Making 200 requests to the backend instead of making one request with 200 objects -- another problem is the fear of timeout. Each request takes 40 seconds to complete.

App.yaml for "default" (be + fe deployed together):

```<code>runtime: custom
env: flex
service: default

automatic_scaling:
  max_num_instances: 1

resources:
  cpu: 1
  memory_gb: 1
  disk_size_gb: 10

skip_files:
- node_modules/
- test*.js
- ^(.*/)?.*\.md$
</code>```

Note: the exact app.yaml from the repo drove up my costs to $250/13 days. I need to find a cheaper way to execute this program.

答:
I'm not entirely sure how billing works on Google Cloud. If it's message throughput then running headless Chrome is going to be expensive no matter what since it sends requests through WebSockets (meaning at a cost, likely).

This is something that browserless is designed bottom-up for: headless browsers in the cloud. I've also open-sourced the underlying docker images here if you're interested.

I think the bottom line is that many/most providers out there just really aren't well setup to handle binaries executing like a browser. Either their way of deploying makes it tough, or that their methodologies behind billing make it expensive. Believe me when I say that your issue regarding billing and transparency aren't the first I have encountered.

Body:
I have the following setup:

Angular Front-end

MongoDb database

NodeJS/Express backend for API (+ puppeteer)

steps to deployment:

1. ng build -prod --> creates dist in /server

2. gcloud app deploy (Node.js + Express + Puppeteer + Dockerfile config*)

Because puppeteer is basically chrome; some libraries which aren't given to me, had to be uploaded. No problem, Docker to the rescue.

FROM node:8-slim

MAINTAINER Eric Bidelman <ebidel@>

RUN apt-get update && apt-get install -y wget --no-install-recommends \
    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
    && apt-get update \
    && apt-get install -y google-chrome-unstable \
      --no-install-recommends \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get purge --auto-remove -y curl \
    && rm -rf /src/*.deb

COPY . /app/
WORKDIR app

# Install deps for server.
RUN yarn

ARG CACHEBUST=1
RUN yarn add puppeteer

RUN groupadd -r pptruser && useradd -r -g pptruser -G audio,video pptruser \
    && mkdir -p /home/pptruser/Downloads \
    && chown -R pptruser:pptruser /home/pptruser \
    && chown -R pptruser:pptruser /app

USER pptruser

EXPOSE 8080

CMD ["yarn", "start"]

this was taken from "try-puppeteer" github repo (https://github.com/ebidel/try-puppeteer)

Now the front-end is a private site, max 2 people on. How do I deploy Angular in a way where NodeJS doesn't have to solve it? Someone suggested "Google Cloud Bucket for $0.09/mo" which is cool.

Now the MongoDB instance is using google cloud compute engine. The database has a collection of 400 documents, which are at the size of 11kb each. Still on free resources here.

Functionality on the site:
For all (filtered) documents --> do action which requires us to load pupeteer().then( res.send(results))

This means that there is an average of 200 API requests from the frontend being handled in one blow. Even though NodeJS handles this well (one by one, synchronously) I was thinking about adding more "NodeJS-clones", and maybe I can handle simultaneous requests this way?

--This makes me wonder, if I have a NodeJS server for 300 clients at a time; how are the requests being handled? How don't I feel a "stoppage" between requests? Is there a queue that goes 1 by 1; or is this a limitation on AJAX?

In other words, how can I deploy this in a way that I can handle this waterfall of requests?

I've read up on "nginx" and "forever," but I'm more thinking along the lines of loading perhaps 10 instances of puppeteer (even from the same VM, like tabs or windows) where they can all work concurrently.

Here's where I'm stuck:
I understand I can deploy node clones; but how would I do it with google cloud where I can scale through dividing and conquoring. (200 requests at 2 requests "per tick" is twice as fast as 200 requests at 1 request "per tick".)

Am I doing this the wrong way? Making 200 requests to the backend instead of making one request with 200 objects -- another problem is the fear of timeout. Each request takes 40 seconds to complete.

App.yaml for "default" (be + fe deployed together):

runtime: custom
env: flex
service: default

automatic_scaling:
  max_num_instances: 1

resources:
  cpu: 1
  memory_gb: 1
  disk_size_gb: 10

skip_files:
- node_modules/
- test*.js
- ^(.*/)?.*\.md$

Note: the exact app.yaml from the repo drove up my costs to $250/13 days. I need to find a cheaper way to execute this program.


问:
Android Twitter open source client
Where can I get the code of a Twitter client for Android? Possibly a recent one using the latest SDK. Thanks</p>

答:
I have coded a "very" simple Twitter client which implements Sign-in with twitter functionality.

maybe it doesn't give you exactly what you want/expect, but it might give you an idea.

http://thetechnib.blogspot.com/2011/01/android-sign-in-with-twitter.html

ContentLicense: CC BY-SA 2.5

Title: Android Twitter open source client


问:
Finding actual error out of data binding error
I am using data binding without any problems and it works good. But sometimes it frustrate me a lot by hiding the real problem by showing data binding error for no reason. Last time i made some changes in room database and mistakenly used wrong table name in ROOM DAO. At the time of building project android studio displayed multiple data binding error for no reason but not the real culprit ( wrong table name ). When i fixed that build worked. Now again i have made some changes and its giving me same data binding error, i am going through each file to find the real culprit but didn't see anything problematic. Any help to show all the error not just data binding error. This is very annoying Android Studio gradle build did not display all error at the bottom. </p>

答:
The Java compiler cuts off errors after 100 by default. With a standard Android-style project structure, add this to your root level build.gradle to raise the limit (to 500 in this case) - this raises the limit for all subprojects. You will still have to dig through all errors to find the real ones:

```<code>subprojects {
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << '-Xmaxerrs' << '500'
        }
    }
}
</code>```

Body:
The Java compiler cuts off errors after 100 by default. With a standard Android-style project structure, add this to your root level build.gradle to raise the limit (to 500 in this case) - this raises the limit for all subprojects. You will still have to dig through all errors to find the real ones:

subprojects {
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << '-Xmaxerrs' << '500'
        }
    }
}


问:
Chart JS onclick doesn't work
Can someone tell me what I'm doing wrong here, chart renders but when I click the bar I get error in console:

Uncaught TypeError: ComboChart.getElementsAtEvent is not a function
    at HTMLCanvasElement.document.getElementById.onclick.

I verified a couple of other posts on stack but don't seem to get an idea, I'm fairly new to javascript, please help me understand why this wouldn't work.

Thanks a lot!

    <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">

            <canvas id="ComboChart"></canvas>

```

答:
You will have to instantiate ComboChart in your code.

When you create the chart using new Chart(document.getElementById("ComboChart")), you will have to assign the result to a variable called ComboChart: var ComboChart = new Chart(document.getElementById("ComboChart"))

That way, you can reference it from the event handler.

    <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">

            <canvas id="ComboChart"></canvas>

```

Title: Chart JS onclick doesn't work

Body:
You will have to instantiate ComboChart in your code.

When you create the chart using new Chart(document.getElementById("ComboChart")), you will have to assign the result to a variable called ComboChart: var ComboChart = new Chart(document.getElementById("ComboChart"))

That way, you can reference it from the event handler.

<head>
    <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">

    <style>
        .wrapper {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;
            grid-auto-rows: minmax(100px, auto);
            grid-row-gap: 1em;
            grid-column-gap: 1em;
            justify-items: stretch;
            align-items: stretch;
            grid-auto-flow: column;
        }

        .wrapper>div {
            //background: #eee;
            padding: 1em;
        }

        .wrapper>div:nth-child(odd) {
            //background: #ddd;
        }

        .ComboChart {
            /*justify-self:end;*/
            grid-column: 1/9;
            grid-row: 1/5;
        }

        .container {
            /*align-self:end;*/
            grid-column: 7/9;
            grid-row: 2;
        }

        #myProgress {
            width: 100%;
            background-color: #ddd;
        }

        #myBar {
            width: N/A%;
            height: 30px;
            background-color: ;
            text-align: center;
            line-height: 30px;
            color: white;
        }

        .Top5 {
            /*align-self:end;*/
            grid-column: 1/3;
            grid-row: 3;
        }

    </style>
</head>

<body>

    <div class="wrapper">

        <div class="ComboChart">
            <canvas id="ComboChart"></canvas>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
            <script>
                console.log(Chart.defaults.global)

                var obj = JSON.parse('{"Account":{"JAN":{"Month":"JAN","MonthlyBudget":323342.6200000000,"MonthlyPosted":207198.1700000000,"MonthlyVariance":116144.4500000000,"YTDBudget":323342.6200000000,"YTDPosted":207198.1700000000,"YTDVariance":116144.4500000000,"AnnualBudget":3879559.340000000,"AnnualPosted":1935521.880000000,"AnnualVariance":1944037.460000000},"FEB":{"Month":"FEB","MonthlyBudget":303967.7900000000,"MonthlyPosted":333011.4200000000,"MonthlyVariance":-29043.63000000000,"YTDBudget":627310.4100000000,"YTDPosted":540092.5900000000,"YTDVariance":87217.82000000002,"AnnualBudget":3879559.340000000,"AnnualPosted":1935613.380000000,"AnnualVariance":1943945.960000000},"MAR":{"Month":"MAR","MonthlyBudget":325389.6400000000,"MonthlyPosted":223266.5100000000,"MonthlyVariance":102123.1300000000,"YTDBudget":952700.0500000000,"YTDPosted":761933.8800000000,"YTDVariance":190766.1700000000,"AnnualBudget":3879559.340000000,"AnnualPosted":1929419.560000000,"AnnualVariance":1950139.780000000},"APR":{"Month":"APR","MonthlyBudget":321608.2000000000,"MonthlyPosted":268868.0300000001,"MonthlyVariance":52740.17000000000,"YTDBudget":1274308.250000000,"YTDPosted":1032227.130000000,"YTDVariance":242081.1200000000,"AnnualBudget":3879559.340000000,"AnnualPosted":1935613.380000000,"AnnualVariance":1943945.960000000},"MAY":{"Month":"MAY","MonthlyBudget":328223.9600000000,"MonthlyPosted":267917.2600000000,"MonthlyVariance":60306.70000000000,"YTDBudget":1602532.210000000,"YTDPosted":1300144.390000000,"YTDVariance":302387.8200000000,"AnnualBudget":3879559.340000000,"AnnualPosted":1937114.100000000,"AnnualVariance":1942445.240000000},"JUN":{"Month":"JUN","MonthlyBudget":321608.2000000000,"MonthlyPosted":256167.9500000000,"MonthlyVariance":65440.25000000000,"YTDBudget":1924140.410000000,"YTDPosted":1555711.980000000,"YTDVariance":368428.4300000000,"AnnualBudget":3879559.340000000,"AnnualPosted":1935613.380000000,"AnnualVariance":1943945.960000000},"JUL":{"Month":"JUL","MonthlyBudget":328223.9600000000,"MonthlyPosted":268862.8300000000,"MonthlyVariance":59361.13000000000,"YTDBudget":2252364.370000000,"YTDPosted":1821052.940000000,"YTDVariance":431311.4300000000,"AnnualBudget":3879559.340000000,"AnnualPosted":1930920.280000000,"AnnualVariance":1948639.060000000},"AUG":{"Month":"AUG","MonthlyBudget":328223.9600000000,"MonthlyPosted":250416.9300000000,"MonthlyVariance":77807.03000000000,"YTDBudget":2580588.330000000,"YTDPosted":2075383.600000000,"YTDVariance":505204.7300000000,"AnnualBudget":3879559.340000000,"AnnualPosted":1936905.600000000,"AnnualVariance":1942653.740000000},"SEP":{"Month":"SEP","MonthlyBudget":313274.8700000000,"MonthlyPosted":-76566.64000000000,"MonthlyVariance":389841.5100000000,"YTDBudget":2827196.560000000,"YTDPosted":1961361.240000000,"YTDVariance":865835.3200000000,"AnnualBudget":3779559.380000000,"AnnualPosted":1900049.880000000,"AnnualVariance":1879509.500000000},"OCT":{"Month":"OCT","MonthlyBudget":0,"MonthlyPosted":-61311.36000000000,"MonthlyVariance":61311.36000000000,"YTDBudget":1764331.340000000,"YTDPosted":1231178.370000000,"YTDVariance":533152.9700000000,"AnnualBudget":2362354.180000000,"AnnualPosted":1231178.370000000,"AnnualVariance":1131175.810000000}}}');

                if (obj.Account.NOV != null) {
                    novMonth = obj.Account.NOV.Month;
                    novAnnualPosted = obj.Account.NOV.AnnualPosted;
                    novAnnualVariance = obj.Account.NOV.AnnualVariance;
                } else {
                    novMonth = 'NOV';
                    novAnnualPosted = 0;
                    novAnnualVariance = 0;
                }

                if (obj.Account.DEC != null) {
                    decMonth = obj.Account.DEC.Month;
                    decAnnualPosted = obj.Account.DEC.AnnualPosted;
                    decAnnualVariance = obj.Account.DEC.AnnualVariance;
                } else {
                    decMonth = 'DEC';
                    decAnnualPosted = 0;
                    decAnnualVariance = 0;
                }

                var comma = ",";
                var month = novMonth.concat(decMonth);

                var randomColorFactor = function() {
                    return Math.round(Math.random() * 255);
                };
                var randomColor = function(opacity) {
                    return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
                };

                var ComboChart = new Chart(document.getElementById("ComboChart"), {
                    type: 'bar',
                    data: {
                        labels: [obj.Account.JAN.Month, obj.Account.FEB.Month, obj.Account.MAR.Month, obj.Account.APR.Month, obj.Account.MAY.Month, obj.Account.JUN.Month, obj.Account.JUL.Month, obj.Account.AUG.Month, obj.Account.SEP.Month, obj.Account.OCT.Month, month],
                        datasets: [{
                                label: "Annual Posted",
                                type: "bar",
                                borderColor: 'rgb(115, 115, 115)',
                                backgroundColor: 'rgb(115, 115, 115)',
                                data: [obj.Account.JAN.AnnualPosted,
                                    obj.Account.FEB.AnnualPosted,
                                    obj.Account.MAR.AnnualPosted,
                                    obj.Account.APR.AnnualPosted,
                                    obj.Account.MAY.AnnualPosted,
                                    obj.Account.JUN.AnnualPosted,
                                    obj.Account.JUL.AnnualPosted,
                                    obj.Account.AUG.AnnualPosted,
                                    obj.Account.SEP.AnnualPosted,
                                    obj.Account.OCT.AnnualPosted,
                                    novAnnualPosted,
                                    decAnnualPosted
                                ],
                                fill: false
                            },
                            {
                                label: "Annual Variance",
                                type: "bar",
                                borderColor: 'rgb(210, 11, 11)',
                                backgroundColor: 'rgb(210, 11, 11)',
                                data: [obj.Account.JAN.AnnualVariance,
                                    obj.Account.FEB.AnnualVariance,
                                    obj.Account.MAR.AnnualVariance,
                                    obj.Account.APR.AnnualVariance,
                                    obj.Account.MAY.AnnualVariance,
                                    obj.Account.JUN.AnnualVariance,
                                    obj.Account.JUL.AnnualVariance,
                                    obj.Account.AUG.AnnualVariance,
                                    obj.Account.SEP.AnnualVariance,
                                    obj.Account.OCT.AnnualVariance,
                                    novAnnualVariance,
                                    decAnnualVariance
                                ],
                                fill: false
                            }
                        ]
                    },

                    options: {
                        title: {
                            display: true,
                            text: 'YTD Budget vs Posted',
                            position: 'right'
                        },
                        legend: {
                            display: true,
                            position: 'bottom'
                        },
                        maintainAspectRatio: false,
                        responsive: true,
                        responsiveAnimationDuration: 1500,
                        scales: {
                            xAxes: [{
                                gridLines: {
                                    display: false
                                }
                            }],
                            yAxes: [{
                                gridLines: {
                                    display: false
                                },
                                ticks: {
                                    beginAtZero: true,
                                    callback: function(value, index, values) {
                                        if (parseInt(value) >= 1000) {
                                            return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                                        } else {
                                            return '$' + value;
                                        }
                                    }
                                }
                            }]
                        },
                    }

                });

                document.getElementById("ComboChart").onclick = function(evt) {
                    var activePoints = ComboChart.getElementsAtEvent(evt);
                    var firstPoint = activePoints[0];
                    var label = ComboChart.data.labels[firstPoint._index];
                    var value = ComboChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
                    if (firstPoint !== undefined)
                        alert(label + ": " + value);

                };

            </script>
        </div>
    </div>
</body>

<body>


问:
How do I implement Disqus in ASP.NET MVC?
I'm in the middle of specifying the build/buy trade-offs for a public website and have hit a rather interesting avenue.

Background

Part of the design of the website is to incorporate comments against a set of different 'items' which obviously have their own IDss. (i.e. /recipes/23 or equipment/16 etc, etc).

Initially, i had specified a comments system with tags. However, the project sponsor has come back and asked if it would be easy to incorporate Disqus into the mix. I've used this before with Joomla (never in .NET) and think that it'll be a great idea as the comments are automatically distrubuted via the usual social network mediums by default.

Question

Is it fairly painless to set up an implementation of Disqus on ASP.NET MVC that works seamlessly?  Are there tutorials or examples of a working Disqus solution in ASP.NET MVC? I've seen this example and have read the documentation so far.

答:
I'm electing to use the async JavaScript load approach (as opposed to using the fullblown API methods). here's how simple it is using this in ASPNET MVC (It also works for ASP.NET):

From the documentation:

```<code><!-- add the div to receive the comments via ajax -->
<div id="disqus_thread"></div>

<!-- the required javascript link to disqus -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
    var disqus_shortname = 'mydisqusname';

    // Question pour XWiki : ici il faut que je configure un identifier
    // c'est comme un sujet de Mail. Il faudrait que je mette par exemple
    // l'url de la page XWiki afin que les commentaires soient regroupes

    // ensemble par article. Bref est ce que vous pouvez me mettre un ID ?

    var disqus_identifier = 'comments-league-<%= Html.Encode(Model.ID) %>';
    var disqus_url = '<%= HttpContext.Current.Request.Url %>';
    // using disqus_developer = 1 helps to debug to localhost etc..
    var disqus_developer = 1;

    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';

        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
</code>```

That's all there is to it.

Body:
I'm electing to use the async JavaScript load approach (as opposed to using the fullblown API methods). here's how simple it is using this in ASPNET MVC (It also works for ASP.NET):

From the documentation:

<!-- add the div to receive the comments via ajax -->
<div id="disqus_thread"></div>

<!-- the required javascript link to disqus -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
    var disqus_shortname = 'mydisqusname';

    // Question pour XWiki : ici il faut que je configure un identifier
    // c'est comme un sujet de Mail. Il faudrait que je mette par exemple
    // l'url de la page XWiki afin que les commentaires soient regroupes

    // ensemble par article. Bref est ce que vous pouvez me mettre un ID ?

    var disqus_identifier = 'comments-league-<%= Html.Encode(Model.ID) %>';
    var disqus_url = '<%= HttpContext.Current.Request.Url %>';
    // using disqus_developer = 1 helps to debug to localhost etc..
    var disqus_developer = 1;

    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';

        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>

That's all there is to it.


问:
"the label [5] is not in the [index]" while duplicating rows
I'm trying to reformat a CSV to turn each month column into a separate row per record (essentially rotating it), i.e.,:

Into:

To do this, I thought the best way would be to:

loop through each row, loop through for each month column (Jan-17, Feb-17, etc...), then duplicate the row.

Then insert the month and totals into Date and Totals columns.

Then remove that record that was duplicated and start where the index left off (I.e., after 5 record loops for each date, the index to start on would be 5).

Then when all rows are duplicated, remove, the month columns (Jan-17, Feb-17, etc...)

It does it for the first data row (i.e., brand1), but after the first outer loop completes, it breaks with:

the label [5] is not in the [index]

```<code>df['date'] = ''
df['totals'] = 0
months = ['Jan-17', 'Feb-17', 'Mar-17', 'Apr-17', 'May-17']

dropRowIndex = 0
nextDuplicateRowStartIndex = 0
totalRows = df.shape[0]

for i in range(0, totalRows):
    print('--------------')
    print(df)
    for col in df:
        if col in months:
            # Insert a row above 0th index with 0th row's values
            # Duplicate the row at this index for each month
            # Then move on to the next "row", which would be the latest index count
            df.loc[nextDuplicateRowStartIndex-1] = df.loc[nextDuplicateRowStartIndex].values
            df.loc[nextDuplicateRowStartIndex-1, 'date'] = col
            df.loc[nextDuplicateRowStartIndex-1, 'totals'] = df.loc[nextDuplicateRowStartIndex-1][col]

            df.index = df.index + 1
            df = df.sort_index()
            dropRowIndex += 1

    # Drop duplicated row by index
    df.drop(dropRowIndex, inplace=True)
    nextDuplicateRowStartIndex = dropRowIndex

# Remove months columns
for col in df:
    if col in months:
        df = df.drop(col, 1)
</code>```

Terminal output:

```<code>-------------- INITIAL DATA FRAME:
    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17 date  totals
0  brand1     222     333     444     555     666            0
1  brand2    7777    8888    9999    1010    1111            0
2  brand3   12121   13131   14141   15151   16161            0
-------------- DATA FRAME AFTER FIRST OUTER LOOP (ROW) ITERATION:
    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17    date  totals
0  brand1     222     333     444     555     666  May-17     666
1  brand1     222     333     444     555     666  Apr-17     555
2  brand1     222     333     444     555     666  Mar-17     444
3  brand1     222     333     444     555     666  Feb-17     333
4  brand1     222     333     444     555     666  Jan-17     222
6  brand2    7777    8888    9999    1010    1111               0
7  brand3   12121   13131   14141   15151   16161               0
Traceback (most recent call last):
  File "/Users/danielturcotte/Sites/project/env/lib/python3.6/site-packages/pandas/core/indexing.py", line 1506, in _has_valid_type
    error()
  File "/Users/danielturcotte/Sites/project/env/lib/python3.6/site-packages/pandas/core/indexing.py", line 1501, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [5] is not in the [index]'
</code>```

ERROR

KeyError: 'the label [5] is not in the [index]'

One thought I had was because I'm using .loc[index], where index is an integer, perhaps .loc doesn't work with integers, but .iloc[] does. If I do

```<code>df.iloc[nextDuplicateRowStartIndex-1] = df.iloc[nextDuplicateRowStartIndex].values
</code>```

I get ERROR:

ValueError: labels [10] not contained in axis

And the terminal output produces NaNs:

```<code>    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17    date  totals
0     NaN     NaN     NaN     NaN     NaN     NaN  May-17     NaN
1     NaN     NaN     NaN     NaN     NaN     NaN  Apr-17     NaN
2     NaN     NaN     NaN     NaN     NaN     NaN  Mar-17     NaN
3     NaN     NaN     NaN     NaN     NaN     NaN  Feb-17     NaN
4     NaN     NaN     NaN     NaN     NaN     NaN  Jan-17     NaN
6  brand2  7777.0  8888.0  9999.0  1010.0  1111.0             0.0
7     NaN     NaN     NaN     NaN     NaN     NaN  Apr-17     NaN
</code>```

Though I'm not convinced this is the issue as both print(df.iloc[0]) and print(df.loc[0]) yield the same results (even though I'm accessing loc[0] with an integer).

Doing melt:

答:
By using asongtoruin's data and stack

```<code>df.set_index('brand').stack().reset_index(name='Total').rename(columns={'level_1':'Date'})
Out[1043]:
    brand    Date  Total
0  brand1  Feb-17    333
1  brand1  Jan-17     22
2  brand2  Feb-17    424
3  brand2  Jan-17    232
4  brand3  Feb-17    999
5  brand3  Jan-17    324
</code>```

Body:
I'm trying to reformat a CSV to turn each month column into a separate row per record (essentially rotating it), i.e.,:

Into:

To do this, I thought the best way would be to:

loop through each row, loop through for each month column (Jan-17, Feb-17, etc...), then duplicate the row.

Then insert the month and totals into Date and Totals columns.

Then remove that record that was duplicated and start where the index left off (I.e., after 5 record loops for each date, the index to start on would be 5).

Then when all rows are duplicated, remove, the month columns (Jan-17, Feb-17, etc...)

It does it for the first data row (i.e., brand1), but after the first outer loop completes, it breaks with:

the label [5] is not in the [index]

df['date'] = ''
df['totals'] = 0
months = ['Jan-17', 'Feb-17', 'Mar-17', 'Apr-17', 'May-17']

dropRowIndex = 0
nextDuplicateRowStartIndex = 0
totalRows = df.shape[0]

for i in range(0, totalRows):
    print('--------------')
    print(df)
    for col in df:
        if col in months:
            # Insert a row above 0th index with 0th row's values
            # Duplicate the row at this index for each month
            # Then move on to the next "row", which would be the latest index count
            df.loc[nextDuplicateRowStartIndex-1] = df.loc[nextDuplicateRowStartIndex].values
            df.loc[nextDuplicateRowStartIndex-1, 'date'] = col
            df.loc[nextDuplicateRowStartIndex-1, 'totals'] = df.loc[nextDuplicateRowStartIndex-1][col]

            df.index = df.index + 1
            df = df.sort_index()
            dropRowIndex += 1

    # Drop duplicated row by index
    df.drop(dropRowIndex, inplace=True)
    nextDuplicateRowStartIndex = dropRowIndex

# Remove months columns
for col in df:
    if col in months:
        df = df.drop(col, 1)

Terminal output:

-------------- INITIAL DATA FRAME:
    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17 date  totals
0  brand1     222     333     444     555     666            0
1  brand2    7777    8888    9999    1010    1111            0
2  brand3   12121   13131   14141   15151   16161            0
-------------- DATA FRAME AFTER FIRST OUTER LOOP (ROW) ITERATION:
    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17    date  totals
0  brand1     222     333     444     555     666  May-17     666
1  brand1     222     333     444     555     666  Apr-17     555
2  brand1     222     333     444     555     666  Mar-17     444
3  brand1     222     333     444     555     666  Feb-17     333
4  brand1     222     333     444     555     666  Jan-17     222
6  brand2    7777    8888    9999    1010    1111               0
7  brand3   12121   13131   14141   15151   16161               0
Traceback (most recent call last):
  File "/Users/danielturcotte/Sites/project/env/lib/python3.6/site-packages/pandas/core/indexing.py", line 1506, in _has_valid_type
    error()
  File "/Users/danielturcotte/Sites/project/env/lib/python3.6/site-packages/pandas/core/indexing.py", line 1501, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [5] is not in the [index]'

ERROR

KeyError: 'the label [5] is not in the [index]'

One thought I had was because I'm using .loc[index], where index is an integer, perhaps .loc doesn't work with integers, but .iloc[] does. If I do

df.iloc[nextDuplicateRowStartIndex-1] = df.iloc[nextDuplicateRowStartIndex].values

I get ERROR:

ValueError: labels [10] not contained in axis

And the terminal output produces NaNs:

    brand  Jan-17  Feb-17  Mar-17  Apr-17  May-17    date  totals
0     NaN     NaN     NaN     NaN     NaN     NaN  May-17     NaN
1     NaN     NaN     NaN     NaN     NaN     NaN  Apr-17     NaN
2     NaN     NaN     NaN     NaN     NaN     NaN  Mar-17     NaN
3     NaN     NaN     NaN     NaN     NaN     NaN  Feb-17     NaN
4     NaN     NaN     NaN     NaN     NaN     NaN  Jan-17     NaN
6  brand2  7777.0  8888.0  9999.0  1010.0  1111.0             0.0
7     NaN     NaN     NaN     NaN     NaN     NaN  Apr-17     NaN

Though I'm not convinced this is the issue as both print(df.iloc[0]) and print(df.loc[0]) yield the same results (even though I'm accessing loc[0] with an integer).

Doing melt:

Body:
By using asongtoruin's data and stack

df.set_index('brand').stack().reset_index(name='Total').rename(columns={'level_1':'Date'})
Out[1043]:
    brand    Date  Total
0  brand1  Feb-17    333
1  brand1  Jan-17     22
2  brand2  Feb-17    424
3  brand2  Jan-17    232
4  brand3  Feb-17    999
5  brand3  Jan-17    324


问:
Is it possible to reset a Jupyter Notebook
I have access to a Jupyter Notebook that was created as a learning tool for some code - so the idea is just to play around and see what changing different things does.

I played around, but now I want to reset everything back to how it was before I started editing it. As I can't see an easy way to do this, I'm guessing that I'm thinking of it all the wrong way.

Is it not possible to reset the book? If not, why not?

Thank you!

答:
Navigate to Help > Edit Keyboard Shortcuts in an open notebook. Find the option for clear all cells output

Add a shortcut such as Ctrl-C


问:
Mixlib::ShellOut::ShellCommandFailed
I am getting an error on installing the package using a recipe in Linux.

```<code>================================================================================[0m
    [31mError executing action `install` on resource 'package[libxslt]'[0m
    ================================================================================[0m

[0m    Mixlib::ShellOut::ShellCommandFailed[0m
    ------------------------------------[0m
    Expected process to exit with [0], but received '1'
[0m    ---- Begin output of /usr/bin/python /opt/chef/embedded/apps/chef/lib/chef/provider/package/yum-dump.py --options --installed-provides --yum-lock-timeout 30 ----
[0m    STDOUT: [option installonlypkgs] kernel kernel-bigmem installonlypkg(kernel-module) installonlypkg(vm) kernel-enterprise kernel-smp kernel-debug kernel-unsupported kernel-source kernel-devel kernel-PAE kernel-PAE-debug
[0m    STDERR: yum-dump Repository Error: failure: repodata/5c43262c2b560eb91f2874d3ef6e20536af2b9ec1421335130736b6d1e1a73a7-primary.sqlite.bz2 from pgdg93: [Errno 256] No more mirrors to try.
[0m    ---- End output of /usr/bin/python /opt/chef/embedded/apps/chef/lib/chef/provider/package/yum-dump.py --options --installed-provides --yum-lock-timeout 30 ----
[0m    Ran /usr/bin/python /opt/chef/embedded/apps/chef/lib/chef/provider/package/yum-dump.py --options --installed-provides --yum-lock-timeout 30 returned 1[0m
</code>```

I am using chef version 11.18.12

Can someone explain me the cause and solution?

答: As mentioned in comments [Errno 256] No more mirrors to try. is the real error from Yum, however Chef 11 is quite old and unsupported (and unsafe) so I recommend you try with something newer if possible. Barring that, it looks like your config for the pgdg93 repo may need to be updated or the repo may be having server issues.

Title: Mixlib::ShellOut::ShellCommandFailed

Body:
I am getting an error on installing the package using a recipe in Linux.

================================================================================[0m
    [31mError executing action `install` on resource 'package[libxslt]'[0m
    ================================================================================[0m

[0m    Mixlib::ShellOut::ShellCommandFailed[0m
    ------------------------------------[0m
    Expected process to exit with [0], but received '1'
[0m    ---- Begin output of /usr/bin/python /opt/chef/embedded/apps/chef/lib/chef/provider/package/yum-dump.py --options --installed-provides --yum-lock-timeout 30 ----
[0m    STDOUT: [option installonlypkgs] kernel kernel-bigmem installonlypkg(kernel-module) installonlypkg(vm) kernel-enterprise kernel-smp kernel-debug kernel-unsupported kernel-source kernel-devel kernel-PAE kernel-PAE-debug
[0m    STDERR: yum-dump Repository Error: failure: repodata/5c43262c2b560eb91f2874d3ef6e20536af2b9ec1421335130736b6d1e1a73a7-primary.sqlite.bz2 from pgdg93: [Errno 256] No more mirrors to try.
[0m    ---- End output of /usr/bin/python /opt/chef/embedded/apps/chef/lib/chef/provider/package/yum-dump.py --options --installed-provides --yum-lock-timeout 30 ----
[0m    Ran /usr/bin/python /opt/chef/embedded/apps/chef/lib/chef/provider/package/yum-dump.py --options --installed-provides --yum-lock-timeout 30 returned 1[0m

I am using chef version 11.18.12

Can someone explain me the cause and solution?


问:
Since QuickSight can directly query S3, when would we need to use Athena as data source for QuickSight?
May be I am missing something but I am not able to  understand what benefit I will get if I connect Athena with QuickSight instead of connecting QuickSight directly with S3. Please help me to understand this.</p>

答:
Amazon S3 is an object storage built to store and retrieve any amount of data. Basically, it has some raw data or unstructured data (in certain file format  .csv or .tsv).

Amazon Athena uses a managed Data Catalog to store information and
  schemas about the databases and tables that you create for your data
  stored in Amazon S3. So, Athena knows about the data and its structure
  (i.e. some schema) in S3.

Also, QuickSight can directly connect to the Athena database and query the data for analysis. When you connect to Athena database, you are most likely to handle structured or semi-structured data.

Amazon S3 Manifest Files are not required when the data source is Amazon Athena.

Some limitations while connecting to S3 directly:-

No file specified in the manifest can exceed 1 GB in size, the total
  size of the all the files specified can't exceed 10 GB, and the total
  number of files specified can't exceed 1000.

The above limitations are not available when you use create the Data Set Using Amazon Athena Data.

Another Feature when creating a Data Set Using Amazon Athena Data :-

You can directly analyze the data without loading or load into SPICE
  and analyze the data.

Conclusion:-

If you have not done anything on your S3 files, you can just ahead and use QuickSight using S3 as data set.

In case, if you have loaded the S3 data into Athena, then you can use Athena as data set for QuickSight.

By using the Athena or any other data source, you will get few benefits and can overcome some limitation (i.e. file size) mentioned above.

ContentLicense: CC BY-SA 4.0


问:
Efficiency of structural recursion vs tail recursion
I want to know the difference between executing

```<code>factorial 0 = 0
factorial n = n * factorial (n-1)
</code>```

and

```<code>factorial 0 r = r
factorial n r = factorial (n-1) (r * n)
</code>```

Wich is more performant?

答:
I'm not sure either is. The first will evaluate n-1 in the pattern test for 0, but will produce a stack of multiplications that can't begin to execute until it reaches 0. The second will produce that same stack stored in the r argument. The advantage of the second, however, is that you can make the r argument strict and be purely tail recursive in constant space, because its multiplication order agrees with the call order.

We can interpret the first version as factorial n = foldr (*) 1 [n,n-1..1], and the second as factorial n = foldl (*) 1 [n,n-1..1]. Thus the difference in strictness for r is the same as between foldl and foldl'. But if the list is long and the operation can shortcut by not inspecting the second argument, the foldr version gets a noted advantage.

Body:
I want to know the difference between executing

factorial 0 = 0
factorial n = n * factorial (n-1)

and

factorial 0 r = r
factorial n r = factorial (n-1) (r * n)

Wich is more performant?


问:
Azure AD B2C exception when integrating with ADFS
I am trying to integrate B2C with my company's corporate ADFS. I am following Microsoft docs for guidance:
https://learn.microsoft.com/azure/active-directory-b2c/active-directory-b2c-custom-setup-adfs2016-idp

I have followed all the steps mentioned on docs plus the initial configuration, and added the certificate supplied by the ADFS.

When I try to test this by running the sign-in/sign-up policy in Azure AD B2C, I see the link to login to ADFS. Clicking on it, takes me to

I get following response:

```<code>https://login.microsoftonline.com/******.onmicrosoft.com?error=server_error&error_description=AADB2C%3a+An+exception+has+occured.%0d%0aCorrelation+ID%3a+7b15db4c-e91d-49ce-94ca-7c5525cc10f2%0d%0aTimestamp%3a+2017-11-17+09%3a47%3a34Z%0d%0a
</code>```

Is there a way to find out what has gone wrong?

答: Turn on logging via App Insights.  See this guide: Collecting Logs.</p>

Body:
I am trying to integrate B2C with my company's corporate ADFS. I am following Microsoft docs for guidance:
https://learn.microsoft.com/azure/active-directory-b2c/active-directory-b2c-custom-setup-adfs2016-idp

I have followed all the steps mentioned on docs plus the initial configuration, and added the certificate supplied by the ADFS.

When I try to test this by running the sign-in/sign-up policy in Azure AD B2C, I see the link to login to ADFS. Clicking on it, takes me to

I get following response:

https://login.microsoftonline.com/******.onmicrosoft.com?error=server_error&error_description=AADB2C%3a+An+exception+has+occured.%0d%0aCorrelation+ID%3a+7b15db4c-e91d-49ce-94ca-7c5525cc10f2%0d%0aTimestamp%3a+2017-11-17+09%3a47%3a34Z%0d%0a

Is there a way to find out what has gone wrong?


问:
AWK, printf format specifier %x has problems with negative values
It seems AWK has problems with the unsigned hex format specifier:

```<code>echo 0x80000000 | awk '{printf("0x%08x\n", $1)}'
</code>```

gives back: 0x7fffffff

Is this a known problem with awk?

Thanks!

答:
The problem is that awk only converts input parameters to numbers automatically if they are decimal. But this should work:

echo 0x80000000 | awk '{printf("0x%08x\n", strtonum($1))}'

It's all explained in here, in the strtonum section:
http://www.gnu.org/manual/gawk/html_node/String-Functions.html#String-Functions

Body:
It seems AWK has problems with the unsigned hex format specifier:

echo 0x80000000 | awk '{printf("0x%08x\n", $1)}'

gives back: 0x7fffffff

Is this a known problem with awk?

Thanks!


问:
Importing typescript module into angular component
I am trying to use a certain library in my component but I seem to be missing a step in including it properly

My component is as follows.  The library in question is geolib

```<code>import { Component, OnInit } from '@angular/core';
import { StationsService } from '../../../services/stations/stations.service';
import { Station } from '../../../classes/station.model';
import 'geolib';

@Component({
  selector: 'app-pollution',
 templateUrl: './pollution.component.html',
 styleUrls: ['./pollution.component.scss']
})
export class PollutionComponent implements OnInit {
private markers: Station[];

constructor(private stationsService: StationsService) { }

ngOnInit() {
    this.stationsService.GetAll().subscribe(
        res => {
            for (let i of res) {
                var t = geolib.computeDestinationPoint({ latitude: i.Lat, longitude: i.Long }, 1234, 90);
            }
            this.markers = res;
        }
    );
  }
}
</code>```

geloibs .d.ts file is as follows

```<code>declare namespace geolib {
.....
}
declare module "geolib" {
 export = geolib;
}
</code>```

The tooling doesn't complain and everything compiles but when I run it geolib is not defined.

答:
Use this syntax to import a module structured this way:</p>

```<code>import * as geolib from 'geolib';
</code>```

Body:
I am trying to use a certain library in my component but I seem to be missing a step in including it properly

My component is as follows.  The library in question is geolib

import { Component, OnInit } from '@angular/core';
import { StationsService } from '../../../services/stations/stations.service';
import { Station } from '../../../classes/station.model';
import 'geolib';

@Component({
  selector: 'app-pollution',
 templateUrl: './pollution.component.html',
 styleUrls: ['./pollution.component.scss']
})
export class PollutionComponent implements OnInit {
private markers: Station[];

constructor(private stationsService: StationsService) { }

ngOnInit() {
    this.stationsService.GetAll().subscribe(
        res => {
            for (let i of res) {
                var t = geolib.computeDestinationPoint({ latitude: i.Lat, longitude: i.Long }, 1234, 90);
            }
            this.markers = res;
        }
    );
  }
}

geloibs .d.ts file is as follows

declare namespace geolib {
.....
}
declare module "geolib" {
 export = geolib;
}

The tooling doesn't complain and everything compiles but when I run it geolib is not defined.

Body:
Use this syntax to import a module structured this way:

import * as geolib from 'geolib';


问:
Oracle SQL - Eliminate values that are not equal on a join
Here's how my tables look: Both tables have a composite primary key on all 3 columns. And the SecondaryId will not repeat from these two tables. This is obviously not enforced by a DB constraint but by business rules on the front-end.

```<code>Table1:
PrimaryID|SecondaryID|Email
1   9999    ABC@GMAIL.COM
1   9999    DEF@GMAIL.COM
2   8888    CCC@GMAIL.COM
3   7777    CBA@GMAIL.COM

Table2:
PrimaryID|SecondaryID|Email
1   1111    ABC@GMAIL.COM
2   2222    XYZ@GMAIL.COM
3   3333    CBA@GMAIL.COM
</code>```

I want the secondaryid in both tables returned, joining on the same primaryid where the emails are different on all occurrences of the primary id.

For PrimaryID = 1:
Table1 has two rows, table 2 has one row. But that one email from table2 matches with the one on table1 so I don't want that back. Here's my query but that doesn't eliminate the above duplicate which is what I need.

```<code> SELECT DISTINCT T1.SECONDARYID, T2.SECONDARYID
    FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.PRIMARYID = T2.PRIMARYID
    AND T1.EMAIL <> T2.EMAIL;
</code>```

Returns

```<code>9999    1111
8888    2222
</code>```

答:
So, you want to take all records from one table and find all such records from another table that the ID field is equal, but no record exists in the second table with an equal email.

I'd try something along these lines:

```<code>select one.*, another.*
from one, another
where
  one.id = another.id and
  not exists (
    select 1
    from another as another_again
    where
      another_again.id = one.id and
      another_again.email = one.email
  )
</code>```

This might be not strictly the fastest query (hopefully Oracle can come up with a nice query plan). It should be easy to understand, though.

Body:
Here's how my tables look: Both tables have a composite primary key on all 3 columns. And the SecondaryId will not repeat from these two tables. This is obviously not enforced by a DB constraint but by business rules on the front-end.

Table1:
PrimaryID|SecondaryID|Email
1   9999    ABC@GMAIL.COM
1   9999    DEF@GMAIL.COM
2   8888    CCC@GMAIL.COM
3   7777    CBA@GMAIL.COM

Table2:
PrimaryID|SecondaryID|Email
1   1111    ABC@GMAIL.COM
2   2222    XYZ@GMAIL.COM
3   3333    CBA@GMAIL.COM

I want the secondaryid in both tables returned, joining on the same primaryid where the emails are different on all occurrences of the primary id.

For PrimaryID = 1:
Table1 has two rows, table 2 has one row. But that one email from table2 matches with the one on table1 so I don't want that back. Here's my query but that doesn't eliminate the above duplicate which is what I need.

 SELECT DISTINCT T1.SECONDARYID, T2.SECONDARYID
    FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T1.PRIMARYID = T2.PRIMARYID
    AND T1.EMAIL <> T2.EMAIL;

Returns

9999    1111
8888    2222

Body:
So, you want to take all records from one table and find all such records from another table that the ID field is equal, but no record exists in the second table with an equal email.

I'd try something along these lines:

select one.*, another.*
from one, another
where
  one.id = another.id and
  not exists (
    select 1
    from another as another_again
    where
      another_again.id = one.id and
      another_again.email = one.email
  )

This might be not strictly the fastest query (hopefully Oracle can come up with a nice query plan). It should be easy to understand, though.


问:
Div over another div with overflow
I want to display some kind of tooltip on the left side of the long div(vertical).
And if I set the parend div css to overflow-y:auto; then the child div is not displayed. Here is a fiddle of the problem https://jsfiddle.net/wrwvc6Lc/2/
try to remove the overflow-y:auto; prop and everything is fine.
Is there a way to do so, as I need the overflow prop.

#infoBox {
  z-index: 1200;
  width:160px;
  height:90%;
  position: absolute;
  top: 10px;
  right: 10px;

   background-color:white;
    overflow-y:auto; /* REMOVE THIS */
    border:1px solid red
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="infoBox">
Lorem Ipsum is simply dummy text.
Lorem Ipsum is simply dummy text.
<div style="position:absolute; border:1px solid green; left:-90px; height:50px;width:100px;background-color:red">
Tooltip
</div>
</div></code>```

UPD: I want that tooltip to be relative to the content inside the main infoBox div (3-4 text block with tooltip), so placing that tooltip out of the infobox is not ok.

答:
The thing you're trying to do here is not possible (correct me if I'm wrong). Because overflow: auto; is required to set the scrollbars. But overflow also has an other property that every element inside the div with overflow: auto; can't go outside this element and will be cut off from this element which is intended.

Your concept can only work if you're not working with the overflow: auto; and you can't use scrollbars for this reason unfortunately.

Title: Div over another div with overflow

Body:
I want to display some kind of tooltip on the left side of the long div(vertical).
And if I set the parend div css to overflow-y:auto; then the child div is not displayed. Here is a fiddle of the problem https://jsfiddle.net/wrwvc6Lc/2/
try to remove the overflow-y:auto; prop and everything is fine.
Is there a way to do so, as I need the overflow prop.

#infoBox {
  z-index: 1200;
  width:160px;
  height:90%;
  position: absolute;
  top: 10px;
  right: 10px;

   background-color:white;
    overflow-y:auto; /* REMOVE THIS */
    border:1px solid red
    }

Lorem Ipsum is simply dummy text.
Lorem Ipsum is simply dummy text.

Tooltip

UPD: I want that tooltip to be relative to the content inside the main infoBox div (3-4 text block with tooltip), so placing that tooltip out of the infobox is not ok.


问:
Button not centering after moving it to bottom of div
I'm trying to create a form where the submit is always at the bottom and in the center.

I'm centering by using text-align: center in the parent div and moving it to the bottom with position: absolute and bottom: 20px, but it seems that after I do that it moves slightly off center - why is this case and how do I remedy this?

HTML:

```<code><div class='container'>
  <form>
    <p>
      <input name='group 1' type='radio' id='1' />
      <label for='1'>option 1</label>
    </p>
    <p>
      <input name='group 1' type='radio' id='2' />
      <label for='2'>option 2</label>
    </p>
    <p>
      <input name='group 2' type='radio' id='3' />
      <label for='3'>option 1</label>
    </p>
    <p>
      <input name='group 1' type='radio' id='4' />
      <label for='4'>option 1</label>
    </p>
    <button type='submit'>
      Submit
    </button>
  </form>
</div>
</code>```

CSS:

```<code>.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
}

button {
  position: absolute;
  bottom: 20px;
}
</code>```

Demo: https://jsfiddle.net/f9ktLn9o/3/

答:
Where you've pulled it out of the stack using position: absolute; it'll now be centered to the left of the button. If you translate it 50% of the width of the button to the left, it should fix the issue.

```<code>transform: translateX(-50%);
</code>```

https://jsfiddle.net/f9ktLn9o/4/

Body:
I'm trying to create a form where the submit is always at the bottom and in the center.

I'm centering by using text-align: center in the parent div and moving it to the bottom with position: absolute and bottom: 20px, but it seems that after I do that it moves slightly off center - why is this case and how do I remedy this?

HTML:

  <form>

      <input name='group 1' type='radio' id='1' />
      option 1

      <input name='group 1' type='radio' id='2' />
      option 2

      <input name='group 2' type='radio' id='3' />
      option 1

      <input name='group 1' type='radio' id='4' />
      option 1

    <button type='submit'>
      Submit
    </button>
  </form>

CSS:

.container {
  width: 400px;
  height: 400px;
  border: 2px solid red;
  text-align: center;
}

button {
  position: absolute;
  bottom: 20px;
}

Demo: https://jsfiddle.net/f9ktLn9o/3/

Body:
Where you've pulled it out of the stack using position: absolute; it'll now be centered to the left of the button. If you translate it 50% of the width of the button to the left, it should fix the issue.

transform: translateX(-50%);

https://jsfiddle.net/f9ktLn9o/4/


问:
how create msdeploy package without absolute path in content folder?
I have a problem related to creating msdeploy package for deploying to azure web app.
I run msdeploy -verb:sync -source:contentPath="C:\inetpub\wwwroot\<SiteName>" -dest:package=test.zip And after investigating package i found that it contains a full hierarchy of folders eg: \Content\C_C\inetpub\wwwroot\<SiteName>\ and when i am trying to deploy this package to azure a have an exception because i don't have such permissions.
Question: how to remove path from content folder so my archive will looks like \Content\<SiteName>?

答:
After a day of investigation i figure out how to do this:

$msDeployPackageCommand = "$MsDeployExePath
 -source:iisApp=$PathToApplication
 -dest:package=$ZipCreationPath
 -verb:sync
 -enableLink:contentLibExtension
 -replace:match=$ReplacePathToApplication,replace=$replaceWith
 -retryAttempts:2
 -disablerule:BackupRule
 -declareParam:name='PackageManagementService',kind='ProviderPath',scope='IisApp',match=$ReplacePathToApplication,defaultValue=$replaceWith";

This works fine.


问:
Change Magento Template
I have been asked by a customer to edit there ecommerce website, the cms system they use is Magento, how would i go about changing the category page html coding as i need to change a h2 to a h1. Were is it stored on the FTP so i can download edit html and then reupload. i have tried to go to /public_html/app/design/frontend/base/mylightbulb/template/catalog/category and the view.phtml does not contain the html i am after

Thanks

答:
You should be able to edit their theme file for the category page here

/app/design/frontend/themepackage/theme/template/catalog/category/view.phtml

Title: Change Magento Template


问:
Unity - using enum properties to detect objects colliding
Last night I was working on a C-Sharp project trying to code around GameObjects hitting each other.  I wanted different gate types (e.g. wood, stone, metal) that could be broken down by different weapons (e.g. club, sword, axe).

For detecting the collisions on the GateManager I was using tags for each gate. So for example:

```<code>    void OnTriggerEnter(Collider collider) {
       switch (gameObject.tag) {
         case "WoodenGate":
             ...
         case "StoneGate":
             ...
</code>```

The above code isn't exact but should give an idea.  It felt wrong to have each gate type set as a different tag (if every gate type has a different tag and every material type has a different tag, etc, then I will end up with hundreds of tags).

So I came up with an alternative.  I set up an enum of GateType and created 3 values (WoodenGate, StoneGate, MetalGate).  I then attached a public GateType property to the GateManager class.  This allowed me to select which enum was relevant to each prefab within the 'Inspector' window of unity.  It was very neat and I was really happy.

Then a problem arose: I added a 4th enum halfway up the list (e.g. GlassGate). Because the enums are simply int values, the 3rd item was no longer MetalGate but was now StoneGate.  This meant the metal gate prefab suddenly had a GateType of stonegate.  Which broke my game.

Apologies, for the wordy question, but my question therefore is how should I best label and identify lots of different types of items?  I don't want to use tags (because I would need too many) and I don't want to use enums (because they form the brittle issue when used in conjuction with the unity inspector.

I assume this must be a common requirement for many games (e.g. in games you can use your pickaxe on lots of different gameobjects to gathering different resources) so just wondering the best practice?

答:
Enums are the most convenient way to do this. Add an index to the enum value and increment it manually.

```<code>public GateType gateType;

public enum GateType
{
    Wood = 0,
    Stone = 1,
    Brick = 2
}
</code>```

Now if you want to add another one in the middle of the 'list' do it like this:

```<code>public GateType gateType;

public enum GateType
{
    Wood = 0,
    Metall = 3,
    Stone = 1,
    Brick = 2
}
</code>```

Unity should keep the correct values on your objects, since you added the index.

Body:
Last night I was working on a C-Sharp project trying to code around GameObjects hitting each other.  I wanted different gate types (e.g. wood, stone, metal) that could be broken down by different weapons (e.g. club, sword, axe).

For detecting the collisions on the GateManager I was using tags for each gate. So for example:

    void OnTriggerEnter(Collider collider) {
       switch (gameObject.tag) {
         case "WoodenGate":
             ...
         case "StoneGate":
             ...

The above code isn't exact but should give an idea.  It felt wrong to have each gate type set as a different tag (if every gate type has a different tag and every material type has a different tag, etc, then I will end up with hundreds of tags).

So I came up with an alternative.  I set up an enum of GateType and created 3 values (WoodenGate, StoneGate, MetalGate).  I then attached a public GateType property to the GateManager class.  This allowed me to select which enum was relevant to each prefab within the 'Inspector' window of unity.  It was very neat and I was really happy.

Then a problem arose: I added a 4th enum halfway up the list (e.g. GlassGate). Because the enums are simply int values, the 3rd item was no longer MetalGate but was now StoneGate.  This meant the metal gate prefab suddenly had a GateType of stonegate.  Which broke my game.

Apologies, for the wordy question, but my question therefore is how should I best label and identify lots of different types of items?  I don't want to use tags (because I would need too many) and I don't want to use enums (because they form the brittle issue when used in conjuction with the unity inspector.

I assume this must be a common requirement for many games (e.g. in games you can use your pickaxe on lots of different gameobjects to gathering different resources) so just wondering the best practice?

Body:
Enums are the most convenient way to do this. Add an index to the enum value and increment it manually.

public GateType gateType;

public enum GateType
{
    Wood = 0,
    Stone = 1,
    Brick = 2
}

Now if you want to add another one in the middle of the 'list' do it like this:

public GateType gateType;

public enum GateType
{
    Wood = 0,
    Metall = 3,
    Stone = 1,
    Brick = 2
}

Unity should keep the correct values on your objects, since you added the index.


问:
java: multiple exception throwing
I read one piece of codes:

```<code>public void myfunc() throws MyException {
       try {
            // codes here
        } catch(AlreadyExistsException e) {
            throw new sub1MyException("yyy"); // first catch block
        } catch(Exception e) {
            throw new sub2MyException("xxx"); // second catch block
        }
}
</code>```

sub1MyException and sub2MyException are both sub-classes of MyException. AlreadyExistsException is NOT sub-class of MyException.

I have some questons:

1, will throw new sub1MyException("yyy"); be caught by the second catch block?

2, Any anti-patterns in the above codes. I did some search but did not find any similar patterns or examples. If any, please leave a comment.

3, I think, it is not necessary to use so many sub-classes because exception messages already in the Exception. Custom messages such as yyy and xxx not very helpful.

Thanks

答:
1) no it won't. it's not inside the try-catch. </p>

<p>2 & 3 - it depends what you need to do. if you need to handle the different exceptions in a different manner, then do so. Otherwise you can just catch Exception. </p>

Title: java: multiple exception throwing

Body:
I read one piece of codes:

public void myfunc() throws MyException {
       try {
            // codes here
        } catch(AlreadyExistsException e) {
            throw new sub1MyException("yyy"); // first catch block
        } catch(Exception e) {
            throw new sub2MyException("xxx"); // second catch block
        }
}

sub1MyException and sub2MyException are both sub-classes of MyException. AlreadyExistsException is NOT sub-class of MyException.

I have some questons:

1, will throw new sub1MyException("yyy"); be caught by the second catch block?

2, Any anti-patterns in the above codes. I did some search but did not find any similar patterns or examples. If any, please leave a comment.

3, I think, it is not necessary to use so many sub-classes because exception messages already in the Exception. Custom messages such as yyy and xxx not very helpful.

Thanks

Body:
1) no it won't. it's not inside the try-catch.

2 & 3 - it depends what you need to do. if you need to handle the different exceptions in a different manner, then do so. Otherwise you can just catch Exception.


问:
How to disable editing in EditText on start, then enable it back when the user clicks on the EditText?
My app contains an EditText object with some text in it. When the activity opens I don't want this EditText to be editable (view only, no blinking cursor & no keyboard pop up). Then in order to edit, the user clicks on the EditText (This brings back the blinking cursor and the keyboard pops up).
There should have been a function like setEditable(boolean). The editable XML attribute in EditText is deprecated (The warning suggests using setInputType() instead).

Is there a way to achieve this?

Final note: I have searched the internet for couple hours and this is the best I ended up with:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
...

editor = (EditText) findViewById(R.id.noteEditText);
editor.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        editor.setInputType(
                EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
    }
});

editor.setInputType(EditorInfo.TYPE_NULL);

...
}
</code>```

This doesn't work as I intend. I have to double click in order to be able to edit (On first click the blinking cursor and the keyboard don't appear, in second click they do)

答:
Place this in your parent tag of the XML and you are done.

```<code>android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
</code>```

But the basic idea is to stop child views getting focus before anything else. So just give focus to the parent view group before the child.

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/mainLayout"
  android:descendantFocusability="beforeDescendants"
  android:focusableInTouchMode="true" >

    <EditText
        android:id="@+id/noteEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="number"
        android:maxLength="30" >
    </EditText>

</RelativeLayout>
</code>```

Body:
My app contains an EditText object with some text in it. When the activity opens I don't want this EditText to be editable (view only, no blinking cursor & no keyboard pop up). Then in order to edit, the user clicks on the EditText (This brings back the blinking cursor and the keyboard pops up).
There should have been a function like setEditable(boolean). The editable XML attribute in EditText is deprecated (The warning suggests using setInputType() instead).

Is there a way to achieve this?

Final note: I have searched the internet for couple hours and this is the best I ended up with:

@Override
protected void onCreate(Bundle savedInstanceState) {
...

editor = (EditText) findViewById(R.id.noteEditText);
editor.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        editor.setInputType(
                EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE);
    }
});

editor.setInputType(EditorInfo.TYPE_NULL);

...
}

This doesn't work as I intend. I have to double click in order to be able to edit (On first click the blinking cursor and the keyboard don't appear, in second click they do)

Body:
Place this in your parent tag of the XML and you are done.

android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"

But the basic idea is to stop child views getting focus before anything else. So just give focus to the parent view group before the child.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/mainLayout"
  android:descendantFocusability="beforeDescendants"
  android:focusableInTouchMode="true" >

    <EditText
        android:id="@+id/noteEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="number"
        android:maxLength="30" >
    </EditText>

</RelativeLayout>


问:
Autohotkey : Wildcard ahk_class match
I used winspy to grab an ahk_class for my autohotkey macro. Sometimes that application has 2+ ahk_classes associated with that program

Example:

```<code>HwndWrapper[program.exe;;1111-1111]
HwndWrapper[program.exe;;2222-2222]
</code>```

How can I use winNotExist to simply just match both names? Or perhaps use a ||, OR etc?

E.g.

```<code>F12::
IfWinNotExist, ahk_class "HwndWrapper.+"
    Run, AQ8.exe
GroupAdd, kjexplorers11, ahk_class "HwndWrapper.+" ;You have to make a new group for each application, don't use the same one for all of them!
if WinActive("ahk_exe AQ8.exe")
    GroupActivate, kjexplorers11, r
else
    WinActivate ahk_class ahk_class "HwndWrapper.+" ;you have to use WinActivatebottom if you didn't create a window group.
Return
</code>```

答:
I finally figured it out. SetTitleMatchMode, Regex.

This command affects the behavior of all windowing commands, e.g. WinExist and WinActivate

Then write some javascript-like regex statements as arguments.

The full list of window commands is on AHK site

Script, revised

```<code>F12::
SetTitleMatchMode,RegEx
IfWinNotExist, ahk_class HwndWrapper.+
    Run, AQ8.exe
GroupAdd, kjexplorers11, ahk_class HwndWrapper.+ ;You have to make a new group for each application, don't use the same one for all of them!
if WinActive("ahk_exe AQ8.exe")
    GroupActivate, kjexplorers11, r
else
    WinActivate ahk_class ahk_class HwndWrapper.+ ;you have to use WinActivatebottom if you didn't create a window group.
Return
</code>```

So now I can cycle through any application with more than 1 ahk_Class name. Example of what script does

Title: Autohotkey : Wildcard ahk_class match

Body:
I used winspy to grab an ahk_class for my autohotkey macro. Sometimes that application has 2+ ahk_classes associated with that program

Example:

HwndWrapper[program.exe;;1111-1111]
HwndWrapper[program.exe;;2222-2222]

How can I use winNotExist to simply just match both names? Or perhaps use a ||, OR etc?

E.g.

F12::
IfWinNotExist, ahk_class "HwndWrapper.+"
    Run, AQ8.exe
GroupAdd, kjexplorers11, ahk_class "HwndWrapper.+" ;You have to make a new group for each application, don't use the same one for all of them!
if WinActive("ahk_exe AQ8.exe")
    GroupActivate, kjexplorers11, r
else
    WinActivate ahk_class ahk_class "HwndWrapper.+" ;you have to use WinActivatebottom if you didn't create a window group.
Return

Body:
I finally figured it out. SetTitleMatchMode, Regex.

This command affects the behavior of all windowing commands, e.g. WinExist and WinActivate

Then write some javascript-like regex statements as arguments.

The full list of window commands is on AHK site

Script, revised

F12::
SetTitleMatchMode,RegEx
IfWinNotExist, ahk_class HwndWrapper.+
    Run, AQ8.exe
GroupAdd, kjexplorers11, ahk_class HwndWrapper.+ ;You have to make a new group for each application, don't use the same one for all of them!
if WinActive("ahk_exe AQ8.exe")
    GroupActivate, kjexplorers11, r
else
    WinActivate ahk_class ahk_class HwndWrapper.+ ;you have to use WinActivatebottom if you didn't create a window group.
Return

So now I can cycle through any application with more than 1 ahk_Class name. Example of what script does


答:
No, you'd have to nest a try-catch block inside your catch for that to happen.

Catching Exception is an anti-pattern in itself, but it's so widely used that people don't really care anymore. You shouldn't really catch Exception because then you basically have no idea what you are expecting (and try-catch blocks are about predictability). The only place in which you should blanket-catch Exception is in a general error handler that handles the final error dispatch (showing a big ugly error message, logging errors etc.)

If the only thing in which your errors differ is in the error message, then no, there's no use in differentiating them. If there's a difference in how they propagate (for example, one is a recoverable error and the other is a runtime error), then you should differentiate. The rule of the thumb is that you should only have different Exception classes if they differ in their propagation strategy (i.e. in which try-catch blocks they are handled in further down the road).

Title: java: multiple exception throwing