问:
DynamoDB partition key choice for notes app
I want to create a DynamoDB table that allows me to save notes from users.

The attributes I have:

user_id

note_id (uuid)

type

text

The main queries I will need:

Get all notes of a certain user

Get a specific note

Get all notes of a certain type (the less used query)

I know that in terms of performance and DynamoDB partitions note_id would be the right choice because they are unique and would be distributed equally over the partitions but on the other hand is much harder to get all notes of a user without scanning all items or using a GSI. And if they are unique I suppose it doesn't make any sense to have a sort key.

The other option would be to use user_id as partition key and note_id as sort key, but if I have certain users that are a much larger number of notes than others wouldn't that impact my performance?

Is it better to have a partition key unique (like note_id) to scale well with DynamoDB partitions and use GSIs to create my queries or to use instead a partition key for my main query (user_id)?

Thanks

答:
Possibly the simplest and most cost-effective way would be a single table:

Table Structure

note_id (uuid) / hash key

user_id

type

text

Have two GSIs, one for "Get all notes of a certain user" and one for "Get all notes of a certain type (the less used query)":

GSI for "Get all notes of a certain user"

user_id / hash key

note_id (uuid) / range key

type

text

A little note on this - which of your queries is the most frequent: "Get all notes of a certain user" or "Get a specific note"? If it's the former, then you could swap the GSI keys for the table keys and vice-versa (if that makes sense - in essence, have your user_id + note_id as the key for your table and the note_id as the GSI key). This also depends upon how you structure your user_id - I suspect you've already picked up on; make sure your user_id is not sequential - make it a UUID or similar.

GSI for "Get all notes of a certain type (the less used query)"

type / hash key

note_id (uuid) / range key

user_id

text

Depending upon the cardinality of the type field, you'll need to test whether a GSI will actually be of benefit here or not.

If the GSI is of little benefit and you need more performance, another option would be to store the type with an array of note_id in a separate table altogether. Beware of the 400k item limit with this one and the fact that you'll need to perform another query to get the text of the note.

With this table structure and GSIs, you're able to make a single query for the information you're after, rather than making two if you have two tables.

Of course, you know your data best - it's best to start with what you think is best and then test it to ensure it meets what you're looking for. DynamoDB is priced by provisioned throughput + the amount of indexed data stored so creating "fat" indexes with many attributes projects, as above, if there is a lot of data then it could become more cost effective to perform two queries and store less indexed data.


来源: stackexchange

问:
Googlechart as image tag with specific format ruby on rails
How do I add a image tag with a google pie chart, until now I have installed the gem but I would like to also personalize the chart, the size, colors, tags, etc. I've tried using tutorial like rail cast but it is outdated and some don't work for me.</p>

```<code><%=image tag #googlechart %>
</code>```

答:
If you installed the gem and used the command bundle install like shown below

Gemfile:

```<code>gem "googlecharts", :require => "gchart"
</code>```

file.html.ebr:

```<code><% require 'gchart' %>
<%= image_tag(Gchart.pie
            :size => '600x400',
            :title => 'Title here',
            :data => [1,4,5],
            :legend => ['Parameter1','Parameter2','Parameter3'],
            :bar_colors => ['2EB82E','3399FF','FF471A'],
            :labels => [label1, label2, label3])%>
</code>```

The chart has the format of the size, title, data, legend, colors and labels that can be personalized and is painted as an image in the html.

ContentLicense: CC BY-SA 3.0

Body:
How do I add a image tag with a google pie chart, until now I have installed the gem but I would like to also personalize the chart, the size, colors, tags, etc. I've tried using tutorial like rail cast but it is outdated and some don't work for me.

<%=image tag #googlechart %>

Body:
If you installed the gem and used the command bundle install like shown below

Gemfile:

gem "googlecharts", :require => "gchart"

file.html.ebr:

<% require 'gchart' %>
<%= image_tag(Gchart.pie
            :size => '600x400',
            :title => 'Title here',
            :data => [1,4,5],
            :legend => ['Parameter1','Parameter2','Parameter3'],
            :bar_colors => ['2EB82E','3399FF','FF471A'],
            :labels => [label1, label2, label3])%>

The chart has the format of the size, title, data, legend, colors and labels that can be personalized and is painted as an image in the html.


问:
SQL INTERSECT by one field and get another field
I'm trying to do this SQL query:

```<code> SELECT field FROM table
 INTERSECT
 SELECT field FROM table
</code>```

Which return the intersection by the given field, but I want to get another field from the table as a result (intersected by the given field), how do I do that?

答:
I would use an EXISTS subquery:

```<code>SELECT t1.OtherField
FROM Table1 t1
WHERE EXISTS (
        SELECT 1
        FROM Table2 t2
        WHERE t2.Field = t1.Field
    )
</code>```

Alternately, you can use an IN subquery, which may work better in some RDBMSs or configurations:

```<code>SELECT t1.OtherField
FROM Table1 t1
WHERE t1.Field IN (
        SELECT t2.Field
        FROM Table2 t2
    )
</code>```

Body:
I'm trying to do this SQL query:

 SELECT field FROM table
 INTERSECT
 SELECT field FROM table

Which return the intersection by the given field, but I want to get another field from the table as a result (intersected by the given field), how do I do that?

Body:
I would use an EXISTS subquery:

SELECT t1.OtherField
FROM Table1 t1
WHERE EXISTS (
        SELECT 1
        FROM Table2 t2
        WHERE t2.Field = t1.Field
    )

Alternately, you can use an IN subquery, which may work better in some RDBMSs or configurations:

SELECT t1.OtherField
FROM Table1 t1
WHERE t1.Field IN (
        SELECT t2.Field
        FROM Table2 t2
    )


问:
Making a new list with tuples based on strings in the list
```<code>L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]
</code>```

Each number represents a person. So, there are five people from 0 to 4 in the list. L[0] always shows how many people are in the list.

```<code>L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]
</code>```

The person "0" is paired with 1 and 2. So, it has a list of 1, 2 in a tuple. My approach to get the result above is to compare the first character in L[1] to the end of the list. If the first letter in L[1] matches with the first letter in L[2], it bundles the second letter in L[2] with the second letter in L[1]. Finally, the new list is paired with 0 in a tuple. By the way, I cannot come up with such thing that can check the first letter in strings. I am not sure if this approach is right or not.

I am struggling to make such list L1 above. Could anyone let me know if my approach to this question is right? If it is wrong, please briefly give me a hint to solve this.

答:
Probably the best thing is to first use a defaultdict:

```<code>from collections import defaultdict
from itertools import islice

result = defaultdict(list)

for li in islice(L,1,None):
    h, *others = map(int,li.split())
    for other in others:
        result[h].append(other)
</code>```

Or a version that works for python-2.x:

```<code>from collections import defaultdict
from itertools import islice

result = defaultdict(list)

for li in islice(L,1,None):
    data = map(int,li.split())
    h = data[0]
    for other in data[1:]:
        result[h].append(other)
</code>```

and then we obtain the items of that dictionary:

```<code>L1 = list(result.items())
</code>```

This produces:

```<code>>>> L1
[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]
</code>```

Note that in this case the items are not ordered: since a dictionary in Python usually has no order (the latest implementations in CPython have, but this is seen as an implementation detail).

But converting the dictionary back into a list is not logical, since the advantage of a dictionary is a fast lookup (in O(1), constant time).

We can make the last part more elegant by writing:

```<code>from collections import defaultdict

result = defaultdict(list)

for li in islice(L,1,None):
    h, *others = map(int,li.split())
    result[h] += others
</code>```

Body:
L = ["5", "0 1", "0 2", "1 3", "2 3", "2 4", "3 4"]

Each number represents a person. So, there are five people from 0 to 4 in the list. L[0] always shows how many people are in the list.

L1 = [(0,[1,2]), (1, [3]), (2, [3,4]), (3, [4])]

The person "0" is paired with 1 and 2. So, it has a list of 1, 2 in a tuple. My approach to get the result above is to compare the first character in L[1] to the end of the list. If the first letter in L[1] matches with the first letter in L[2], it bundles the second letter in L[2] with the second letter in L[1]. Finally, the new list is paired with 0 in a tuple. By the way, I cannot come up with such thing that can check the first letter in strings. I am not sure if this approach is right or not.

I am struggling to make such list L1 above. Could anyone let me know if my approach to this question is right? If it is wrong, please briefly give me a hint to solve this.

Body:
Probably the best thing is to first use a defaultdict:

from collections import defaultdict
from itertools import islice

result = defaultdict(list)

for li in islice(L,1,None):
    h, *others = map(int,li.split())
    for other in others:
        result[h].append(other)

Or a version that works for python-2.x:

from collections import defaultdict
from itertools import islice

result = defaultdict(list)

for li in islice(L,1,None):
    data = map(int,li.split())
    h = data[0]
    for other in data[1:]:
        result[h].append(other)

and then we obtain the items of that dictionary:

L1 = list(result.items())

This produces:

>>> L1
[(0, [1, 2]), (1, [3]), (2, [3, 4]), (3, [4])]

Note that in this case the items are not ordered: since a dictionary in Python usually has no order (the latest implementations in CPython have, but this is seen as an implementation detail).

But converting the dictionary back into a list is not logical, since the advantage of a dictionary is a fast lookup (in O(1), constant time).

We can make the last part more elegant by writing:

from collections import defaultdict

result = defaultdict(list)

for li in islice(L,1,None):
    h, *others = map(int,li.split())
    result[h] += others


问:
Application Not Receiving Serial Data from COM Port - C++
My application is not properly receiving data from the COM port.  This used to work.  I don't know what happened.  I know that the proper data is being sent/received over the line because I can see it on my protocol analyzer.

The PC gets into the WAIT_OBJECT_0 + 1 state, but the buffer contents are always zero.  I know this is a lot, but if anyone can point out what I'm doing wrong, I'd really appreciate it.  I can add/remove details as requested.  Thanks.

EDIT: Additional Information

I have been able to verify that the PC makes the call to ReadFileEx, and it "succeeds."  However, the PC never gets into FileIOCompletionRoutine.  Any ideas?  (I removed the error-handling from the code to make life simpler.)  Also, from what I read on the MSDN website, it looks like FileIOCompletionRoutine will get called asynchronously in its own thread.  Is that correct?  Thanks.

EDIT: Final Solution

This is what I came up with.  Obviously, the initialization and error-handling code is not here.  We can't make things too easy. :)

```<code>// Load event handles.
pHandles[0] = s_hSerialPortRxThreadExitEvent;
// OVERLAPPED structure event handle is loaded in loop.

while ( blContinue )
{
    // Wait for a communications event.
    if ( !::WaitCommEvent( s_hSerialPort, &dwEventMask, &s_ov ) )
    {
        if ( ::GetLastError() != ERROR_IO_PENDING )
        {
            blContinue = FALSE;
            continue;
        }
        else if ( ::WaitForSingleObject( pHandles[0], 0 ) == WAIT_OBJECT_0 )
        {
            // The thread-exit event has been signaled.  Get out of here.
            blContinue = FALSE;
            continue;
        }
    }
    else
    {
        // Load OVERLAPPED structure event handle.
        pHandles[1] = s_ov.hEvent;
    }

    if ( dwEventMask & EV_RXCHAR )
    {
        if ( !::ReadFile( s_hSerialPort, pBuf, RX_BUF_SIZE, NULL, &s_ov ) )
        {
            if ( ::GetLastError() == ERROR_IO_PENDING )
            {
                // Wait for events.
                dwObjectWaitState = ::WaitForMultipleObjects( 2, pHandles, FALSE, INFINITE );

                // Switch on event.
                switch ( dwObjectWaitState )
                {
                case WAIT_OBJECT_0:             // thread exit event signaled
                    blContinue = FALSE;
                    continue;

                case WAIT_OBJECT_0 + 1:         // OVERLAPPED structure event signalled
                    // Reset event first to mitigate underrun condition.
                    if ( !::ResetEvent( pHandles[1] ) )
                    {
                        blContinue = FALSE;
                        continue;
                    }

                    // Get the OVERLAPPED result.
                    if ( !::GetOverlappedResult( s_hSerialPort, &s_ov, &dwBytesRead, FALSE ) )
                    {
                        blContinue = FALSE;
                        continue;
                    }
                    break;

                default:                        // Error
                    blContinue = FALSE;
                    continue;
                }
            }
        }
        else if ( !::GetOverlappedResult( s_hSerialPort, &s_ov, &dwBytesRead, FALSE ) )
        {
            blContinue = FALSE;
            continue;
        }

        // If bytes were read...
        if ( dwBytesRead > 0 )
        {
            // Copy received data from local buffer to thread-safe serial port buffer.
            ::EnterCriticalSection( &s_csRxRingBuffer );
            blSuccess = s_pobjRxRingBuffer->Add( pBuf, dwBytesRead, TRUE );
            ::LeaveCriticalSection( &s_csRxRingBuffer );

            if ( !blSuccess )
            {
                blContinue = FALSE;
                continue;
            }

            // Set the received data event.
            if ( !::SetEvent( s_phEventIds[RECEIVE_EVENT] ) )
            {
                blContinue = FALSE;
                continue;
            }
        }
    }

    if ( dwEventMask & EV_TXEMPTY )
    {
        // Set the transmit complete event.
        if ( !::SetEvent( s_phEventIds[TRANSMIT_EVENT] ) )
        {
            blContinue = FALSE;
            continue;
        }
    }

} // end while ( blContinue );
</code>```

答:
Also, from what I read on the MSDN
  website, it looks like
  FileIOCompletionRoutine will get
  called asynchronously in its own
  thread. Is that correct?

No, that is not correct. The completion routine gets called in the context of the thread in which it the ReadFileEx called is made. When it is ready to run, it is queued until the thread is in an "alertable wait state". That typically happens when you call one of the Wait* functions. Furthermore, from the MSDN for ReadFileEx, it states:

The ReadFileEx function ignores the
  OVERLAPPED structure's hEvent member.
  An application is free to use that
  member for its own purposes in the
  context of a ReadFileEx call.
  ReadFileEx signals completion of its
  read operation by calling, or queuing
  a call to, the completion routine
  pointed to by lpCompletionRoutine, so
  it does not need an event handle.

So the event you have created has no effect. Also, the reads will not be processed until ReadFileEx is called, so you have to reverse the order with your wait. What you should be doing in your reading loop is something like this (in Pseudocode):

```<code>while(continue)
{
    ReadFileEx();
    WaitForSingleObject(s_hSerialPortRxThreadExitEvent);
    . . . etc . . .
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My application is not properly receiving data from the COM port.  This used to work.  I don't know what happened.  I know that the proper data is being sent/received over the line because I can see it on my protocol analyzer.

The PC gets into the WAIT_OBJECT_0 + 1 state, but the buffer contents are always zero.  I know this is a lot, but if anyone can point out what I'm doing wrong, I'd really appreciate it.  I can add/remove details as requested.  Thanks.

EDIT: Additional Information

I have been able to verify that the PC makes the call to ReadFileEx, and it "succeeds."  However, the PC never gets into FileIOCompletionRoutine.  Any ideas?  (I removed the error-handling from the code to make life simpler.)  Also, from what I read on the MSDN website, it looks like FileIOCompletionRoutine will get called asynchronously in its own thread.  Is that correct?  Thanks.

EDIT: Final Solution

This is what I came up with.  Obviously, the initialization and error-handling code is not here.  We can't make things too easy. :)

// Load event handles.
pHandles[0] = s_hSerialPortRxThreadExitEvent;
// OVERLAPPED structure event handle is loaded in loop.

while ( blContinue )
{
    // Wait for a communications event.
    if ( !::WaitCommEvent( s_hSerialPort, &dwEventMask, &s_ov ) )
    {
        if ( ::GetLastError() != ERROR_IO_PENDING )
        {
            blContinue = FALSE;
            continue;
        }
        else if ( ::WaitForSingleObject( pHandles[0], 0 ) == WAIT_OBJECT_0 )
        {
            // The thread-exit event has been signaled.  Get out of here.
            blContinue = FALSE;
            continue;
        }
    }
    else
    {
        // Load OVERLAPPED structure event handle.
        pHandles[1] = s_ov.hEvent;
    }

    if ( dwEventMask & EV_RXCHAR )
    {
        if ( !::ReadFile( s_hSerialPort, pBuf, RX_BUF_SIZE, NULL, &s_ov ) )
        {
            if ( ::GetLastError() == ERROR_IO_PENDING )
            {
                // Wait for events.
                dwObjectWaitState = ::WaitForMultipleObjects( 2, pHandles, FALSE, INFINITE );

                // Switch on event.
                switch ( dwObjectWaitState )
                {
                case WAIT_OBJECT_0:             // thread exit event signaled
                    blContinue = FALSE;
                    continue;

                case WAIT_OBJECT_0 + 1:         // OVERLAPPED structure event signalled
                    // Reset event first to mitigate underrun condition.
                    if ( !::ResetEvent( pHandles[1] ) )
                    {
                        blContinue = FALSE;
                        continue;
                    }

                    // Get the OVERLAPPED result.
                    if ( !::GetOverlappedResult( s_hSerialPort, &s_ov, &dwBytesRead, FALSE ) )
                    {
                        blContinue = FALSE;
                        continue;
                    }
                    break;

                default:                        // Error
                    blContinue = FALSE;
                    continue;
                }
            }
        }
        else if ( !::GetOverlappedResult( s_hSerialPort, &s_ov, &dwBytesRead, FALSE ) )
        {
            blContinue = FALSE;
            continue;
        }

        // If bytes were read...
        if ( dwBytesRead > 0 )
        {
            // Copy received data from local buffer to thread-safe serial port buffer.
            ::EnterCriticalSection( &s_csRxRingBuffer );
            blSuccess = s_pobjRxRingBuffer->Add( pBuf, dwBytesRead, TRUE );
            ::LeaveCriticalSection( &s_csRxRingBuffer );

            if ( !blSuccess )
            {
                blContinue = FALSE;
                continue;
            }

            // Set the received data event.
            if ( !::SetEvent( s_phEventIds[RECEIVE_EVENT] ) )
            {
                blContinue = FALSE;
                continue;
            }
        }
    }

    if ( dwEventMask & EV_TXEMPTY )
    {
        // Set the transmit complete event.
        if ( !::SetEvent( s_phEventIds[TRANSMIT_EVENT] ) )
        {
            blContinue = FALSE;
            continue;
        }
    }

} // end while ( blContinue );

Body:
Also, from what I read on the MSDN
  website, it looks like
  FileIOCompletionRoutine will get
  called asynchronously in its own
  thread. Is that correct?

No, that is not correct. The completion routine gets called in the context of the thread in which it the ReadFileEx called is made. When it is ready to run, it is queued until the thread is in an "alertable wait state". That typically happens when you call one of the Wait* functions. Furthermore, from the MSDN for ReadFileEx, it states:

The ReadFileEx function ignores the
  OVERLAPPED structure's hEvent member.
  An application is free to use that
  member for its own purposes in the
  context of a ReadFileEx call.
  ReadFileEx signals completion of its
  read operation by calling, or queuing
  a call to, the completion routine
  pointed to by lpCompletionRoutine, so
  it does not need an event handle.

So the event you have created has no effect. Also, the reads will not be processed until ReadFileEx is called, so you have to reverse the order with your wait. What you should be doing in your reading loop is something like this (in Pseudocode):

while(continue)
{
    ReadFileEx();
    WaitForSingleObject(s_hSerialPortRxThreadExitEvent);
    . . . etc . . .
}


问:
Use eval to update local variables?
I want to provide eval some compiled code (via compile) that when evaluated should update some variables in the locals I passed in.

```<code>x = 5
global_dict = {'__builtins__': None}
local_dict = {'x': x}
code = compile("x = x * 2", "<string>", "single")

# This updates x
eval(code, global_dict, globals())

# This doesn't
eval(code, global_dict, local_dict)

# Nor does this...
eval(code, global_dict, globals().copy())
</code>```

答:
You could do it like this (it works in CPython 3.6.3 anyway), although it not OK to update the dictionary returned by locals() (see Note in the documentation.

```<code>x = 5
code = compile("x = x * 2", "<string>", "single")
eval(code, locals())
print('x:', x)  # -> x: 10
</code>```

Note, too, as @juanpa.arrivillaga pointed out in a comment, that at the module-level, locals()is the same as globals()—so you can avoid the restriction by using it instead. In other words, eval(code, globals()) would be better and avoids the issue.

(I verified that they're the same with an assert locals() == globals() at the beginning of the code to verify they're the same.)

Title: Use eval to update local variables?

Body:
I want to provide eval some compiled code (via compile) that when evaluated should update some variables in the locals I passed in.

x = 5
global_dict = {'__builtins__': None}
local_dict = {'x': x}
code = compile("x = x * 2", "<string>", "single")

# This updates x
eval(code, global_dict, globals())

# This doesn't
eval(code, global_dict, local_dict)

# Nor does this...
eval(code, global_dict, globals().copy())

Body:
You could do it like this (it works in CPython 3.6.3 anyway), although it not OK to update the dictionary returned by locals() (see Note in the documentation.

x = 5
code = compile("x = x * 2", "<string>", "single")
eval(code, locals())
print('x:', x)  # -> x: 10

Note, too, as @juanpa.arrivillaga pointed out in a comment, that at the module-level, locals()is the same as globals()—so you can avoid the restriction by using it instead. In other words, eval(code, globals()) would be better and avoids the issue.

(I verified that they're the same with an assert locals() == globals() at the beginning of the code to verify they're the same.)


问:
In Android how to display percentage in pie chart with achartengine
I am using achartengine for displaying the pie chart and I have tried this :--

```<code>public class AChartEnginePieChartActivity extends Activity {

private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };

private static double[] VALUES = new double[] { 10, 11, 12, 13 };

private static String[] NAME_LIST = new String[] { "A", "B", "C", "D" };

private CategorySeries mSeries = new CategorySeries("");

private DefaultRenderer mRenderer = new DefaultRenderer();

private GraphicalView mChartView;

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

mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);

for (int i = 0; i < VALUES.length; i++) {
mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}

if (mChartView != null) {
mChartView.repaint();
}

}

@SuppressLint("ShowToast")
@Override
protected void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);

mChartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();

if (seriesSelection == null) {
Toast.makeText(AChartEnginePieChartActivity.this,"No chart element was clicked",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AChartEnginePieChartActivity.this,"Chart element data point index "+ (seriesSelection.getPointIndex()+1) + " was clicked" + " point value="+ seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});

mChartView.setOnLongClickListener(new View.OnLongClickListener() {
@SuppressLint("ShowToast")
@Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(AChartEnginePieChartActivity.this,"No chart element was long pressed", Toast.LENGTH_SHORT);
return false;
} else {
Toast.makeText(AChartEnginePieChartActivity.this,"Chart element data point index "+ seriesSelection.getPointIndex()+ " was long pressed",Toast.LENGTH_SHORT);
return true;
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
else {
mChartView.repaint();
}
}
}
</code>```

Here its displaying the pie chart Like this picture..But I want the value as percentage..
like A(10%) B(11%) in the picture..
How can I do that?????
please suggest me

答:
Creating a IValueFormatter:

```<code>public class MyValueFormatter implements IValueFormatter {

private DecimalFormat mFormat;

public MyValueFormatter() {
    mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
}

@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
    // write your logic here
    return mFormat.format(value) + " %"; // e.g. append a dollar-sign
}}
</code>```

And next, set your formatter to the ChartData or DataSet object:

```<code>dataSet.setValueFormatter(new MyValueFormatter());
</code>```

Remember this inner class just adds % to the end of your value.
For example if you want to add $, you should be using $ instead of %.

Body:
I am using achartengine for displaying the pie chart and I have tried this :--

public class AChartEnginePieChartActivity extends Activity {

private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };

private static double[] VALUES = new double[] { 10, 11, 12, 13 };

private static String[] NAME_LIST = new String[] { "A", "B", "C", "D" };

private CategorySeries mSeries = new CategorySeries("");

private DefaultRenderer mRenderer = new DefaultRenderer();

private GraphicalView mChartView;

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

mRenderer.setApplyBackgroundColor(true);
mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50));
mRenderer.setChartTitleTextSize(20);
mRenderer.setLabelsTextSize(15);
mRenderer.setLegendTextSize(15);
mRenderer.setMargins(new int[] { 20, 30, 15, 0 });
mRenderer.setZoomButtonsVisible(true);
mRenderer.setStartAngle(90);

for (int i = 0; i < VALUES.length; i++) {
mSeries.add(NAME_LIST[i] + " " + VALUES[i], VALUES[i]);
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(mSeries.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}

if (mChartView != null) {
mChartView.repaint();
}

}

@SuppressLint("ShowToast")
@Override
protected void onResume() {
super.onResume();
if (mChartView == null) {
LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
mChartView = ChartFactory.getPieChartView(this, mSeries, mRenderer);
mRenderer.setClickEnabled(true);
mRenderer.setSelectableBuffer(10);

mChartView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();

if (seriesSelection == null) {
Toast.makeText(AChartEnginePieChartActivity.this,"No chart element was clicked",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AChartEnginePieChartActivity.this,"Chart element data point index "+ (seriesSelection.getPointIndex()+1) + " was clicked" + " point value="+ seriesSelection.getValue(), Toast.LENGTH_SHORT).show();
}
}
});

mChartView.setOnLongClickListener(new View.OnLongClickListener() {
@SuppressLint("ShowToast")
@Override
public boolean onLongClick(View v) {
SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
if (seriesSelection == null) {
Toast.makeText(AChartEnginePieChartActivity.this,"No chart element was long pressed", Toast.LENGTH_SHORT);
return false;
} else {
Toast.makeText(AChartEnginePieChartActivity.this,"Chart element data point index "+ seriesSelection.getPointIndex()+ " was long pressed",Toast.LENGTH_SHORT);
return true;
}
}
});
layout.addView(mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
else {
mChartView.repaint();
}
}
}

Here its displaying the pie chart Like this picture..But I want the value as percentage..
like A(10%) B(11%) in the picture..
How can I do that?????
please suggest me

Body:
Creating a IValueFormatter:

public class MyValueFormatter implements IValueFormatter {

private DecimalFormat mFormat;

public MyValueFormatter() {
    mFormat = new DecimalFormat("###,###,##0.0"); // use one decimal
}

@Override
public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
    // write your logic here
    return mFormat.format(value) + " %"; // e.g. append a dollar-sign
}}

And next, set your formatter to the ChartData or DataSet object:

dataSet.setValueFormatter(new MyValueFormatter());

Remember this inner class just adds % to the end of your value.
For example if you want to add $, you should be using $ instead of %.


问:
Observable Collection Edit items if exists else add new one
I have some textbox in my window, their content will be added into Observable Collection after clicking on btn_add then will be a source for dg_VoucherDetail.
Problem is :
When I use it first time everything is fine but second time it just replace the old Observable Collection except adding new item to old Collection,
and for edit section there is no item in Collection to search and edit.
Here is The Code :</p>

```<code>    private void btn_add_Click(object sender, RoutedEventArgs e)
    {
        _VoucherDetail = new ObservableCollection<VoucherDetail>();
        VoucherDetail Voucher = new VoucherDetail();

        if (dg_VoucherDetail.HasItems == true)
        {
            for (int i = 0; i < _VoucherDetail.Count; i++)
            {
                if (_VoucherDetail[i].LedgerID == SelectedLedgerID)
                {
                    if (_VoucherDetail[i].DefinitiveID == SelectedDefinitiveID)
                    {
                        if (_VoucherDetail[i].Credit == Convert.ToDecimal(txt_Amount.Text))
                            return;
                        else if (_VoucherDetail[i].Debit == Convert.ToDecimal(txt_Amount.Text))
                            return;
                        else
                        {
                            Voucher.LedgerID = SelectedLedgerID;
                            Voucher.DefinitiveID = SelectedDefinitiveID;
                            if (radio_debit.IsChecked == true)
                            {
                                Voucher.Debit = Convert.ToDecimal(txt_Amount.Text);
                                Voucher.Credit = 0;
                            }
                            else if (radio_credit.IsChecked == true)
                            {
                                Voucher.Debit = 0;
                                Voucher.Credit = Convert.ToDecimal(txt_Amount.Text);
                            }
                            _VoucherDetail[i] = Voucher;
                        }
                    }
                    else if (_VoucherDetail[i].DefinitiveID != SelectedDefinitiveID)
                    {
                        Voucher.LedgerID = SelectedLedgerID;
                        Voucher.DefinitiveID = SelectedDefinitiveID;
                        if (radio_debit.IsChecked == true)
                        {
                            Voucher.Debit = Convert.ToDecimal(txt_Amount.Text);
                            Voucher.Credit = 0;
                        }
                        else if (radio_credit.IsChecked == true)
                        {
                            Voucher.Debit = 0;
                            Voucher.Credit = Convert.ToDecimal(txt_Amount.Text);
                        }
                        _VoucherDetail.Add(Voucher);
                    }
                }
                else if (_VoucherDetail[i].LedgerID != SelectedLedgerID)
                {
                    Voucher.LedgerID = SelectedLedgerID;
                    Voucher.DefinitiveID = SelectedDefinitiveID;
                    if (radio_debit.IsChecked == true)
                    {
                        Voucher.Debit = Convert.ToDecimal(txt_Amount.Text);
                        Voucher.Credit = 0;
                    }
                    else if (radio_credit.IsChecked == true)
                    {
                        Voucher.Debit = 0;
                        Voucher.Credit = Convert.ToDecimal(txt_Amount.Text);
                    }
                    _VoucherDetail.Add(Voucher);
                }
            }
        }
        if (dg_VoucherDetail.HasItems == false)
        {
            Voucher.LedgerID = SelectedLedgerID;
            Voucher.DefinitiveID = SelectedDefinitiveID;
            if (radio_debit.IsChecked == true)
            {
                Voucher.Debit = Convert.ToDecimal(txt_Amount.Text);
                Voucher.Credit = 0;
            }
            else if (radio_credit.IsChecked == true)
            {
                Voucher.Debit = 0;
                Voucher.Credit = Convert.ToDecimal(txt_Amount.Text);
            }
            _VoucherDetail.Add(Voucher);
  //          dg_VoucherDetail.Items.Add(VoucherDetail);
        }
        dg_VoucherDetail.ItemsSource = _VoucherDetail;
    }

    internal class VoucherDetail
{
    public decimal LedgerID { get; set; }
    public decimal DefinitiveID { get; set; }
    public decimal Debit { get; set; }
    public decimal Credit { get; set; }
}
</code>```

答:
Here's a simple snippet which "updates" an entry if the entry is present in the collection. This snippet has things hard-coded but making it dynamic should be trivial.</p>

```<code>using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;

namespace UpdateObservableCollection_47291451
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        DataGrid dg = new DataGrid();
        Button btn = new Button();
        ObservableCollection<VoucherDetail> datasource = new ObservableCollection<VoucherDetail>();
        public MainWindow()
        {
            InitializeComponent();
            dg.Height = 200;
            dg.Width = 500;
            MainGrid.Children.Add(dg);//add DataGrid to page
            btn.Content = "Click me";
            btn.Click += Btn_Click;
            btn.Height = 25;
            btn.Width = 50;
            MainGrid.Children.Add(btn);//add button to page

            dg.ItemsSource = datasource;//bind grid to data

            //create initial data records
            for (int i = 0; i < 5; i++)
            {
                datasource.Add(new UpdateObservableCollection_47291451.VoucherDetail { Credit = i, Debit = i, DefinitiveID = i, LedgerID = i });
            }
        }

        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            //if a record with DefinitiveID of 1 exist, then update the entry
            if (datasource.FirstOrDefault(p => p.DefinitiveID == 1) != null)
            {
                datasource.First(p => p.DefinitiveID == 1).Credit = 1234;
                dg.Items.Refresh();
            }
            else
            {
                datasource.Add(new UpdateObservableCollection_47291451.VoucherDetail { DefinitiveID = 99, Credit = 99, Debit = 99, LedgerID = 99 });
            }
        }
    }

    internal class VoucherDetail
    {
        public decimal LedgerID { get; set; }
        public decimal DefinitiveID { get; set; }
        public decimal Debit { get; set; }
        public decimal Credit { get; set; }
    }

}
</code>```

Body:
I have some textbox in my window, their content will be added into Observable Collection after clicking on btn_add then will be a source for dg_VoucherDetail.
Problem is :
When I use it first time everything is fine but second time it just replace the old Observable Collection except adding new item to old Collection,
and for edit section there is no item in Collection to search and edit.
Here is The Code :

    private void btn_add_Click(object sender, RoutedEventArgs e)
    {
        _VoucherDetail = new ObservableCollection<VoucherDetail>();
        VoucherDetail Voucher = new VoucherDetail();

        if (dg_VoucherDetail.HasItems == true)
        {
            for (int i = 0; i < _VoucherDetail.Count; i++)
            {
                if (_VoucherDetail[i].LedgerID == SelectedLedgerID)
                {
                    if (_VoucherDetail[i].DefinitiveID == SelectedDefinitiveID)
                    {
                        if (_VoucherDetail[i].Credit == Convert.ToDecimal(txt_Amount.Text))
                            return;
                        else if (_VoucherDetail[i].Debit == Convert.ToDecimal(txt_Amount.Text))
                            return;
                        else
                        {
                            Voucher.LedgerID = SelectedLedgerID;
                            Voucher.DefinitiveID = SelectedDefinitiveID;
                            if (radio_debit.IsChecked == true)
                            {
                                Voucher.Debit = Convert.ToDecimal(txt_Amount.Text);
                                Voucher.Credit = 0;
                            }
                            else if (radio_credit.IsChecked == true)
                            {
                                Voucher.Debit = 0;
                                Voucher.Credit = Convert.ToDecimal(txt_Amount.Text);
                            }
                            _VoucherDetail[i] = Voucher;
                        }
                    }
                    else if (_VoucherDetail[i].DefinitiveID != SelectedDefinitiveID)
                    {
                        Voucher.LedgerID = SelectedLedgerID;
                        Voucher.DefinitiveID = SelectedDefinitiveID;
                        if (radio_debit.IsChecked == true)
                        {
                            Voucher.Debit = Convert.ToDecimal(txt_Amount.Text);
                            Voucher.Credit = 0;
                        }
                        else if (radio_credit.IsChecked == true)
                        {
                            Voucher.Debit = 0;
                            Voucher.Credit = Convert.ToDecimal(txt_Amount.Text);
                        }
                        _VoucherDetail.Add(Voucher);
                    }
                }
                else if (_VoucherDetail[i].LedgerID != SelectedLedgerID)
                {
                    Voucher.LedgerID = SelectedLedgerID;
                    Voucher.DefinitiveID = SelectedDefinitiveID;
                    if (radio_debit.IsChecked == true)
                    {
                        Voucher.Debit = Convert.ToDecimal(txt_Amount.Text);
                        Voucher.Credit = 0;
                    }
                    else if (radio_credit.IsChecked == true)
                    {
                        Voucher.Debit = 0;
                        Voucher.Credit = Convert.ToDecimal(txt_Amount.Text);
                    }
                    _VoucherDetail.Add(Voucher);
                }
            }
        }
        if (dg_VoucherDetail.HasItems == false)
        {
            Voucher.LedgerID = SelectedLedgerID;
            Voucher.DefinitiveID = SelectedDefinitiveID;
            if (radio_debit.IsChecked == true)
            {
                Voucher.Debit = Convert.ToDecimal(txt_Amount.Text);
                Voucher.Credit = 0;
            }
            else if (radio_credit.IsChecked == true)
            {
                Voucher.Debit = 0;
                Voucher.Credit = Convert.ToDecimal(txt_Amount.Text);
            }
            _VoucherDetail.Add(Voucher);
  //          dg_VoucherDetail.Items.Add(VoucherDetail);
        }
        dg_VoucherDetail.ItemsSource = _VoucherDetail;
    }

    internal class VoucherDetail
{
    public decimal LedgerID { get; set; }
    public decimal DefinitiveID { get; set; }
    public decimal Debit { get; set; }
    public decimal Credit { get; set; }
}

Body:
Here's a simple snippet which "updates" an entry if the entry is present in the collection. This snippet has things hard-coded but making it dynamic should be trivial.

using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Collections.ObjectModel;

namespace UpdateObservableCollection_47291451
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        DataGrid dg = new DataGrid();
        Button btn = new Button();
        ObservableCollection<VoucherDetail> datasource = new ObservableCollection<VoucherDetail>();
        public MainWindow()
        {
            InitializeComponent();
            dg.Height = 200;
            dg.Width = 500;
            MainGrid.Children.Add(dg);//add DataGrid to page
            btn.Content = "Click me";
            btn.Click += Btn_Click;
            btn.Height = 25;
            btn.Width = 50;
            MainGrid.Children.Add(btn);//add button to page

            dg.ItemsSource = datasource;//bind grid to data

            //create initial data records
            for (int i = 0; i < 5; i++)
            {
                datasource.Add(new UpdateObservableCollection_47291451.VoucherDetail { Credit = i, Debit = i, DefinitiveID = i, LedgerID = i });
            }
        }

        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            //if a record with DefinitiveID of 1 exist, then update the entry
            if (datasource.FirstOrDefault(p => p.DefinitiveID == 1) != null)
            {
                datasource.First(p => p.DefinitiveID == 1).Credit = 1234;
                dg.Items.Refresh();
            }
            else
            {
                datasource.Add(new UpdateObservableCollection_47291451.VoucherDetail { DefinitiveID = 99, Credit = 99, Debit = 99, LedgerID = 99 });
            }
        }
    }

    internal class VoucherDetail
    {
        public decimal LedgerID { get; set; }
        public decimal DefinitiveID { get; set; }
        public decimal Debit { get; set; }
        public decimal Credit { get; set; }
    }

}


问:
Compare two datetime values in a stored procedure using SQL Server?
Inside the stored procedure's SELECT statement, I have to get the max datetime value.

```<code>((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId)) as RecentDateTime,
</code>```

This works. I see the new column with the datetime value in the SQL Server Management Studio grid.

However, I need to compare this value with another datetime value to see if they are equal. I get a syntax error for the following statement inside the SELECT statement

```<code>((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId) = MM.MyDateTime) as RecentDateTime,
</code>```

Or:

```<code>@RecentDateTime = ((SELECT MAX(MyDateTime)
                    FROM MyTable
                    WHERE MyId = MM.MyId) = MM.MyDateTime)
</code>```

If I can store the result of the comparison to a variable, I can take this value and compare it to another value.

Not sure why I keep getting the syntax error or how to fix this. Any help is appreciated by a newbie.

答:
How about a correlated subquery?

```<code>select
     t.MyId
    ,t.MyDateTime
    ,RecentDateTime = (select max(t2.MyDateTime) from MyTable t2 where t2.MyId = t.MyId)
from
    MyTable t
</code>```

Or with a derived table...

```<code>select
    t.MyId
    ,t.MyDateTime
    ,RecentDateTime = t2.DT
from
    MyTable t
left join
    (select t2.MyId, max(t2.MyDateTime) DT from MyTable t2 group by t2.MyId) t2 on t2.MyId = t.MyId
</code>```

Then, if you wanted only the ones where they didn't match, you could wrap it in a CTE...

```<code>;with cte as(
    select
        t.MyId
        ,t.MyDateTime
        ,RecentDateTime = t2.DT
    from
        MyTable t
    left join
        (select t2.MyId, max(t2.MyDateTime) DT from MyTable t2 group by t2.MyId) t2 on t2.MyId = t.MyId)

select *
from cte
where MyDateTime <> RecentDateTime
</code>```

Body:
Inside the stored procedure's SELECT statement, I have to get the max datetime value.

((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId)) as RecentDateTime,

This works. I see the new column with the datetime value in the SQL Server Management Studio grid.

However, I need to compare this value with another datetime value to see if they are equal. I get a syntax error for the following statement inside the SELECT statement

((SELECT MAX(MyDateTime)
  FROM MyTable
  WHERE MyId = MM.MyId) = MM.MyDateTime) as RecentDateTime,

Or:

@RecentDateTime = ((SELECT MAX(MyDateTime)
                    FROM MyTable
                    WHERE MyId = MM.MyId) = MM.MyDateTime)

If I can store the result of the comparison to a variable, I can take this value and compare it to another value.

Not sure why I keep getting the syntax error or how to fix this. Any help is appreciated by a newbie.

Body:
How about a correlated subquery?

select
     t.MyId
    ,t.MyDateTime
    ,RecentDateTime = (select max(t2.MyDateTime) from MyTable t2 where t2.MyId = t.MyId)
from
    MyTable t

Or with a derived table...

select
    t.MyId
    ,t.MyDateTime
    ,RecentDateTime = t2.DT
from
    MyTable t
left join
    (select t2.MyId, max(t2.MyDateTime) DT from MyTable t2 group by t2.MyId) t2 on t2.MyId = t.MyId

Then, if you wanted only the ones where they didn't match, you could wrap it in a CTE...

;with cte as(
    select
        t.MyId
        ,t.MyDateTime
        ,RecentDateTime = t2.DT
    from
        MyTable t
    left join
        (select t2.MyId, max(t2.MyDateTime) DT from MyTable t2 group by t2.MyId) t2 on t2.MyId = t.MyId)

select *
from cte
where MyDateTime <> RecentDateTime


问:
Please explain this base 62 PHP conversion function/algorithm
Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

```<code>private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}
</code>```

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.

答:
A more pseudocodey version.</p>

```<code>// Maps some characters such that
//  0   ->'0'
//  9   ->'9'
//  10  ->'a'
//  35  ->'z'
//  36  ->'A'
//  61  ->'Z'
Let constant characters = List ('0'..'9', 'a'..'z', 'A'..'Z')
Let constant size = length of characters

Function LogBase(number base, number x)
    Return LogBase10(x) / LogBase10(base)

Function LeftMostPosition(unsigned integer message)
    Return Floor(LogBase(size,message))

Function ShiftRight(unsigned integer message, unsigned integer numberOfPositions)
    Return Floor(message / (size to the numberOfPositions power))

Function ShiftLeft(unsigned integer message, unsigned integer numberOfPositions)
    Return message * (size to the numberOfPositions power)

Function Decode(unsigned integer message)
    Let var buffer be a string buffer

    // Runs a number of times equal to LeftMostPosition(message) + 1
    Count position from LeftMostPosition(message) down through 0
        // Get the symbol from the left side of the message
        Let var index = ShiftRight(message, position)
        // Add the decoded character
        To buffer, add characters[index]
        // And then remove it from the incoming message
        Let message = message - ShiftLeft(index, position)

    Return contents of buffer
</code>```

Body:
Could anyone please explain the code below? That or point me to some resources shedding some light :)

It converts an integer to a base62 string.

private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

private static function _convertBase($num)
{
    $base = strlen(self::$_characters);
    $string = '';

    for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
        $a = floor($num / pow($base, $t));
        $string .= substr(self::$_characters, $a, 1);
        $num = $num - ($a * pow($base, $t));
    }

    return $string;
}

Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.

Body:
A more pseudocodey version.

// Maps some characters such that
//  0   ->'0'
//  9   ->'9'
//  10  ->'a'
//  35  ->'z'
//  36  ->'A'
//  61  ->'Z'
Let constant characters = List ('0'..'9', 'a'..'z', 'A'..'Z')
Let constant size = length of characters

Function LogBase(number base, number x)
    Return LogBase10(x) / LogBase10(base)

Function LeftMostPosition(unsigned integer message)
    Return Floor(LogBase(size,message))

Function ShiftRight(unsigned integer message, unsigned integer numberOfPositions)
    Return Floor(message / (size to the numberOfPositions power))

Function ShiftLeft(unsigned integer message, unsigned integer numberOfPositions)
    Return message * (size to the numberOfPositions power)

Function Decode(unsigned integer message)
    Let var buffer be a string buffer

    // Runs a number of times equal to LeftMostPosition(message) + 1
    Count position from LeftMostPosition(message) down through 0
        // Get the symbol from the left side of the message
        Let var index = ShiftRight(message, position)
        // Add the decoded character
        To buffer, add characters[index]
        // And then remove it from the incoming message
        Let message = message - ShiftLeft(index, position)

    Return contents of buffer


问:
Splitting words for .rtf file
I would like make a program in Python which will take a .rtf file or input text and add /- sing in words after a, e, i, o, u so when you load text back in Word, words will split at certain situations.

e.g. When you reduce margins

```<code>Some random te-
 xt in microso-
 ft office.
</code>```

But when you stretch text it should look normal.
Some random text in Microsoft Office.
Any suggestions how to split sentences in letters and then add /- after a, e, i, o, u?

答:
I'm not sure I understand the task. But if you want to add a hyphen after each vowel you encounter in a string, something like this could work:

s = "Some random text in Microsoft Office"

Vowels = "aeiou"

new_s=""

for char in s:

```<code> if char.lower() in Vowels:

      char=char+"-"

      new_s +=char

 else:

      new_s +=char
</code>```

print(new_s)

ContentLicense: CC BY-SA 4.0

Title: Splitting words for .rtf file

Body:
I would like make a program in Python which will take a .rtf file or input text and add /- sing in words after a, e, i, o, u so when you load text back in Word, words will split at certain situations.

e.g. When you reduce margins

Some random te-
 xt in microso-
 ft office.

But when you stretch text it should look normal.
Some random text in Microsoft Office.
Any suggestions how to split sentences in letters and then add /- after a, e, i, o, u?

Body:
I'm not sure I understand the task. But if you want to add a hyphen after each vowel you encounter in a string, something like this could work:

s = "Some random text in Microsoft Office"

Vowels = "aeiou"

new_s=""

for char in s:

 if char.lower() in Vowels:

      char=char+"-"

      new_s +=char

 else:

      new_s +=char

print(new_s)


问:
RNN can't learn integral function
For studying deep learning, RNN, LSTM and so on I tried to make RNN fit integration function. I have put random signal from 0 to 1 as input to RNN and made integral from biased by -0.5 input signal, made the limit for integral between 0:1 and put it as RNN target to learn. Blue - random input, orange - integrated input

So I have time series with only one input (random) and one output (limited integral of input) and I want RNN to predict output by the input.
I used Pytorch and tried to use vanilla RNN, GRU cell, different sizes of hidden layers, stacking several RNN, putting dense connected layers to the RNN output, different deep in backpropagation through time (from 2 to 50 gradients rolling-back). And I can't get a good result at all! It works somehow, but I can't find a way to fit integral function precisely. Here is the best of my results:
green - RNN output. Green line (model output) does not fit orange line in many cases - that is the problem.

Here is my source code in jupyter.
My questions: is it possible - to learn a saturated integral function by RNN? Where is my problem? What can I try more to achieve good quality? Ideally I want to RNN output be equal desired output (integral function) through all time series.

PS:
My code in raw format:

```<code>import numpy as np
from scipy.stats import truncnorm
import random
import math
import copy
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.cm as cm

def generate_data(num_of_data):
    input_data=[]
    output_data=[]
    current_input_value=0
    current_output_value=0
    for i in range(num_of_data):
        if (random.random()<0.1):
            current_input_value=random.random()
#            current_output_value=0
        current_input_value=current_input_value+(random.random()-0.5)*0
        current_output_value=current_output_value+0.0*(current_input_value-current_output_value)+(current_input_value-0.5)*0.1
        if (current_output_value<0):
            current_output_value=0
        if (current_output_value>1):
            current_output_value=1

        input_data.append(current_input_value)
        output_data.append(current_output_value)
    return input_data,output_data

%matplotlib inline
matplotlib.rcParams['figure.figsize'] = (20, 6)

input_data,output_data=generate_data(500)
plt.plot(input_data)
plt.plot(output_data)
plt.show()

import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim

class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(RNN, self).__init__()
        self.number_of_layers=1
        self.hidden_size = hidden_size
        self.gru = nn.GRU(input_size, hidden_size,self.number_of_layers)
        self.Dense1 = nn.Linear(hidden_size, hidden_size)
        self.Dense1A = nn.ReLU()
        self.Dense2 = nn.Linear(hidden_size, output_size)

    def forward(self, input, hidden):
        gru_output, hidden = self.gru(input, hidden)
        Dense1Out=self.Dense1(gru_output)
        Dense1OutAct=self.Dense1A(Dense1Out)
        output=self.Dense2(Dense1OutAct)
        return output, hidden

    def initHidden(self):
        return Variable(torch.zeros(self.number_of_layers,1,self.hidden_size))

import time
import math
import operator

def timeSince(since):
    now = time.time()
    s = now - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s)
rnn = RNN(1, 50, 1)

n_iters = 250000
print_every = 2000
plot_every = 2000
all_losses = []
total_loss_print = 0
total_loss_plot = 0

criterion=nn.L1Loss()

print("training...\n")

start = time.time()
optimizer = optim.Adam(rnn.parameters(), lr=0.0002)
rnn_hidden = rnn.initHidden()
rnn.zero_grad()
loss = 0
#for gata_q in range(int(n_iters/500)):
#    rnn_hidden = rnn.initHidden()

input_data,output_data=generate_data(n_iters)
for data_index in range(len(input_data)):
    input_tensor=torch.zeros(1, 1, 1)
    input_tensor[0][0][0]=input_data[data_index]

    output_tensor=torch.zeros(1, 1, 1)
    output_tensor[0][0][0]=output_data[data_index]

    rnn_output, rnn_hidden = rnn(Variable(input_tensor), rnn_hidden)
    loss += criterion(rnn_output, Variable(output_tensor))

    if data_index%2==0:
        loss.backward()

        total_loss_print += loss.data[0]
        total_loss_plot += loss.data[0]
        optimizer.step()
        rnn_hidden=Variable(rnn_hidden.data)
        rnn.zero_grad()
        loss = 0

    if data_index % print_every == 0:
        print('%s (%d %d%%) tl=%.4f' % (timeSince(start), data_index, data_index / n_iters * 100,total_loss_print/print_every))
        total_loss_print = 0

    if data_index % plot_every == 0:
        all_losses.append(total_loss_plot / plot_every)
        total_loss_plot = 0

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.figure()
plt.plot(all_losses)
plt.show()

rnn_hidden = rnn.initHidden()

rnn.zero_grad()
loss = 0

rnn_output_data=[]
input_data,output_data=generate_data(1500)
for data_index in range(len(input_data)):
    input_tensor=torch.zeros(1, 1, 1)
    input_tensor[0][0][0]=input_data[data_index]
    rnn_output, rnn_hidden = rnn(Variable(input_tensor), rnn_hidden)
    rnn_output_data.append(rnn_output.data.numpy()[0][0][0])

plt.plot(input_data)#blue
plt.plot(output_data)#ogange
plt.plot(rnn_output_data)#green
plt.show()
</code>```

答:
I have found the problem by myself. The problem was in some case of overfitting on latest data, as in reinforcement learning case overfitting can occur with exploiting latest strategy. As I was not using any mini-batches and applied optimiser directly after a new point of data, and as because of data points similar through 20-50 of samples, optimiser simply fitted network to only latest points forgetting of fitting previous. I solved it by collecting gradient data through time for 50 points and only after it I apply one step of optimiser. The network can learn now much better, but still not perfect.

Here is modification of code to make it work:

```<code>rnn_output, rnn_hidden = rnn(Variable(input_tensor), rnn_hidden)

loss += criterion(rnn_output, Variable(output_tensor))

if data_index % 2==0:
    loss.backward()
    total_loss_print += loss.data[0]
    rnn_hidden=Variable(rnn_hidden.data)
    loss = 0
   # torch.nn.utils.clip_grad_norm(rnn.parameters(), 0.01)
if data_index % 50==0:
    optimizer.step()
    rnn.zero_grad()
</code>```

and new result of learning of integral:
pic.

Title: RNN can't learn integral function

Body:
For studying deep learning, RNN, LSTM and so on I tried to make RNN fit integration function. I have put random signal from 0 to 1 as input to RNN and made integral from biased by -0.5 input signal, made the limit for integral between 0:1 and put it as RNN target to learn. Blue - random input, orange - integrated input

So I have time series with only one input (random) and one output (limited integral of input) and I want RNN to predict output by the input.
I used Pytorch and tried to use vanilla RNN, GRU cell, different sizes of hidden layers, stacking several RNN, putting dense connected layers to the RNN output, different deep in backpropagation through time (from 2 to 50 gradients rolling-back). And I can't get a good result at all! It works somehow, but I can't find a way to fit integral function precisely. Here is the best of my results:
green - RNN output. Green line (model output) does not fit orange line in many cases - that is the problem.

Here is my source code in jupyter.
My questions: is it possible - to learn a saturated integral function by RNN? Where is my problem? What can I try more to achieve good quality? Ideally I want to RNN output be equal desired output (integral function) through all time series.

PS:
My code in raw format:

import numpy as np
from scipy.stats import truncnorm
import random
import math
import copy
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.cm as cm

def generate_data(num_of_data):
    input_data=[]
    output_data=[]
    current_input_value=0
    current_output_value=0
    for i in range(num_of_data):
        if (random.random()<0.1):
            current_input_value=random.random()
#            current_output_value=0
        current_input_value=current_input_value+(random.random()-0.5)*0
        current_output_value=current_output_value+0.0*(current_input_value-current_output_value)+(current_input_value-0.5)*0.1
        if (current_output_value<0):
            current_output_value=0
        if (current_output_value>1):
            current_output_value=1

        input_data.append(current_input_value)
        output_data.append(current_output_value)
    return input_data,output_data

%matplotlib inline
matplotlib.rcParams['figure.figsize'] = (20, 6)

input_data,output_data=generate_data(500)
plt.plot(input_data)
plt.plot(output_data)
plt.show()

import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim

class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(RNN, self).__init__()
        self.number_of_layers=1
        self.hidden_size = hidden_size
        self.gru = nn.GRU(input_size, hidden_size,self.number_of_layers)
        self.Dense1 = nn.Linear(hidden_size, hidden_size)
        self.Dense1A = nn.ReLU()
        self.Dense2 = nn.Linear(hidden_size, output_size)

    def forward(self, input, hidden):
        gru_output, hidden = self.gru(input, hidden)
        Dense1Out=self.Dense1(gru_output)
        Dense1OutAct=self.Dense1A(Dense1Out)
        output=self.Dense2(Dense1OutAct)
        return output, hidden

    def initHidden(self):
        return Variable(torch.zeros(self.number_of_layers,1,self.hidden_size))

import time
import math
import operator

def timeSince(since):
    now = time.time()
    s = now - since
    m = math.floor(s / 60)
    s -= m * 60
    return '%dm %ds' % (m, s)
rnn = RNN(1, 50, 1)

n_iters = 250000
print_every = 2000
plot_every = 2000
all_losses = []
total_loss_print = 0
total_loss_plot = 0

criterion=nn.L1Loss()

print("training...\n")

start = time.time()
optimizer = optim.Adam(rnn.parameters(), lr=0.0002)
rnn_hidden = rnn.initHidden()
rnn.zero_grad()
loss = 0
#for gata_q in range(int(n_iters/500)):
#    rnn_hidden = rnn.initHidden()

input_data,output_data=generate_data(n_iters)
for data_index in range(len(input_data)):
    input_tensor=torch.zeros(1, 1, 1)
    input_tensor[0][0][0]=input_data[data_index]

    output_tensor=torch.zeros(1, 1, 1)
    output_tensor[0][0][0]=output_data[data_index]

    rnn_output, rnn_hidden = rnn(Variable(input_tensor), rnn_hidden)
    loss += criterion(rnn_output, Variable(output_tensor))

    if data_index%2==0:
        loss.backward()

        total_loss_print += loss.data[0]
        total_loss_plot += loss.data[0]
        optimizer.step()
        rnn_hidden=Variable(rnn_hidden.data)
        rnn.zero_grad()
        loss = 0

    if data_index % print_every == 0:
        print('%s (%d %d%%) tl=%.4f' % (timeSince(start), data_index, data_index / n_iters * 100,total_loss_print/print_every))
        total_loss_print = 0

    if data_index % plot_every == 0:
        all_losses.append(total_loss_plot / plot_every)
        total_loss_plot = 0

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

plt.figure()
plt.plot(all_losses)
plt.show()

rnn_hidden = rnn.initHidden()

rnn.zero_grad()
loss = 0

rnn_output_data=[]
input_data,output_data=generate_data(1500)
for data_index in range(len(input_data)):
    input_tensor=torch.zeros(1, 1, 1)
    input_tensor[0][0][0]=input_data[data_index]
    rnn_output, rnn_hidden = rnn(Variable(input_tensor), rnn_hidden)
    rnn_output_data.append(rnn_output.data.numpy()[0][0][0])

plt.plot(input_data)#blue
plt.plot(output_data)#ogange
plt.plot(rnn_output_data)#green
plt.show()

Body:
I have found the problem by myself. The problem was in some case of overfitting on latest data, as in reinforcement learning case overfitting can occur with exploiting latest strategy. As I was not using any mini-batches and applied optimiser directly after a new point of data, and as because of data points similar through 20-50 of samples, optimiser simply fitted network to only latest points forgetting of fitting previous. I solved it by collecting gradient data through time for 50 points and only after it I apply one step of optimiser. The network can learn now much better, but still not perfect.

Here is modification of code to make it work:

rnn_output, rnn_hidden = rnn(Variable(input_tensor), rnn_hidden)

loss += criterion(rnn_output, Variable(output_tensor))

if data_index % 2==0:
    loss.backward()
    total_loss_print += loss.data[0]
    rnn_hidden=Variable(rnn_hidden.data)
    loss = 0
   # torch.nn.utils.clip_grad_norm(rnn.parameters(), 0.01)
if data_index % 50==0:
    optimizer.step()
    rnn.zero_grad()

and new result of learning of integral:
pic.


问:
(React-Navigation) Called redux action many times on when screen loading
Hi when I enter screen with TabNavigator (have 5 tabs) and one of them is calling redux action on componentWillMount. But the weird things is why it never stop calling the action.

答:
This usually happens when you are calling setState from inside a lifecycle method. It sets off a chain reaction because the component re-renders when Redux updates, and re-rendering causes Redux to update.

I would imagine this is the source of your problem.

To fix it, you will need to improve how it is setting the state, such as updating only the field that is needed, or making the component only listen to that one field, or not updating it there.

You could also add conditionals, such as if (this && this) dont update

Also very good to investigate is if (props === nextProps) dont update

You might need to look at shouldComponentUpdate lifecycle method, but I would say generally, that should be avoided because it can create strange bugs that are hard to track down.


问:
How to Display VS Code output window to side rather than below
In my VS Code set up I see the output/FSI frame below the main text editor pane like this:

whereas I would love it to appear to the right in the side-by-side view like it does on the images in this link: http://www.wintellect.com/devcenter/jwood/a-quick-look-at-f-in-visual-studio-code

Is there a config option I cannot find somewhere?

I tried Googling but drew a blank and cannot see anything obvious in the config options mentioned on the vs code site page describing the config options

答:
This feature is available from version 1.18.0+

Simply click this icon to dock to the right:


问:
Grails: how to set language dynamically in gsp or using js
I want to set language value of a gsp page dynamically .  Currently I am just doing it using basic hardcoded value . I did find something with JS Onload event described here.

But I wanted to find something that is GSP driven . Is there any way ?

My current code looks like

答:
I think maybe you are thinking of this in a more complex way than it actuall is.

In grails you have your layouts/main.gsp which is your sitemesh.

The tag <html lang='en' is declared at the very top of this

If you simply edit this page and add the following:

```<code><g:set var="locale" value="${session?.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'?:java.util.Locale.UK}"/>
<html lang="${locale?.language?:'en'}" class="no-js">
</code>```

Then when I visit my site:
localhost:8080/?lang=ja_JP  view source shows:

You need to do that for each sitemesh that requires to do this - having a read about this property it seems it doesn't do much for the browser but may help non human things such as search engines.

Body:
I think maybe you are thinking of this in a more complex way than it actuall is.

In grails you have your layouts/main.gsp which is your sitemesh.

The tag <html lang='en' is declared at the very top of this

If you simply edit this page and add the following:

<g:set var="locale" value="${session?.'org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE'?:java.util.Locale.UK}"/>
<html lang="${locale?.language?:'en'}" class="no-js">

Then when I visit my site:
localhost:8080/?lang=ja_JP  view source shows:
<html lang="ja" class="no-js">

You need to do that for each sitemesh that requires to do this - having a read about this property it seems it doesn't do much for the browser but may help non human things such as search engines.


问:
Returning Dynamic Content-Type via AWS API Gateway and Lambda Function
I want to use an AWS API Gateway as a proxy for fetching files from an S3 bucket and returning them to the client. I'm using a Lambda function to talk to S3 and send the file to the client via the AWS API Gateway. I've rad that the best way to do this is to use a "Lambda proxy integration" so the entire request gets piped to Lambda without any modification. But if I do that then I can't setup an Integration Response for the resulting response from my Lambda function. So all the client gets is JSON.

It seems there should be a way for the API Gateway to take the JSON and transform the request to the proper response for the client but I can't seem to figure out how to make that happen. There are lots of examples that point to setting a content-type on the response from the API Gateway manually but I need to set the content-type header to whatever the file type is.

Also for images and binary formats my Lambda function is returning a base64 encoded string and the property isBase64Encoded set to true. When I go to the "Binary Support" section and specify something like image/* as a content type that should be returned as binary, it doesn't work. I only have success by setting the Binary Support content type to */* (aka everything) which won't work for non-binary content types.

What am I missing and why does this seem so difficult?

答:
Turns out API Gateway isn't the problem. My Lambda function wasn't returning proper headers.

For handling binary responses I found you need to set Binary Support content type to */* (aka everything) and then have your Lambda function return the property isBase64Encoded set to true. Responses that are base64 encoded and indicated as such will be decoded and served as binary while other requests will be returned as is.

Here's a simple Gist for a Lambda function that takes a given path and reads the file from S3 and returns it via the API Gateway:

```<code>/**
 * This is a simple AWS Lambda function that will look for a given file on S3 and return it
 * passing along all of the headers of the S3 file. To make this available via a URL use
 * API Gateway with an AWS Lambda Proxy Integration.
 *
 * Set the S3_REGION and S3_BUCKET global parameters in AWS Lambda
 * Make sure the Lambda function is passed an object with `{ pathParameters : { proxy: 'path/to/file.jpg' } }` set
 */

var AWS = require('aws-sdk');

exports.handler = function( event, context, callback ) {
    var region = process.env.S3_REGION;
    var bucket = process.env.S3_BUCKET;
    var key = decodeURI( event.pathParameters.proxy );

    // Basic server response
    /*
    var response = {
        statusCode: 200,
        headers: {
            'Content-Type': 'text/plain',
        },
        body: "Hello world!",
    };
    callback( null, response );
    */

    // Fetch from S3
    var s3 = new AWS.S3( Object.assign({ region: region }) );
    return s3.makeUnauthenticatedRequest(
        'getObject',
        { Bucket: bucket, Key: key },
        function(err, data) {
            if (err) {
                return err;
            }

            var isBase64Encoded = false;
            if ( data.ContentType.indexOf('image/') > -1 ) {
                isBase64Encoded = true;
            }

            var encoding = '';
            if ( isBase64Encoded ) {
                encoding = 'base64'
            }
            var resp = {
                statusCode: 200,
                headers: {
                    'Content-Type': data.ContentType,
                },
                body: new Buffer(data.Body).toString(encoding),
                isBase64Encoded: isBase64Encoded
            };

            callback(null, resp);
        }
    );
};
</code>```

via https://gist.github.com/kingkool68/26aa7a3641a3851dc70ce7f44f589350

Body:
Turns out API Gateway isn't the problem. My Lambda function wasn't returning proper headers.

For handling binary responses I found you need to set Binary Support content type to */* (aka everything) and then have your Lambda function return the property isBase64Encoded set to true. Responses that are base64 encoded and indicated as such will be decoded and served as binary while other requests will be returned as is.

Here's a simple Gist for a Lambda function that takes a given path and reads the file from S3 and returns it via the API Gateway:

/**
 * This is a simple AWS Lambda function that will look for a given file on S3 and return it
 * passing along all of the headers of the S3 file. To make this available via a URL use
 * API Gateway with an AWS Lambda Proxy Integration.
 *
 * Set the S3_REGION and S3_BUCKET global parameters in AWS Lambda
 * Make sure the Lambda function is passed an object with `{ pathParameters : { proxy: 'path/to/file.jpg' } }` set
 */

var AWS = require('aws-sdk');

exports.handler = function( event, context, callback ) {
    var region = process.env.S3_REGION;
    var bucket = process.env.S3_BUCKET;
    var key = decodeURI( event.pathParameters.proxy );

    // Basic server response
    /*
    var response = {
        statusCode: 200,
        headers: {
            'Content-Type': 'text/plain',
        },
        body: "Hello world!",
    };
    callback( null, response );
    */

    // Fetch from S3
    var s3 = new AWS.S3( Object.assign({ region: region }) );
    return s3.makeUnauthenticatedRequest(
        'getObject',
        { Bucket: bucket, Key: key },
        function(err, data) {
            if (err) {
                return err;
            }

            var isBase64Encoded = false;
            if ( data.ContentType.indexOf('image/') > -1 ) {
                isBase64Encoded = true;
            }

            var encoding = '';
            if ( isBase64Encoded ) {
                encoding = 'base64'
            }
            var resp = {
                statusCode: 200,
                headers: {
                    'Content-Type': data.ContentType,
                },
                body: new Buffer(data.Body).toString(encoding),
                isBase64Encoded: isBase64Encoded
            };

            callback(null, resp);
        }
    );
};

via https://gist.github.com/kingkool68/26aa7a3641a3851dc70ce7f44f589350


问:
Selecting Cell Value from Filtered Table
I have a macro that goes through a Table and picks out the value I want value want ("ref") from Col 5 which is then used in rest of code.

```<code>Dim Lobj As ListObject

Set Lobj = SourceBk.Sheets("RefSheet2_x").ListObjects("Table1")

For x = 1 To Lobj.DataBodyRange.Rows.Count

   Ref = Lobj.DataBodyRange(x, 5)

Next x
</code>```

What I need is to be able to run the code so it works on just the visible rows when the Table is filtered (normally filter will be in on Col 2 but may include filters on other cols). My current code ignores any filtering I have applied and works on the whole Table.

Any help appreciated!

答:
You want to check the entire row's Hidden property. Something along those lines:

```<code>Public Sub Answer()
    Dim Lobj As ListObject
    Dim Ref As Variant
    Dim x As Long

    Set Lobj = SourceBk.Sheets("RefSheet2_x").ListObjects("Table1")

    With Lobj
        For x = 1 To .DataBodyRange.Rows.Count
            If Not .DataBodyRange.Rows(x).EntireRow.Hidden Then
                Ref = .DataBodyRange(x, 5).Value
                '...
            End If
        Next
    End With
End Sub
</code>```

Body:
I have a macro that goes through a Table and picks out the value I want value want ("ref") from Col 5 which is then used in rest of code.

Dim Lobj As ListObject

Set Lobj = SourceBk.Sheets("RefSheet2_x").ListObjects("Table1")

For x = 1 To Lobj.DataBodyRange.Rows.Count

   Ref = Lobj.DataBodyRange(x, 5)

Next x

What I need is to be able to run the code so it works on just the visible rows when the Table is filtered (normally filter will be in on Col 2 but may include filters on other cols). My current code ignores any filtering I have applied and works on the whole Table.

Any help appreciated!

Body:
You want to check the entire row's Hidden property. Something along those lines:

Public Sub Answer()
    Dim Lobj As ListObject
    Dim Ref As Variant
    Dim x As Long

    Set Lobj = SourceBk.Sheets("RefSheet2_x").ListObjects("Table1")

    With Lobj
        For x = 1 To .DataBodyRange.Rows.Count
            If Not .DataBodyRange.Rows(x).EntireRow.Hidden Then
                Ref = .DataBodyRange(x, 5).Value
                '...
            End If
        Next
    End With
End Sub


问:
Create a new play scala project shows error in eclipse
I am new to play framework(Scala),I created a new project using
activator new sample play-scala command, sample is my project name.Then I successfully ran a project using activator run command .When I ran a activator eclipse command it showed

```<code>[error] Not a valid command: eclipse (similar: help, alias)
[error] Not a valid project ID: eclipse
[error] Expected ':'
[error] Not a valid key: eclipse (similar: deliver, licenses, clean)
[error] eclipse
</code>```

So from some internet suggestions I added

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0")

this line into my sample project's plugins.sbt file.This fixed the not a valid command error but When I imported a project into eclipse it showed a
object index is not a member of package views.html error please help me to fix the error

plugins.sbt

```<code>// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.4.0")

// web plugins

addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.0.6")

addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.3")

addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.7")

addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0")

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0")
</code>```

答:
i had the same issue upgrading from play 2.3 to play 2.5, just added addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0") to plugins.sbt but still having error Not a valid command: eclipse

So i realized that i had another sbt file under /project 'activator-sbt-eclipse-shim.sbt', i don't know why it was there but it was using and old version addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.3.0")

i just changed that file to the right version and it worked

Body:
I am new to play framework(Scala),I created a new project using
activator new sample play-scala command, sample is my project name.Then I successfully ran a project using activator run command .When I ran a activator eclipse command it showed

[error] Not a valid command: eclipse (similar: help, alias)
[error] Not a valid project ID: eclipse
[error] Expected ':'
[error] Not a valid key: eclipse (similar: deliver, licenses, clean)
[error] eclipse

So from some internet suggestions I added

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0")

this line into my sample project's plugins.sbt file.This fixed the not a valid command error but When I imported a project into eclipse it showed a
object index is not a member of package views.html error please help me to fix the error

plugins.sbt

// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.4.0")

// web plugins

addSbtPlugin("com.typesafe.sbt" % "sbt-coffeescript" % "1.0.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-less" % "1.0.6")

addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.3")

addSbtPlugin("com.typesafe.sbt" % "sbt-rjs" % "1.0.7")

addSbtPlugin("com.typesafe.sbt" % "sbt-digest" % "1.1.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-mocha" % "1.1.0")

addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0")


问:
Selecting only ngrams based on the first word in rstudio
I'm currentley working on a nlp-project. As a training data set I'm using the Bible. You can easily create a random corpus with, if you want to try it yourself:

```<code>rcorpus(nwords = 50, alphabet = letters, minwordlen = 1, maxwordlen = 6)
</code>```

After processing the text file, I'm dividing the corpus into n-grams with ngram-package

```<code>library(ngram)
# this is a preproccsed Corpus I have created earlier

bible_corpus<- Corpus(DirSource("C:/Users/XYZ/XYZ/"))
</code>```

Now I'm processing the corpus with a function, I have set up earlier.

```<code>corpus_sentences <- Text_To_Clean_Sentences(paste(bible_corpus, collapse=" "))
</code>```

Next step is to make a function for splitting our corpus into ngram

```<code># function for getting n-grams
Get_Ngrams <- function(sentence_splits, ngram_size=2) {
ngrams <- c()
for (sentence in sentence_splits) {
sentence <- Trim(sentence)
if ((nchar(sentence) > 0) && (sapply(gregexpr("\\W+", sentence), length) >=
ngram_size)) {
    ngs <- ngram(sentence , n=ngram_size)
    ngrams <- c(ngrams, get.ngrams(ngs))
     }
}
 return (ngrams)
}

# making n-grams based on Get_Ngrams
n2 <- Get_Ngrams(corpus_sentences, ngram_size=2)
n3 <- Get_Ngrams(corpus_sentences, ngram_size=3)
n4 <- Get_Ngrams(corpus_sentences, ngram_size=4)
n5 <- Get_Ngrams(corpus_sentences, ngram_size=5)

# collect all n-grams
n_all <- c(n5,n4,n3,n2)
</code>```

Time to enter a search term

```<code># enter SEARCH Word
word <- 'good '

#
matches <- c()
for (sentence in n_all) {
# find exact match with double backslash and escape
if (grepl(paste0('\\<',word), sentence)) {
print(sentence)
matches <- c(matches, sentence)
}
}

# find highest probability word
precision_match <- c()
for (a_match in matches) {
# how many spaces in from of search word
precision_match <- c(precision_match,nchar(strsplit(x = a_match, split =
word)[[1]][[1]]))
}
</code>```

The last step returns all ngrams, which contain our search word from line
    29,
Now i want to remove all sentence which dont start with search word we have entered.

for example "precision_match" returns:

```<code>[1] search_word wordX wordY wordZ
[2] search_word wordY wordX wordZ
[3] wordY search_word wordX wordZ
[4] wordY wordX wordZ search_word
</code>```

Of course I could manually select [1] und [2] since I can see that these two lines start with our search_word. But this isn't pratical with a big number of matches. So how can I extracte the n-grams starting with our search_word?

答:
I run your code and don't know why you use the last part with the precision_match...
It basically gives you the difference in positions of the search word from the beginning of the string. Your question however seems to be tackled at a step earlier (matches).

Try

```<code>set.seed(33)
test <- rcorpus(nwords = 50, alphabet = letters, minwordlen = 1, maxwordlen = 6)

Get_Ngrams <- function(sentence_splits, ngram_size=2) {
  ngrams <- c()
  for (sentence in sentence_splits) {
    sentence <- trimws(sentence)
    if ((nchar(sentence) > 0) && (sapply(gregexpr("\\W+", sentence), length) >=
                              ngram_size)) {
      ngs <- ngram(sentence , n=ngram_size)
      ngrams <- c(ngrams, get.ngrams(ngs))
    }
  }
  return (ngrams)
}

ngram2 <- Get_Ngrams(test,2)
ngram3 <- Get_Ngrams(test,3)
n_all <- c(ngram2,ngram3)

word <- 'ghpbw'

matches <- c()
for (sentence in n_all) {
  # find exact match with double backslash and escape
  if (grepl(paste0('\\<',word), sentence)) {
    print(sentence)
    matches <- c(matches, sentence)
  }
}

matches[grepl(pattern = paste0("^",word), matches)]
</code>```

which results in the ngrams starting with the search word ghpbw [1] "ghpbw zbaiou"       "ghpbw zbaiou ffrpj" discarding [1] "wil ghpbw"        "dxjv wil ghpbw"   "wil ghpbw zbaiou"

Body:
I'm currentley working on a nlp-project. As a training data set I'm using the Bible. You can easily create a random corpus with, if you want to try it yourself:

rcorpus(nwords = 50, alphabet = letters, minwordlen = 1, maxwordlen = 6)

After processing the text file, I'm dividing the corpus into n-grams with ngram-package

library(ngram)
# this is a preproccsed Corpus I have created earlier

bible_corpus<- Corpus(DirSource("C:/Users/XYZ/XYZ/"))

Now I'm processing the corpus with a function, I have set up earlier.

corpus_sentences <- Text_To_Clean_Sentences(paste(bible_corpus, collapse=" "))

Next step is to make a function for splitting our corpus into ngram

# function for getting n-grams
Get_Ngrams <- function(sentence_splits, ngram_size=2) {
ngrams <- c()
for (sentence in sentence_splits) {
sentence <- Trim(sentence)
if ((nchar(sentence) > 0) && (sapply(gregexpr("\\W+", sentence), length) >=
ngram_size)) {
    ngs <- ngram(sentence , n=ngram_size)
    ngrams <- c(ngrams, get.ngrams(ngs))
     }
}
 return (ngrams)
}

# making n-grams based on Get_Ngrams
n2 <- Get_Ngrams(corpus_sentences, ngram_size=2)
n3 <- Get_Ngrams(corpus_sentences, ngram_size=3)
n4 <- Get_Ngrams(corpus_sentences, ngram_size=4)
n5 <- Get_Ngrams(corpus_sentences, ngram_size=5)

# collect all n-grams
n_all <- c(n5,n4,n3,n2)

Time to enter a search term

# enter SEARCH Word
word <- 'good '

#
matches <- c()
for (sentence in n_all) {
# find exact match with double backslash and escape
if (grepl(paste0('\\<',word), sentence)) {
print(sentence)
matches <- c(matches, sentence)
}
}

# find highest probability word
precision_match <- c()
for (a_match in matches) {
# how many spaces in from of search word
precision_match <- c(precision_match,nchar(strsplit(x = a_match, split =
word)[[1]][[1]]))
}

The last step returns all ngrams, which contain our search word from line
    29,
Now i want to remove all sentence which dont start with search word we have entered.

for example "precision_match" returns:

[1] search_word wordX wordY wordZ
[2] search_word wordY wordX wordZ
[3] wordY search_word wordX wordZ
[4] wordY wordX wordZ search_word

Of course I could manually select [1] und [2] since I can see that these two lines start with our search_word. But this isn't pratical with a big number of matches. So how can I extracte the n-grams starting with our search_word?

Body:
I run your code and don't know why you use the last part with the precision_match...
It basically gives you the difference in positions of the search word from the beginning of the string. Your question however seems to be tackled at a step earlier (matches).

Try

set.seed(33)
test <- rcorpus(nwords = 50, alphabet = letters, minwordlen = 1, maxwordlen = 6)

Get_Ngrams <- function(sentence_splits, ngram_size=2) {
  ngrams <- c()
  for (sentence in sentence_splits) {
    sentence <- trimws(sentence)
    if ((nchar(sentence) > 0) && (sapply(gregexpr("\\W+", sentence), length) >=
                              ngram_size)) {
      ngs <- ngram(sentence , n=ngram_size)
      ngrams <- c(ngrams, get.ngrams(ngs))
    }
  }
  return (ngrams)
}

ngram2 <- Get_Ngrams(test,2)
ngram3 <- Get_Ngrams(test,3)
n_all <- c(ngram2,ngram3)

word <- 'ghpbw'

matches <- c()
for (sentence in n_all) {
  # find exact match with double backslash and escape
  if (grepl(paste0('\\<',word), sentence)) {
    print(sentence)
    matches <- c(matches, sentence)
  }
}

matches[grepl(pattern = paste0("^",word), matches)]

which results in the ngrams starting with the search word ghpbw [1] "ghpbw zbaiou"       "ghpbw zbaiou ffrpj" discarding [1] "wil ghpbw"        "dxjv wil ghpbw"   "wil ghpbw zbaiou"


问:
Is it possible to hide a page in a PDF document using javascript?
Is it possible to hide a page in a PDF document using javascript?</p>

答:
HTML JavaScript cannot access objects within a PDF file.

This might be a start for you on the Acrobat Javascript
http://partners.adobe.com/public/developer/en/acrobat/sdk/AcroJSGuide.pdf

How can I hide an Acrobat form field based on the value of another?

Use the display method of the Global object:

```<code>var title = this.getField("title");
if (this.getField("showTitle").value == "Off")
title.display = display.hidden;
else
title.display = display.visible;
</code>```

Body:
HTML JavaScript cannot access objects within a PDF file.

This might be a start for you on the Acrobat Javascript
http://partners.adobe.com/public/developer/en/acrobat/sdk/AcroJSGuide.pdf

How can I hide an Acrobat form field based on the value of another?

Use the display method of the Global object:

var title = this.getField("title");
if (this.getField("showTitle").value == "Off")
title.display = display.hidden;
else
title.display = display.visible;


问:
R Shiny mouseover behavior differs for addCircles vs. addCircleMarkers
I have a map where icons are plotted based on mouseover coordinates. When I changed my markers from addCircles() to addCircleMarkers, however, it stopped functioning. Here's a code snippet that shows the problem. Comment out the addCircles line to see how the behavior changes.

```<code>library(shiny)
library(leaflet)

#create test data
dataset <- structure(list(LATITUDE = c(37.09719065, 37.11063138, 37.1132722,
                                 37.0749196, 37.02980937, 36.98644663,
                                 36.94062755, 36.89560073, 36.85363852),
                    LONGITUDE = c(283.6828216, 283.7335099, 283.7892219,
                                  283.813835, 283.812904, 283.7935855,
                                  283.7740784, 283.7531182, 283.7280719),
                    ALTP = c(0.3963670049, 0.8659926907, 1.328491136,
                             1.855292223, 2.358125869, 2.792399835,
                             3.24886324, 3.708547366, 4.146854851)),
                    .Names = c("LATITUDE", "LONGITUDE", "ALTP"),
                    row.names = c(NA, 9L),
                    class = "data.frame")

server <- function(input, output, session) {

# create base map
output$flightpath <- renderLeaflet({
leaflet() %>% addTiles() %>% setView(lng = 283.6828216,
                                              lat = 36.94062755,
                                              zoom = 10)
  })

# add markers - this is where the problem is
observe({
  leafletProxy("flightpath", data = dataset) %>%
     addCircles(weight = 6, radius = 40)
     #addCircleMarkers(weight = 6, radius = 6)
})

# get map mouseover coordinates
map_lat_lng <- reactive ({
  req(input$flightpath_shape_mouseover)
  map_hover  <- input$flightpath_shape_mouseover
  x <- data.frame(map_hover$lat, map_hover$lng)
  colnames(x) <- c("Latitude", "Longitude")
  x
})

# add icon to map
observe({
  leafletProxy("flightpath", data = map_lat_lng()) %>%
    clearGroup("hover") %>%
    addMarkers(group = "hover")
})
}

ui <- fluidPage(leafletOutput("flightpath"))

shinyApp(ui, server)
</code>```

Any help figuring this out would be appreciated. Thanks!

答: You're changing it from a shape to a marker, so you need to change the object category: flightpath_shape_mouseover should become flightpath_marker_mouseover. That should fix it.

Body:
I have a map where icons are plotted based on mouseover coordinates. When I changed my markers from addCircles() to addCircleMarkers, however, it stopped functioning. Here's a code snippet that shows the problem. Comment out the addCircles line to see how the behavior changes.

library(shiny)
library(leaflet)

#create test data
dataset <- structure(list(LATITUDE = c(37.09719065, 37.11063138, 37.1132722,
                                 37.0749196, 37.02980937, 36.98644663,
                                 36.94062755, 36.89560073, 36.85363852),
                    LONGITUDE = c(283.6828216, 283.7335099, 283.7892219,
                                  283.813835, 283.812904, 283.7935855,
                                  283.7740784, 283.7531182, 283.7280719),
                    ALTP = c(0.3963670049, 0.8659926907, 1.328491136,
                             1.855292223, 2.358125869, 2.792399835,
                             3.24886324, 3.708547366, 4.146854851)),
                    .Names = c("LATITUDE", "LONGITUDE", "ALTP"),
                    row.names = c(NA, 9L),
                    class = "data.frame")

server <- function(input, output, session) {

# create base map
output$flightpath <- renderLeaflet({
leaflet() %>% addTiles() %>% setView(lng = 283.6828216,
                                              lat = 36.94062755,
                                              zoom = 10)
  })

# add markers - this is where the problem is
observe({
  leafletProxy("flightpath", data = dataset) %>%
     addCircles(weight = 6, radius = 40)
     #addCircleMarkers(weight = 6, radius = 6)
})

# get map mouseover coordinates
map_lat_lng <- reactive ({
  req(input$flightpath_shape_mouseover)
  map_hover  <- input$flightpath_shape_mouseover
  x <- data.frame(map_hover$lat, map_hover$lng)
  colnames(x) <- c("Latitude", "Longitude")
  x
})

# add icon to map
observe({
  leafletProxy("flightpath", data = map_lat_lng()) %>%
    clearGroup("hover") %>%
    addMarkers(group = "hover")
})
}

ui <- fluidPage(leafletOutput("flightpath"))

shinyApp(ui, server)

Any help figuring this out would be appreciated. Thanks!


问:
openGL moving camera
I m trying to move my camera. I am using gluLookAt function. I have some variables for this.

```<code>float x,y,z ==> is camera location
float lx,ly,lz ==> is point that camera looks.
</code>```

I try to move on x axis

```<code>x= x+0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);
</code>```

it is work.

When i try to move on z axis as same as above

```<code>z = z +0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);
</code>```

nothing  change. Also when i invoke this function several times, first half of object dissapear (corners of object) and after next calling gluLookAt object dissapear completely.

I want the object looks bigger when camera move forward and smaller when camera move backward. But any changes is occured when i move camera on z axis.

What is the problem? Why object dissapear? How can i achieve that object get bigger when moving camera forward.

I know i can solve it by glTranslate or increasing size of object. But i want to use  gluLookAt.

Thanks you for answers.

答: As mentioned by Michael, this sounds like a projection matrix problem. When using a perspective transform, depth is transformed so as to provide better depth-testing accuracy nearer to the camera than in the distance. As part of this transform the z-coordinates (in viewport coordinates) are divided by zNear (the near plane distance) - zFar (the far plane distance). To minimise depth-fighting the zNear distance (the distance in front of the camera at which objects become invisible) must be as large as you can get away with, so as you move towards objects they will eventually cross the plane and the front of the object will be clipped (which generally appears as if the front of the object has been cut off and you can see inside/through it).</p>

Title: openGL moving camera

Body:
I m trying to move my camera. I am using gluLookAt function. I have some variables for this.

float x,y,z ==> is camera location
float lx,ly,lz ==> is point that camera looks.

I try to move on x axis

x= x+0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);

it is work.

When i try to move on z axis as same as above

z = z +0.01
gluLookAt(x,y,z, lx,ly,lz, 0.0 1.0, 0.0);

nothing  change. Also when i invoke this function several times, first half of object dissapear (corners of object) and after next calling gluLookAt object dissapear completely.

I want the object looks bigger when camera move forward and smaller when camera move backward. But any changes is occured when i move camera on z axis.

What is the problem? Why object dissapear? How can i achieve that object get bigger when moving camera forward.

I know i can solve it by glTranslate or increasing size of object. But i want to use  gluLookAt.

Thanks you for answers.