问:
WPF WCF MVVM OutOfMemoryException
I am working on this WCF-WPF app. I am frequently getting this error on an asynchronous XamDataGrid. Trying to make a WCF call and populate the Grid. I initially thought this is something to do with the large amounts of data returned from WCF and I made the call return data is much small pieces, by calling only for a category only. This error comes up randomly, not always on the same set of data. Reproducible enough in 15-20 tries.

I am running Windows XP (32bit), Dual Core, with 4GB of ram. When this exception is raised, client machine only uses about 2GB of RAM, and on the server W3WP is using only 800MB (of 6GB, 3 cores. Total memory use on server is ~2GB).

This is only happening on XP machines. Does not get this error on Windows 7 box.

Please guide me how to resolve this issue.

Thanks in advance

```<code>Event Viewer Logs this Message:
Event Type: Error
Event Source:   .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID:   5000
Date:       10/13/2010
Time:       10:50:07 AM
User:       N/A
Computer:   COMP-DC7800
Description:
EventType clr20r3, P1 appname.exe, P2 2.0.0.21872, P3 4cb0a1b1, P4 mscorlib, P5 2.0.0.0, P6 492b834a, P7 35df, P8 45, P9 system.outofmemoryexception, P10 NIL.
</code>```

Below id the Exception details:

```<code>System.OutOfMemoryException was unhandled
Message="Exception of type 'System.OutOfMemoryException' was thrown."
Source="mscorlib"
StackTrace:
   at System.IO.MemoryStream.set_Capacity(Int32 value)
   at System.IO.MemoryStream.EnsureCapacity(Int32 value)
   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlMtomReader.MimePart.GetBuffer(Int32 maxBuffer, Int32& remaining)
   at System.Xml.XmlMtomReader.Initialize(Stream stream, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize)
   at System.Xml.XmlMtomReader.SetInput(Stream stream, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
   at System.Xml.XmlMtomReader.SetInput(Byte[] buffer, Int32 offset, Int32 count, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
   at System.ServiceModel.Channels.MtomMessageEncoder.MtomBufferedMessageData.TakeXmlReader()
   at System.ServiceModel.Channels.BufferedMessageData.DoTakeXmlReader()
   at System.ServiceModel.Channels.BufferedMessageData.GetMessageReader()
   at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReaderAtHeaderContents(IBufferedMessageData bufferedMessageData)
   at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReader(IBufferedMessageData bufferedMessageData, Int32 bufferedMessageHeaderIndex)
   at System.ServiceModel.Channels.MessageHeaders.GetReaderAtHeader(Int32 headerIndex)
   at System.ServiceModel.Channels.WsrmMessageInfo.Get(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, IChannel channel, ISession session, Message message, Boolean csrOnly)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.HandleReceiveComplete(IAsyncResult result)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnReceiveCompletedStatic(IAsyncResult result)
   at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputComplete(IAsyncResult result)
   at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputCompleteStatic(IAsyncResult result)
   at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.Channels.InputQueue`1.AsyncQueueReader.Set(Item item)
   at System.ServiceModel.Channels.InputQueue`1.Dispatch()
   at System.ServiceModel.Channels.InputQueue`1.OnDispatchCallback(Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.OnSecurityContextCallback(Object o)
   at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</code>```

答:
You won't be able to utilise that 4 GB of RAM with a 32 bit OS.

http://chris.pirillo.com/32-bit-windows-and-4gb-of-ram/

If your application is consuming more and more memory as you use it, you may want to look at your memory management. Look at implementing the IDisposable interface for classes with unmanaged resources. Also, avoid keeping references to objects once you've finished using them. Events are particularly bad for this.

How do events cause memory leaks in C# and how do Weak References help mitigate that?

You could also look at streaming to a temporary file instead of streaming to memory.

Title: WPF WCF MVVM OutOfMemoryException

Body:
I am working on this WCF-WPF app. I am frequently getting this error on an asynchronous XamDataGrid. Trying to make a WCF call and populate the Grid. I initially thought this is something to do with the large amounts of data returned from WCF and I made the call return data is much small pieces, by calling only for a category only. This error comes up randomly, not always on the same set of data. Reproducible enough in 15-20 tries.

I am running Windows XP (32bit), Dual Core, with 4GB of ram. When this exception is raised, client machine only uses about 2GB of RAM, and on the server W3WP is using only 800MB (of 6GB, 3 cores. Total memory use on server is ~2GB).

This is only happening on XP machines. Does not get this error on Windows 7 box.

Please guide me how to resolve this issue.

Thanks in advance

Event Viewer Logs this Message:
Event Type: Error
Event Source:   .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID:   5000
Date:       10/13/2010
Time:       10:50:07 AM
User:       N/A
Computer:   COMP-DC7800
Description:
EventType clr20r3, P1 appname.exe, P2 2.0.0.21872, P3 4cb0a1b1, P4 mscorlib, P5 2.0.0.0, P6 492b834a, P7 35df, P8 45, P9 system.outofmemoryexception, P10 NIL.

Below id the Exception details:

System.OutOfMemoryException was unhandled
Message="Exception of type 'System.OutOfMemoryException' was thrown."
Source="mscorlib"
StackTrace:
   at System.IO.MemoryStream.set_Capacity(Int32 value)
   at System.IO.MemoryStream.EnsureCapacity(Int32 value)
   at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
   at System.Xml.XmlMtomReader.MimePart.GetBuffer(Int32 maxBuffer, Int32& remaining)
   at System.Xml.XmlMtomReader.Initialize(Stream stream, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize)
   at System.Xml.XmlMtomReader.SetInput(Stream stream, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
   at System.Xml.XmlMtomReader.SetInput(Byte[] buffer, Int32 offset, Int32 count, Encoding[] encodings, String contentType, XmlDictionaryReaderQuotas quotas, Int32 maxBufferSize, OnXmlDictionaryReaderClose onClose)
   at System.ServiceModel.Channels.MtomMessageEncoder.MtomBufferedMessageData.TakeXmlReader()
   at System.ServiceModel.Channels.BufferedMessageData.DoTakeXmlReader()
   at System.ServiceModel.Channels.BufferedMessageData.GetMessageReader()
   at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReaderAtHeaderContents(IBufferedMessageData bufferedMessageData)
   at System.ServiceModel.Channels.MessageHeaders.GetBufferedMessageHeaderReader(IBufferedMessageData bufferedMessageData, Int32 bufferedMessageHeaderIndex)
   at System.ServiceModel.Channels.MessageHeaders.GetReaderAtHeader(Int32 headerIndex)
   at System.ServiceModel.Channels.WsrmMessageInfo.Get(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, IChannel channel, ISession session, Message message, Boolean csrOnly)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.HandleReceiveComplete(IAsyncResult result)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnReceiveCompletedStatic(IAsyncResult result)
   at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputComplete(IAsyncResult result)
   at System.ServiceModel.Channels.ReliableChannelBinder`1.InputAsyncResult`1.OnInputCompleteStatic(IAsyncResult result)
   at System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.Channels.InputQueue`1.AsyncQueueReader.Set(Item item)
   at System.ServiceModel.Channels.InputQueue`1.Dispatch()
   at System.ServiceModel.Channels.InputQueue`1.OnDispatchCallback(Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke2()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.OnSecurityContextCallback(Object o)
   at System.Security.SecurityContext.Run(SecurityContext securityContext, ContextCallback callback, Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.WorkItem.Invoke()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ProcessCallbacks()
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.CompletionCallback(Object state)
   at System.ServiceModel.Channels.IOThreadScheduler.CriticalHelper.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
   at System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)


来源: stackexchange

问:
Requiring unknown module react/lib/ReactNative
Run command: node ./node_modules/react-native/local-cli/cli.js run-android
or react-native run-android

I got the error "Requiring unknown module react/lib/ReactNative"
trace:

```<code>E/unknown:React: Exception in native call from JS
java.lang.RuntimeException: Error: Requiring unknown module "react/lib/ReactNative". (index.android.bundle:2)
              at com.facebook.react.cxxbridge.CatalystInstanceImpl.loadScriptFromAssets(Native Method)
              at com.facebook.react.cxxbridge.JSBundleLoader$1.loadScript(JSBundleLoader.java:37)
              at com.facebook.react.cxxbridge.CatalystInstanceImpl.runJSBundle(CatalystInstanceImpl.java:177)
              at com.facebook.react.XReactInstanceManagerImpl$4.call(XReactInstanceManagerImpl.java:888)
              at com.facebook.react.XReactInstanceManagerImpl$4.call(XReactInstanceManagerImpl.java:881)
              at com.facebook.react.bridge.queue.MessageQueueThreadImpl$1.run(MessageQueueThreadImpl.java:74)
              at android.os.Handler.handleCallback(Handler.java:751)
              at android.os.Handler.dispatchMessage(Handler.java:95)
              at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)
              at android.os.Looper.loop(Looper.java:154)
              at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196)
              at java.lang.Thread.run(Thread.java:761)
</code>```

"babel-preset-react-native": 1.9.2

"react": "^15.4.1"

"react-native": "^0.31.0"

EDIT:

I uploaded the whole verbose Android Monitor output here:

It actually has a lot of warnings suspiciously related but it is too hard for me to relate, such as:

1) first saying

```<code>W/unknown:InspectorPackagerConnection: Couldn't connect to packager, will silently retry
</code>```

2) then saying:

```<code>  W/unknown:React: Packager connection already open, nooping.
        W/unknown:React: Inspector connection already open, nooping.
</code>```

3)  also a list of:

```<code>  W/unknown:ViewManagerPropertyUpdater: Could not find generated setter for class com.facebook.react.views.XXX
</code>```

答:
could it be related to hot-reloading as suggested below?

Requiring unknown module "react-native". #6753
https://github.com/facebook/react-native/issues/6753

ContentLicense: CC BY-SA 3.0

Body:
Run command: node ./node_modules/react-native/local-cli/cli.js run-android
or react-native run-android

I got the error "Requiring unknown module react/lib/ReactNative"
trace:

E/unknown:React: Exception in native call from JS
java.lang.RuntimeException: Error: Requiring unknown module "react/lib/ReactNative". (index.android.bundle:2)
              at com.facebook.react.cxxbridge.CatalystInstanceImpl.loadScriptFromAssets(Native Method)
              at com.facebook.react.cxxbridge.JSBundleLoader$1.loadScript(JSBundleLoader.java:37)
              at com.facebook.react.cxxbridge.CatalystInstanceImpl.runJSBundle(CatalystInstanceImpl.java:177)
              at com.facebook.react.XReactInstanceManagerImpl$4.call(XReactInstanceManagerImpl.java:888)
              at com.facebook.react.XReactInstanceManagerImpl$4.call(XReactInstanceManagerImpl.java:881)
              at com.facebook.react.bridge.queue.MessageQueueThreadImpl$1.run(MessageQueueThreadImpl.java:74)
              at android.os.Handler.handleCallback(Handler.java:751)
              at android.os.Handler.dispatchMessage(Handler.java:95)
              at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)
              at android.os.Looper.loop(Looper.java:154)
              at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196)
              at java.lang.Thread.run(Thread.java:761)

"babel-preset-react-native": 1.9.2

"react": "^15.4.1"

"react-native": "^0.31.0"

EDIT:

I uploaded the whole verbose Android Monitor output here:

It actually has a lot of warnings suspiciously related but it is too hard for me to relate, such as:

1) first saying

W/unknown:InspectorPackagerConnection: Couldn't connect to packager, will silently retry

2) then saying:

  W/unknown:React: Packager connection already open, nooping.
        W/unknown:React: Inspector connection already open, nooping.

3)  also a list of:

  W/unknown:ViewManagerPropertyUpdater: Could not find generated setter for class com.facebook.react.views.XXX


问:
VB not declaring variables
I have declared the variable "array" but then it says that the variable is undeclared. Its not auto filling "array" when i type so i think that my project file is stuffed? Im in visual studio 2015 if that helps Any help would be great Screen Shot of code</p>

答:
Array is a reserved word in VBA.

try Public arr(137) As String

Title: VB not declaring variables


问:
Understanding ServiceWorker registration
I'm reading the ServiceWorker getting started docs https://developers.google.com/web/fundamentals/getting-started/primers/service-workers.

So first we register our ServiceWorker with the scope. So I did that as below

```<code><!DOCTYPE html>
<html>
<head>
    <title>Getting started with Service Worker</title>
</head>
<body>

<script type="text/javascript">

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

</script>

</body>
</html>
</code>```

and created a sw.js file and wrote a console.log inside sw.js

```<code>console.log("This is sw.js")
</code>```

So when I access the index.html file the first time, that console.log is executed and ServiceWorker registration successful message is printed. But when I refresh the page second time, it only prints the message ServiceWorker registration successful. So why didn't it executed the console.log inside sw.js for the second time. I was expecting it to execute that console.log second time. Am I missing the point here?

答:
A service worker is designed to sit in between your website and the network. So while you load your page initially, it runs the script once and installs the service worker if you have added an event to listen for installs.

Once that's done, you need to attach a listener to the 'fetch' event to capture all your requests inside your page.
So basically if you want to console.log every time a request is made, you can do the following:

```<code>self.addEventListener('fetch', event => {
  console.log(event);
})
</code>```

Body:
I'm reading the ServiceWorker getting started docs https://developers.google.com/web/fundamentals/getting-started/primers/service-workers.

So first we register our ServiceWorker with the scope. So I did that as below

<!DOCTYPE html>

    <title>Getting started with Service Worker</title>

and created a sw.js file and wrote a console.log inside sw.js

console.log("This is sw.js")

So when I access the index.html file the first time, that console.log is executed and ServiceWorker registration successful message is printed. But when I refresh the page second time, it only prints the message ServiceWorker registration successful. So why didn't it executed the console.log inside sw.js for the second time. I was expecting it to execute that console.log second time. Am I missing the point here?

Body:
A service worker is designed to sit in between your website and the network. So while you load your page initially, it runs the script once and installs the service worker if you have added an event to listen for installs.

Once that's done, you need to attach a listener to the 'fetch' event to capture all your requests inside your page.
So basically if you want to console.log every time a request is made, you can do the following:

self.addEventListener('fetch', event => {
  console.log(event);
})


问:
Is it possible to have only the router-outlet as main component?
Currently I'm using this construction to get my router-outlet working as the main app:

```<code>@Component({
    selector: 'my-dummy-app',
    template: '<router-outlet></router-outlet>'
})

export class MyDummyApp {
}
</code>```

Is it possible to cut out the dummy app? I've not had any success. I've tried leaving bootstrap empty, or keep my router-components in the entry collection, but no module config seems to work.

Angular seems bent on having a main component to bootstrap.

答:
Normally you would bootstrap the AppComponent, whos template is anything + <router-outlet> in some place, in the AppModule. Afterwards you would initialize the AppModule as entry point.

Without a main component as entry point I cant imagine how could you tell angular what should be the entry point of the application.

I would say its not possible. When you declare a component in bootstrap in the AppModule, angular will look for its css selector in index.html. If not found -> error. In the other hand, if you dont declare anything inside of the bootstrap section in your app module -> error. Furthermore, if you try to bootstrap the RouterOutet directive in your app module

Uncaught Error: RouterOutlet cannot be used as an entry component.

Also the following quote from the NgModule FAQ seems to support this:

You can embed the child components in the top component's template. Alternatively, make the top component a routing host by giving it a <router-outlet>. Define child routes and let the router load module components into that outlet.

Body:
Currently I'm using this construction to get my router-outlet working as the main app:

@Component({
    selector: 'my-dummy-app',
    template: '<router-outlet></router-outlet>'
})

export class MyDummyApp {
}

Is it possible to cut out the dummy app? I've not had any success. I've tried leaving bootstrap empty, or keep my router-components in the entry collection, but no module config seems to work.

Angular seems bent on having a main component to bootstrap.


问:
Encoding Unicode in the Dictionary Key to Japanese
I just started working on text clustering in Japanese through Python2. However, when I created the dictionary based on these Japanese words/terms, the dictionary keys become unicode instead of Japanese. The codes are as follows:

```<code># load data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz",
encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

## create dictionary
dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

freqrank = np.array(dict_index.values()).argsort()
X_transform = X[:, freqrank < 1000].transpose().toarray()
</code>```

The results of allWrdMat10.columns are still Japanese as follows:

```<code>Index([u'?', u'．', u'・', u'％', u'０', u'１', u'１０月', u'１１月', u'１２
月', u'１つ',
...
u'瀋陽', u'疆', u'盧', u'籠', u'絆', u'胚', u'諫早', u'趙', u'鉉', u'鎔
基'],dtype='object', length=8655)
</code>```

However, the results of dict_index.keys() are as:

```<code>[u'\u77ed\u9283',
 u'\u5efa\u3066',
 u'\u4f0a',
 u'\u5e73\u5b89',
 u'\u6025\u9a30',
 u'\u897f\u65e5\u672c',
 u'\u5e03\u9663',
 ...]
</code>```

Is there any way I can keep the Japanese words/terms in the dictionary keys? Or is there any way I can convert the unicodes back to Japanese words/terms? Thanks.

答:
When you ask the interpreter for the value of an expression it computes the value and then outputs its repr(). The print statement (v2) or function (v3) uses the str() of the value. So if I take one of the problematic keys and ask my interpreter what its value is I get what you see. If I print it, however, I see the required Japanese characters:

```<code>>>> u'\u77ed\u9283'
u'\u77ed\u9283'
>>> print u'\u77ed\u9283'
短銃
</code>```

So you do have the values you need, you just didn't understand that the interpreter was using a different representation, guaranteed to be representable in ASCII.

Body:
I just started working on text clustering in Japanese through Python2. However, when I created the dictionary based on these Japanese words/terms, the dictionary keys become unicode instead of Japanese. The codes are as follows:

# load data
allWrdMat10 = pd.read_csv("../../data/allWrdMat10.csv.gz",
encoding='CP932')

## Set X as CSR Sparse Matrix
X = np.array(allWrdMat10)
X = sp.csr_matrix(X)

## create dictionary
dict_index = {t:i for i,t in enumerate(allWrdMat10.columns)}

freqrank = np.array(dict_index.values()).argsort()
X_transform = X[:, freqrank < 1000].transpose().toarray()

The results of allWrdMat10.columns are still Japanese as follows:

Index([u'?', u'．', u'・', u'％', u'０', u'１', u'１０月', u'１１月', u'１２
月', u'１つ',
...
u'瀋陽', u'疆', u'盧', u'籠', u'絆', u'胚', u'諫早', u'趙', u'鉉', u'鎔
基'],dtype='object', length=8655)

However, the results of dict_index.keys() are as:

[u'\u77ed\u9283',
 u'\u5efa\u3066',
 u'\u4f0a',
 u'\u5e73\u5b89',
 u'\u6025\u9a30',
 u'\u897f\u65e5\u672c',
 u'\u5e03\u9663',
 ...]

Is there any way I can keep the Japanese words/terms in the dictionary keys? Or is there any way I can convert the unicodes back to Japanese words/terms? Thanks.

Body:
When you ask the interpreter for the value of an expression it computes the value and then outputs its repr(). The print statement (v2) or function (v3) uses the str() of the value. So if I take one of the problematic keys and ask my interpreter what its value is I get what you see. If I print it, however, I see the required Japanese characters:

>>> u'\u77ed\u9283'
u'\u77ed\u9283'
>>> print u'\u77ed\u9283'
短銃

So you do have the values you need, you just didn't understand that the interpreter was using a different representation, guaranteed to be representable in ASCII.


问:
How to match the text from textBox1 with a certain column to see if it exist?
When I enter a RegiD to check-in, it takes me to my form 2 but it happens even if the number is not in my RegiD column in my SQL Database. How do it get it to check if the number I entered in my text box is in my SQL Database?

```<code>private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-UHGLPQ8\SQLEXPRESS;Initial Catalog=Test Vol;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM MastVolData WHERE [RegiD] =' " + textBox1.Text + "'" , con);

        SqlDataReader dr =  cmd.ExecuteReader();

        if (dr.Read() == true)
            {
            using (Form2 frm = new Form2(textBox1.Text))
                {
                    frm.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("Wrong I.D! Please try again!");
            }
            textBox1.Clear();
            }
        }
    }
</code>```

答:
First, you need to stop concatenating strings to create SQL statements and start using parameterized queries. Otherwise you are risking SQL Injection attacks.

Second, you need to learn when to use the using statement.

Third, You need to learn about the HasRows property of the SqlDataReader.

Your code should end up looking like this:

```<code>    private void button1_Click(object sender, EventArgs e)
    {
        // use this local variable to prevent keeping sql connection and an active data reader longer than neccessary
        var hasRows = false;

        // You should really get the connection string from your web.config file, I left it hard coded so that you can test.
        var connectionString = @"Data Source=DESKTOP-UHGLPQ8\SQLEXPRESS;Initial Catalog=Test Vol;Integrated Security=True";

        // Use the using statement for any local variable that implements the IDisposable interface
        using (var con = new SqlConnection(connectionString))
        {
            using (var cmd = new SqlCommand("SELECT * FROM MastVolData WHERE [RegiD] = @RegiD;", con))
            {
                cmd.Parameters.Add("@RegiD", SqlDbType.VarChar).Value = textBox1.Text;
                con.Open();
                using (var dr = cmd.ExecuteReader())
                {
                    hasRows = dr.HasRows;
                }
            }
        }

        // Now that your sql connection is closed and disposed, you can use ShowDialog
        if (hasRows)
        {
            using (Form2 frm = new Form2(textBox1.Text))
            {
                frm.ShowDialog();
            }
        }
        else
        {
            MessageBox.Show("Wrong I.D! Please try again!");
        }

        textBox1.Clear();
    }
}
</code>```

Body:
When I enter a RegiD to check-in, it takes me to my form 2 but it happens even if the number is not in my RegiD column in my SQL Database. How do it get it to check if the number I entered in my text box is in my SQL Database?

private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-UHGLPQ8\SQLEXPRESS;Initial Catalog=Test Vol;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM MastVolData WHERE [RegiD] =' " + textBox1.Text + "'" , con);

        SqlDataReader dr =  cmd.ExecuteReader();

        if (dr.Read() == true)
            {
            using (Form2 frm = new Form2(textBox1.Text))
                {
                    frm.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("Wrong I.D! Please try again!");
            }
            textBox1.Clear();
            }
        }
    }

Body:
First, you need to stop concatenating strings to create SQL statements and start using parameterized queries. Otherwise you are risking SQL Injection attacks.

Second, you need to learn when to use the using statement.

Third, You need to learn about the HasRows property of the SqlDataReader.

Your code should end up looking like this:

    private void button1_Click(object sender, EventArgs e)
    {
        // use this local variable to prevent keeping sql connection and an active data reader longer than neccessary
        var hasRows = false;

        // You should really get the connection string from your web.config file, I left it hard coded so that you can test.
        var connectionString = @"Data Source=DESKTOP-UHGLPQ8\SQLEXPRESS;Initial Catalog=Test Vol;Integrated Security=True";

        // Use the using statement for any local variable that implements the IDisposable interface
        using (var con = new SqlConnection(connectionString))
        {
            using (var cmd = new SqlCommand("SELECT * FROM MastVolData WHERE [RegiD] = @RegiD;", con))
            {
                cmd.Parameters.Add("@RegiD", SqlDbType.VarChar).Value = textBox1.Text;
                con.Open();
                using (var dr = cmd.ExecuteReader())
                {
                    hasRows = dr.HasRows;
                }
            }
        }

        // Now that your sql connection is closed and disposed, you can use ShowDialog
        if (hasRows)
        {
            using (Form2 frm = new Form2(textBox1.Text))
            {
                frm.ShowDialog();
            }
        }
        else
        {
            MessageBox.Show("Wrong I.D! Please try again!");
        }

        textBox1.Clear();
    }
}


问:
how to fix this issue that angular js ng-repeat shows only one element in the array of objects?
i have a array of objects in the controller . when the controller invoked,ng-repeat shows all objects in the array as list.  works fine..
but when i push a new object first time into the array.  works fine.. it shows the object as well. when i push another object into array it doesn't show that object.how to fix this issue?
Controller:

```<code> App.controller('teamController', function($scope,$http,$routeParams,$location,$filter) {
$scope.teammembers = [];});
</code>```

Directive:App.directive("searchableMultiselect", function($timeout) {
  return {
    templateUrl: 'angular/templates/team/teamdropdown.php',
    restrict: 'AE',
    scope: {
      displayAttr: '@',
      allItems: '=',
    },link: function(scope, element, attrs) {});

```<code>**Template:**

    <li ng-repeat="item in ::allItems track by $index">
</code>```

Frontend:

```<code><searchable-multiselect display-attr="name"
                                        all-items="teammembers" >
                                     </searchable-multiselect>
</code>```

答:
you allow only one-way binding. need to change it to two-way binding. remove :: in the ng-repeat

```<code><li ng-repeat="item in allItems track by $index">
</code>```

Body:
i have a array of objects in the controller . when the controller invoked,ng-repeat shows all objects in the array as list.  works fine..
but when i push a new object first time into the array.  works fine.. it shows the object as well. when i push another object into array it doesn't show that object.how to fix this issue?
Controller:

 App.controller('teamController', function($scope,$http,$routeParams,$location,$filter) {
$scope.teammembers = [];});

Directive:App.directive("searchableMultiselect", function($timeout) {
  return {
    templateUrl: 'angular/templates/team/teamdropdown.php',
    restrict: 'AE',
    scope: {
      displayAttr: '@',
      allItems: '=',
    },link: function(scope, element, attrs) {});

**Template:**

Frontend:

<searchable-multiselect display-attr="name"
                                        all-items="teammembers" >
                                     </searchable-multiselect>

Body:
you allow only one-way binding. need to change it to two-way binding. remove :: in the ng-repeat

<li ng-repeat="item in allItems track by $index">


问:
array_flip with an array in the value
Simple one (but not solved yet): this is my array

```<code>[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]
</code>```

And I would love to see this result:

```<code>[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]
</code>```

I've already tried array_flip

答:
Try this Live demo</p>

```<code>$array = [
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ]
 ],
 [
   "role" => "user",
   "name" => [
      "Michel",
      "Paul",
      "Tay"
   ]
 ]
];

$result = array_reduce($array, function($carry, $key) {
    foreach ($key['name'] as $name)
        $carry[$name] = $key['role'];
    return $carry;
}, []);

var_dump($result);
</code>```

Title: array_flip with an array in the value

Body:
Simple one (but not solved yet): this is my array

[
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ],
 ],
 [
   "role" => "user",
   "name" => [
     "Michel",
     "Paul",
     "Tay",
 ],
]

And I would love to see this result:

[
 "Felipy" => "admin",
 "Ivan" => "admin",
 "Michael" => "user",
 "Paul" => "user",
 "Tay" => "user",
]

I've already tried array_flip

Body:
Try this Live demo

$array = [
 [
   "role" => "admin",
   "name" => [
     "Felipy",
     "Ivan",
   ]
 ],
 [
   "role" => "user",
   "name" => [
      "Michel",
      "Paul",
      "Tay"
   ]
 ]
];

$result = array_reduce($array, function($carry, $key) {
    foreach ($key['name'] as $name)
        $carry[$name] = $key['role'];
    return $carry;
}, []);

var_dump($result);


问:
Collision Avoidance Example or Help
I have been trying to find a collision avoidance example that I can adapt and use for a game I am working on.  It will be used to model a skier's movements to avoid trees on the hill.  I am basing the movement off of Steering Behaviors for Autonomous Characters and there are a lot of good examples for path following and flocking, but I can't find any good ones for collision avoidance.  The Nature of Code website had awesome tutorials for steering but seemed to cover everything but obstacle avoidance.

I converted the code from here but it doesn't work as well as it should because collisions are found by projecting the obstacles center onto the velocity vector without taking into account when the obstacles center may be outside the limits of collision but the circle is still colliding.  Here is the code I adapted (written in Processing (Java based)).

```<code>// Method to update location
void update() {
  // Update velocity
  vel.add(acc);
  // Limit speed
  vel.limit(maxspeed);
  loc.add(vel);
  // Reset accelertion to 0 each cycle
  acc.mult(0);
}

void obstacleAvoid() {
  float checkLength = 30*vel.mag();
  PVector forward,diff,ray,projection,force;
  float dotProd,dis;
  forward = vel.get();
  forward.normalize();
  ray = forward.get();
  ray.mult(checkLength);
  for ( int i = 0; i < obs.size(); i++ ) {
    Obstacle ob = (Obstacle)obs.get(i);
    diff = ob.pos.get();
    diff.sub(loc);
    PVector temp2 = forward.get();
    temp2.mult(ob.r);
    diff.sub(temp2);
    dotProd = diff.dot(forward);
    if ( dotProd > 0 ) {
      projection = forward.get();
      projection.mult(dotProd);
      dis = PVector.dist(projection,diff);
      if ( (dis < (ob.r + r)) && (projection.mag() < ray.mag()) ) {
        ob.hit = true;
        force = forward.get();
        force.mult(maxforce);
        if ( sign(diff,vel) == -1 ) { //CCW
          force.set(force.y,-force.x,0);
        }
        else { //CW
          force.set(-force.y,force.x,0);
        }
        force.mult(1-(projection.mag())/ray.mag());
        force.limit(maxforce);
        acc.add(force);
      }
    }
  }
}
</code>```

So to help me I was wondering if anyone knew of any complete examples of collision avoidance that follow the Steering Behaviors for Autonomous Characters way of doing things better.  This Site is the example applet for the paper and is the exact example I wish I could see the code for.  Sadly there is no code to come with it and I tried decompiling it but it just showed the main class so that wasn't very helpful.  If someone has the code for this example or something like it, or a tutorial, I would appreciate it a lot.

答:
Craig Reynolds cannot release the source code for the applets you're interested in. Similar source code is available in c++ at OpenSteer, which is maintained by Reynolds. Christian Schnellhammer and Thomas Feilkas worked to expand Reynolds original paper. Their paper is translated into english and contains a section on obstacle avoidance. The source code for their work is available in Java. However, I think Shiffman's code is a great starting point, and it sounds like you're pretty close to what you want already

One of my first Processing programs modified the Boids example to simulate a zombie apocalypse. Triangles chased circles that were avoiding them. Each survivor checks for other zombies in their vision, and averages the location vectors of threats in a function, PVector panic(ArrayList infected). After that, it was a matter of weighting the new vector negatively and adding it to the survivor's current vector like any other force. Something like:

```<code>void flock(ArrayList uninfected, ArrayList infected) {
  PVector sep = separate(uninfected);   // Separation
  PVector ali = align(uninfected);      // Alignment
  PVector coh = cohesion(uninfected);   // Cohesion
  PVector pan = panic(infected);        // Panic
  // Arbitrarily weight these forces
  sep.mult(4.0);
  ali.mult(1.0);
  coh.mult(2.0);
  pan.mult(-3.0);
  // Add the force vectors to acceleration
  acc.add(sep);
  acc.add(ali);
  acc.add(coh);
  acc.add(pan);
}
</code>```

If your skier is successfully detecting the obstacles, then avoidance is the problem. Adding a stronger weight to the avoidance vector, increasing the radius the skier can 'see' to interact with objects, or even adding a method to the object that returns the location of the closest point to the skier could solve your problem. You could also add deceleration based on the distance from the skier to the nearest obstacle in front it.

Remember that even the applet you're interested in does not perfectly avoid obstacles. My solution may not be exactly what is happening in the applet, but by playing around with the forces determining you skier's direction, you can achieve a very similar (and possibly better) effect.

ContentLicense: CC BY-SA 2.5

Title: Collision Avoidance Example or Help

Body:
I have been trying to find a collision avoidance example that I can adapt and use for a game I am working on.  It will be used to model a skier's movements to avoid trees on the hill.  I am basing the movement off of Steering Behaviors for Autonomous Characters and there are a lot of good examples for path following and flocking, but I can't find any good ones for collision avoidance.  The Nature of Code website had awesome tutorials for steering but seemed to cover everything but obstacle avoidance.

I converted the code from here but it doesn't work as well as it should because collisions are found by projecting the obstacles center onto the velocity vector without taking into account when the obstacles center may be outside the limits of collision but the circle is still colliding.  Here is the code I adapted (written in Processing (Java based)).

// Method to update location
void update() {
  // Update velocity
  vel.add(acc);
  // Limit speed
  vel.limit(maxspeed);
  loc.add(vel);
  // Reset accelertion to 0 each cycle
  acc.mult(0);
}

void obstacleAvoid() {
  float checkLength = 30*vel.mag();
  PVector forward,diff,ray,projection,force;
  float dotProd,dis;
  forward = vel.get();
  forward.normalize();
  ray = forward.get();
  ray.mult(checkLength);
  for ( int i = 0; i < obs.size(); i++ ) {
    Obstacle ob = (Obstacle)obs.get(i);
    diff = ob.pos.get();
    diff.sub(loc);
    PVector temp2 = forward.get();
    temp2.mult(ob.r);
    diff.sub(temp2);
    dotProd = diff.dot(forward);
    if ( dotProd > 0 ) {
      projection = forward.get();
      projection.mult(dotProd);
      dis = PVector.dist(projection,diff);
      if ( (dis < (ob.r + r)) && (projection.mag() < ray.mag()) ) {
        ob.hit = true;
        force = forward.get();
        force.mult(maxforce);
        if ( sign(diff,vel) == -1 ) { //CCW
          force.set(force.y,-force.x,0);
        }
        else { //CW
          force.set(-force.y,force.x,0);
        }
        force.mult(1-(projection.mag())/ray.mag());
        force.limit(maxforce);
        acc.add(force);
      }
    }
  }
}

So to help me I was wondering if anyone knew of any complete examples of collision avoidance that follow the Steering Behaviors for Autonomous Characters way of doing things better.  This Site is the example applet for the paper and is the exact example I wish I could see the code for.  Sadly there is no code to come with it and I tried decompiling it but it just showed the main class so that wasn't very helpful.  If someone has the code for this example or something like it, or a tutorial, I would appreciate it a lot.

Body:
Craig Reynolds cannot release the source code for the applets you're interested in. Similar source code is available in c++ at OpenSteer, which is maintained by Reynolds. Christian Schnellhammer and Thomas Feilkas worked to expand Reynolds original paper. Their paper is translated into english and contains a section on obstacle avoidance. The source code for their work is available in Java. However, I think Shiffman's code is a great starting point, and it sounds like you're pretty close to what you want already

One of my first Processing programs modified the Boids example to simulate a zombie apocalypse. Triangles chased circles that were avoiding them. Each survivor checks for other zombies in their vision, and averages the location vectors of threats in a function, PVector panic(ArrayList infected). After that, it was a matter of weighting the new vector negatively and adding it to the survivor's current vector like any other force. Something like:

void flock(ArrayList uninfected, ArrayList infected) {
  PVector sep = separate(uninfected);   // Separation
  PVector ali = align(uninfected);      // Alignment
  PVector coh = cohesion(uninfected);   // Cohesion
  PVector pan = panic(infected);        // Panic
  // Arbitrarily weight these forces
  sep.mult(4.0);
  ali.mult(1.0);
  coh.mult(2.0);
  pan.mult(-3.0);
  // Add the force vectors to acceleration
  acc.add(sep);
  acc.add(ali);
  acc.add(coh);
  acc.add(pan);
}

If your skier is successfully detecting the obstacles, then avoidance is the problem. Adding a stronger weight to the avoidance vector, increasing the radius the skier can 'see' to interact with objects, or even adding a method to the object that returns the location of the closest point to the skier could solve your problem. You could also add deceleration based on the distance from the skier to the nearest obstacle in front it.

Remember that even the applet you're interested in does not perfectly avoid obstacles. My solution may not be exactly what is happening in the applet, but by playing around with the forces determining you skier's direction, you can achieve a very similar (and possibly better) effect.


问:
How to debug the `figwheel-sidecar` project?
How can the figwheel-sidecar project be running on my own machine with my Emacs so I can debug into it?

I tried to cider-jack-in, it works, but how to let the clojurescript project depends on it and let Emacs run the local version of figwheel-sidecar?

答:
https://github.com/bhauman/lein-figwheel/wiki/Using-the-Figwheel-REPL-within-NRepl#integration-with-emacscider

Key steps

```<code>;; ~/.emacs.el or ~/.emacs.d/init.el

(require 'cider)
(setq cider-cljs-lein-repl
      "(do (require 'figwheel-sidecar.repl-api)
           (figwheel-sidecar.repl-api/start-figwheel!)
           (figwheel-sidecar.repl-api/cljs-repl))")
</code>```

M-x cider-jack-in-clojurescript [RET]

Body:
https://github.com/bhauman/lein-figwheel/wiki/Using-the-Figwheel-REPL-within-NRepl#integration-with-emacscider

Key steps

;; ~/.emacs.el or ~/.emacs.d/init.el

(require 'cider)
(setq cider-cljs-lein-repl
      "(do (require 'figwheel-sidecar.repl-api)
           (figwheel-sidecar.repl-api/start-figwheel!)
           (figwheel-sidecar.repl-api/cljs-repl))")

M-x cider-jack-in-clojurescript [RET]


问:
Get values of all items in DynamoDB table and display (Android)
I am having problem with DynamoDB. I dont have any idea on how to get all items in table (in this case, DynamoDBTable) of DynamoDB and display it. I tried to use Scan but it gives me error of null exception.

ScanTable

public void ScanTable() throws Exception {

        DynamoDBMapper mapper = new DynamoDBMapper(client);

        System.out.println("Scanning Tesis");

        DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();

        List<DynamoDBTable> result = mapper.scan(DynamoDBTable.class, scanExpression);
        System.out.println(result.toString());

        for (DynamoDBTest tesis : result) {
           System.out.println(tesis.toString());
        }```
</div>
</div>
</p>

<p>DynamoDBTable</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>@DynamoDBTable(tableName = "Tesis")
public class DynamoDBTest {

        private String Title;
        private String id;
        private String Author;
        private String Year;
        private String Supervisor;
        private String Program;

        @DynamoDBHashKey(attributeName = "Id")
        @DynamoDBAutoGeneratedKey
        public String getId ()
        {
            return id;
        }
        public void setId (String id)
        {
            this.id = id;
        }

        @DynamoDBAttribute(attributeName = "Title")
        public String getTitle()
        {
            return Title;
        }
        public void setTitle (String Title)
        {
            this.Title = Title;
        }

        @DynamoDBAttribute(attributeName = "Author")
        public String getAuthor ()
        {
            return Author;
        }
        public void setAuthor (String Author)
        {
            this.Author = Author;
        }

        @DynamoDBAttribute(attributeName = "Year")
        public String getYear ()
        {
            return Year;
        }
        public void setYear (String Year)
        {
            this.Year = Year;
        }

        @DynamoDBAttribute(attributeName = "Supervisor")
        public String getSupervisor ()
        {
            return Supervisor;
        }
        public void setSupervisor (String Supervisor)
        {
            this.Supervisor = Supervisor;
        }

        @DynamoDBAttribute(attributeName = "Program")
        public String getProgram ()
        {
            return Program;
        }
        public void setProgram (String Program)
        {
            this.Program = Program;
        }
}</code>```

6-28 21:35:47.816  10939-10939/com.example.user.test2 I/System.out﹕ Scanning Tesis
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ java.lang.NullPointerException
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.scan(DynamoDBMapper.java:2007)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.scan(DynamoDBMapper.java:1971)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.example.user.test2.DynamoGetItem.ScanTable(DynamoGetItem.java:53)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.example.user.test2.DynamoGetItem.onCreate(DynamoGetItem.java:30)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5411)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread.access$800(ActivityThread.java:139)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.os.Looper.loop(Looper.java:149)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5257)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)```

Is there anything I did wrong?

答:
```<code>List<DynamoDBTable> result = mapper.scan(DynamoDBTable.class, scanExpression);
    System.out.println(result.toString());

    for (DynamoDBTest tesis : result) {
       System.out.println(tesis.getTitle.toString());
    }
</code>```

<p>you will get all the titles </p>

Body:
I am having problem with DynamoDB. I dont have any idea on how to get all items in table (in this case, DynamoDBTable) of DynamoDB and display it. I tried to use Scan but it gives me error of null exception.

ScanTable

public void ScanTable() throws Exception {

        DynamoDBMapper mapper = new DynamoDBMapper(client);

        System.out.println("Scanning Tesis");

        DynamoDBScanExpression scanExpression = new DynamoDBScanExpression();

        List<DynamoDBTable> result = mapper.scan(DynamoDBTable.class, scanExpression);
        System.out.println(result.toString());

        for (DynamoDBTest tesis : result) {
           System.out.println(tesis.toString());
        }

DynamoDBTable

@DynamoDBTable(tableName = "Tesis")
public class DynamoDBTest {

        private String Title;
        private String id;
        private String Author;
        private String Year;
        private String Supervisor;
        private String Program;

        @DynamoDBHashKey(attributeName = "Id")
        @DynamoDBAutoGeneratedKey
        public String getId ()
        {
            return id;
        }
        public void setId (String id)
        {
            this.id = id;
        }

        @DynamoDBAttribute(attributeName = "Title")
        public String getTitle()
        {
            return Title;
        }
        public void setTitle (String Title)
        {
            this.Title = Title;
        }

        @DynamoDBAttribute(attributeName = "Author")
        public String getAuthor ()
        {
            return Author;
        }
        public void setAuthor (String Author)
        {
            this.Author = Author;
        }

        @DynamoDBAttribute(attributeName = "Year")
        public String getYear ()
        {
            return Year;
        }
        public void setYear (String Year)
        {
            this.Year = Year;
        }

        @DynamoDBAttribute(attributeName = "Supervisor")
        public String getSupervisor ()
        {
            return Supervisor;
        }
        public void setSupervisor (String Supervisor)
        {
            this.Supervisor = Supervisor;
        }

        @DynamoDBAttribute(attributeName = "Program")
        public String getProgram ()
        {
            return Program;
        }
        public void setProgram (String Program)
        {
            this.Program = Program;
        }
}

6-28 21:35:47.816  10939-10939/com.example.user.test2 I/System.out﹕ Scanning Tesis
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ java.lang.NullPointerException
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.scan(DynamoDBMapper.java:2007)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.scan(DynamoDBMapper.java:1971)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.example.user.test2.DynamoGetItem.ScanTable(DynamoGetItem.java:53)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.example.user.test2.DynamoGetItem.onCreate(DynamoGetItem.java:30)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5411)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread.access$800(ActivityThread.java:139)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.os.Looper.loop(Looper.java:149)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5257)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
06-28 21:35:47.826  10939-10939/com.example.user.test2 W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

Is there anything I did wrong?

Body:
List<DynamoDBTable> result = mapper.scan(DynamoDBTable.class, scanExpression);
    System.out.println(result.toString());

    for (DynamoDBTest tesis : result) {
       System.out.println(tesis.getTitle.toString());
    }

you will get all the titles


问:
Unique objects in arraylist by multiple properties (PS)
How can i get unique records by two (or more) properties?
i have ArrayList of objects of type :

```<code>class Something
{
[string] $Name
[string] $Key
[string] $SomethingElse
[string] $Val
}
</code>```

and i would like to select only unique items from this array list, by $name,$key,$somethingelse

答:
Just pipe your list to group-object like this:

```<code>$List | Group-Object Name, Key, Somethingelse | Where-Object Count -eq 1 | Select-Object -Expand Group
</code>```

Group-Object creates groups object with equal properties. You can filter the groups by their count and/or their properties. After that, you can get the groups content by expanding the Group property

Body:
How can i get unique records by two (or more) properties?
i have ArrayList of objects of type :

class Something
{
[string] $Name
[string] $Key
[string] $SomethingElse
[string] $Val
}

and i would like to select only unique items from this array list, by $name,$key,$somethingelse

Body:
Just pipe your list to group-object like this:

$List | Group-Object Name, Key, Somethingelse | Where-Object Count -eq 1 | Select-Object -Expand Group

Group-Object creates groups object with equal properties. You can filter the groups by their count and/or their properties. After that, you can get the groups content by expanding the Group property


问:
Android SoundPool: get notified when end of played
This sound so simple that I can't figure out why I can't find the answer lol

I have a working sound pool class (thanks to a tutorial and some tweaking I did), and it works fine.

the problem now is that I want to be able to change my background music randomly. (not always have the same music in a loop but have 2 or 3 and when one finishes I play one of the 2 others).

problem is I can't find a way to get notified that the music has finished playing.

Any ideas ?

Jason

答:
It can't be done with SoundPool as far as I can tell.

The only audio 'player' that I know which can provide a completion notification is
MediaPlayer - it's more of a complex beast than SoundPool but allows setting an OnCompletionListener to be notified when playback is complete.


问:
Cannot launch emulator on Linux (Ubuntu 15.10)
I try to launch emulator but it outputs into log:

```<code>libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
Major opcode of failed request:  155 (GLX)
Minor opcode of failed request: 6 (X_GLXIsDirect)
Serial number of failed request:  47
Current serial number in output stream:  46
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
Major opcode of failed request:  155 (GLX)
Minor opcode of failed request:  6 (X_GLXIsDirect)
Serial number of failed request:  47
Current serial number in output stream:  46
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  BadValue (integer parameter out of range for operation)
Major opcode of failed request:  155 (GLX)
Minor opcode of failed request:  24 (X_GLXCreateNewContext)
Value in failed request:  0x0
Serial number of failed request:  33
Current serial number in output stream:  34
QObject::~QObject: Timers cannot be stopped from another thread emulator: WARNING: Increasing RAM size to 1GB
</code>```

How to fix it? I read topics with similar errors but it doesn't help me.

答:
I had the similar problems with using i965_dri.so and swrast_dri.so, I wasn't able to change to software graphics in the GUI.

So I went to the emulator's folder (Show on Disk link in AVDM) and found the config.ini

Here I just changed the following line to stop it from using GPU:

```<code>hw.gpu.enabled=no
</code>```

Body:
I try to launch emulator but it outputs into log:

libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
Major opcode of failed request:  155 (GLX)
Minor opcode of failed request: 6 (X_GLXIsDirect)
Serial number of failed request:  47
Current serial number in output stream:  46
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  GLXBadContext
Major opcode of failed request:  155 (GLX)
Minor opcode of failed request:  6 (X_GLXIsDirect)
Serial number of failed request:  47
Current serial number in output stream:  46
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request:  BadValue (integer parameter out of range for operation)
Major opcode of failed request:  155 (GLX)
Minor opcode of failed request:  24 (X_GLXCreateNewContext)
Value in failed request:  0x0
Serial number of failed request:  33
Current serial number in output stream:  34
QObject::~QObject: Timers cannot be stopped from another thread emulator: WARNING: Increasing RAM size to 1GB

How to fix it? I read topics with similar errors but it doesn't help me.

Body:
I had the similar problems with using i965_dri.so and swrast_dri.so, I wasn't able to change to software graphics in the GUI.

So I went to the emulator's folder (Show on Disk link in AVDM) and found the config.ini

Here I just changed the following line to stop it from using GPU:

hw.gpu.enabled=no


问:
RadGrid Column Sorting on every click of the Header
I have a RadGrid like below :-

```<code><telerik:RadGrid ID="RadGrid1" runat="server" OnSelectedIndexChanged="SelectedIndexChanged"  AutoGenerateColumns="False" AllowPaging="True"
    OnNeedDataSource="NeedDataSource" OnItemDataBound="ItemDataBound" OnItemCommand="ItemCommand">
    <MasterTableView DataKeyNames="Id" CommandItemDisplay="Top">
        <CommandItemTemplate>
            <asp:LinkButton ID="btnEditSelected" runat="server" CommandName="EditSelected" Visible='<%# RadGrid1.EditIndexes.Count = 0%>'><img style="border:0px;vertical-align:middle;" alt="" src="images/edit.png"/>Edit Selected </asp:LinkButton>
            <asp:LinkButton ID="LinkButton2" runat="server" CommandName="InitInsert" Visible='<%# Not RadGrid1.MasterTableView.IsItemInserted%>'><img style="border:0px;vertical-align:middle;" alt="" src="images/addrecord.png"/>Add New </asp:LinkButton>
            <asp:LinkButton ID="LinkButton1" OnClientClick="if ( ! checkRowSelected()) return false;" runat="server" CommandName="DeleteSelected"><img style="border:0px;vertical-align:middle;" alt="" src="images/delete.png"/>Delete Selected </asp:LinkButton>
        </CommandItemTemplate>
        <Columns>
            <telerik:GridBoundColumn DataField="Name" HeaderText="Name" ItemStyle-VerticalAlign="Top" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="Small" HeaderStyle-ForeColor="Black">
            </telerik:GridBoundColumn>
            <telerik:GridHyperLinkColumn HeaderText="WebSite" DataTextField="WebSite" DataTextFormatString="{0}" DataNavigateUrlFields="WebSite" DataNavigateUrlFormatString="{0}"
                ItemStyle-VerticalAlign="Top" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="Small" HeaderStyle-ForeColor="Black" Target="_blank" >
            </telerik:GridHyperLinkColumn>
            <telerik:GridBoundColumn DataField="Notes" HeaderText="Notes" ItemStyle-VerticalAlign="Top" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="Small" HeaderStyle-ForeColor="Black">
            </telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>
</code>```

Now I want the Name Column to be 'sortable' alphabetically so if someone clicks the word "Name", they get alpha and reverse alpha sorting with every other click.

So that the sort order changes(to alternate sort) with every click on the Header "Name".

I have a little idea of sorting the column on Header click. But the same column should be sorted in reverse order on the second time click of the Header (and vice-versa).

Could anyone help me how to accomplish this , or any ideas , ThankYou !

答:
Can refer to :-

http://www.telerik.com/forums/multi-column-sorting-when-header-click

There are also other sites that explain well about this.

Thanks a lot !!!

Body:
I have a RadGrid like below :-

<telerik:RadGrid ID="RadGrid1" runat="server" OnSelectedIndexChanged="SelectedIndexChanged"  AutoGenerateColumns="False" AllowPaging="True"
    OnNeedDataSource="NeedDataSource" OnItemDataBound="ItemDataBound" OnItemCommand="ItemCommand">
    <MasterTableView DataKeyNames="Id" CommandItemDisplay="Top">
        <CommandItemTemplate>
            <asp:LinkButton ID="btnEditSelected" runat="server" CommandName="EditSelected" Visible='<%# RadGrid1.EditIndexes.Count = 0%>'>Edit Selected </asp:LinkButton>
            <asp:LinkButton ID="LinkButton2" runat="server" CommandName="InitInsert" Visible='<%# Not RadGrid1.MasterTableView.IsItemInserted%>'>Add New </asp:LinkButton>
            <asp:LinkButton ID="LinkButton1" OnClientClick="if ( ! checkRowSelected()) return false;" runat="server" CommandName="DeleteSelected">Delete Selected </asp:LinkButton>
        </CommandItemTemplate>
        <Columns>
            <telerik:GridBoundColumn DataField="Name" HeaderText="Name" ItemStyle-VerticalAlign="Top" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="Small" HeaderStyle-ForeColor="Black">
            </telerik:GridBoundColumn>
            <telerik:GridHyperLinkColumn HeaderText="WebSite" DataTextField="WebSite" DataTextFormatString="{0}" DataNavigateUrlFields="WebSite" DataNavigateUrlFormatString="{0}"
                ItemStyle-VerticalAlign="Top" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="Small" HeaderStyle-ForeColor="Black" Target="_blank" >
            </telerik:GridHyperLinkColumn>
            <telerik:GridBoundColumn DataField="Notes" HeaderText="Notes" ItemStyle-VerticalAlign="Top" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="Small" HeaderStyle-ForeColor="Black">
            </telerik:GridBoundColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>

Now I want the Name Column to be 'sortable' alphabetically so if someone clicks the word "Name", they get alpha and reverse alpha sorting with every other click.

So that the sort order changes(to alternate sort) with every click on the Header "Name".

I have a little idea of sorting the column on Header click. But the same column should be sorted in reverse order on the second time click of the Header (and vice-versa).

Could anyone help me how to accomplish this , or any ideas , ThankYou !


问:
SQL query to get the count by applying group by
I want to get the below result:

source table :

```<code>Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE
</code>```

Result:

```<code>Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE
</code>```

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

答:
Try this query --</p>

```<code>SELECT SUM(Cnt) AS [COUNT]
    ,A
    ,CASE
        WHEN CHARINDEX('/', B) > 0
            THEN SUBSTRING(B, 1, (CHARINDEX('/', B) - 1))
        ELSE B
        END
FROM tblSample
GROUP BY A, B
ORDER BY A, B
</code>```

Body:
I want to get the below result:

source table :

Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE

Result:

Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

Body:
Try this query --

SELECT SUM(Cnt) AS [COUNT]
    ,A
    ,CASE
        WHEN CHARINDEX('/', B) > 0
            THEN SUBSTRING(B, 1, (CHARINDEX('/', B) - 1))
        ELSE B
        END
FROM tblSample
GROUP BY A, B
ORDER BY A, B


问:
WordPress phone Number Restrict to allow xxx-xxx-xxxx Format
I have Kept the placeholder as xxx-xxx-xxxx

```<code><label> Phone Number </label> [number* shm-mrk-phone minlength:10 maxlength:140 placeholder "]
</code>```

I changes the tel script in plugin formatting.php

```<code>function wpcf7_is_tel( $tel ) {
    $result = preg_match( '/^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/', $tel );
    return apply_filters( 'wpcf7_is_tel', $result, $tel );
}
</code>```

its not allowing xxx-xxx-xxxx( this should allow), its allowing xxxxxxxxxx

答:
It's Very Simple. i used tel instead of number Type to add Mobile Number.

In Contact Form 7 plugin formatting.php Module,

i updated the Code of wpcf7_is_tel function with.

```<code>function wpcf7_is_tel( $tel ) {
    $result = preg_match( '/^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/', $tel );
    return apply_filters( 'wpcf7_is_tel', $result, $tel );
}
</code>```

Works Fine.

Body:
I have Kept the placeholder as xxx-xxx-xxxx

 Phone Number  [number* shm-mrk-phone minlength:10 maxlength:140 placeholder "]

I changes the tel script in plugin formatting.php

function wpcf7_is_tel( $tel ) {
    $result = preg_match( '/^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/', $tel );
    return apply_filters( 'wpcf7_is_tel', $result, $tel );
}

its not allowing xxx-xxx-xxxx( this should allow), its allowing xxxxxxxxxx

Body:
It's Very Simple. i used tel instead of number Type to add Mobile Number.

In Contact Form 7 plugin formatting.php Module,

i updated the Code of wpcf7_is_tel function with.

function wpcf7_is_tel( $tel ) {
    $result = preg_match( '/^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/', $tel );
    return apply_filters( 'wpcf7_is_tel', $result, $tel );
}

Works Fine.


问:
Can I serve AMP pages with firebase-storage?
Since firebase hosting only serve static pages, can I serve [dynamically generated] AMP pages with firebase-storage?</p>

答:
Now with firebase cloud functions, you can use an all-firebase solution:
As an answer to an http request, you can query the database and dynamically generate a amp/html page that is send to the browser.

Here is my approach generating an html page Firebase HTTP Cloud Functions - Read database once

By now I have developed it further to serve an amp page.


问:
Delphi Printing Techniques
Where can I find a good resource for adding print capabilities to my program?

I found this page: http://efg2.com/Lab/Library/Delphi/Printing/index.html but it hasn't been updated in 5 years, and I'd like to know if, with Delphi 2009, StretchDIBits is still preferred to StretchDrawMap, how to best support pagination, preview, etc.

To date, I've cheated by creating html or pdf documents than printing those, but it is a bit onerous to go this far for all print tasks.

答: I have used Rave Reports.</p>

OwnerDisplayName: Zartog

Title: Delphi Printing Techniques

Body: I have used Rave Reports.

OwnerDisplayName: Harriv


问:
EditText Alternatives in a Widget? There has to be a way
Has anyone ever successfully implemented an EditText in a widget? I realize Android does not support this, however, "Friend Stream" on HTC devices does it... Is this due to an HTC feature? Could I implement this on HTC? Anyone have any crazy creative ideas for implementing a textbox which actually allows typing on a homescreen widget?

ANY possible leads on this would be much appreciated!

答: A way to do this is to make a tap on your widget start a new activity (standard) and to make this activity fully transparent. There are ways to retrieve your widget's position, so that you can position a TextView in your activity on top of your widget. Make a tap outside of your TextView close the activity. I think this is what the Google search widget does, you may want to look at this code.</p>


问:
How to know when dd has finished
I have a issue with the dd comand. I use it in a while like this:

```<code>while c=$(dd count=1000 bs=1 2>/dev/null) ;do

    echo -n "$c" > /dev/ttyO5
done < $FILE
</code>```

And it works like charm, the only problem is that once the file is read completely, it doesnt stop the while, it stays there stalled. How could I make the while to stop once the dd read all the file?

BTW: Note my machine is embed linux, it doesnt have all the comands and tools as a normal ubuntu machine would have.

Thanks

Output dd --version

```<code>BusyBox v1.20.2 (MUSE) multi-call binary.

Usage: dd [if=FILE] [of=FILE] [bs=N] [count=N] [skip=N]
        [seek=N]

Copy a file with converting and formatting

        if=FILE         Read from FILE instead of stdin
        of=FILE         Write to FILE instead of stdout
        bs=N            Read and write N bytes at a time
        count=N         Copy only N input blocks
        skip=N          Skip N input blocks
        seek=N          Skip N output blocks

Numbers may be suffixed by c (x1), w (x2), b (x512), kD (x1000), k (x1024),
MD (x1000000), M (x1048576), GD (x1000000000) or G (x1073741824)
</code>```

答:
Since you have if and of, why not use them,

test.sh:

```<code>dd if=$1 of=/dev/ttyO5 count=1000 bs=1 2>/dev/null
</code>```

output:

root@localhost~# ./test.sh file.txt
The quick brown fox jumps over the bashy dog.
root@localhost~#
```

Title: How to know when dd has finished

Body:
I have a issue with the dd comand. I use it in a while like this:

while c=$(dd count=1000 bs=1 2>/dev/null) ;do

    echo -n "$c" > /dev/ttyO5
done < $FILE

And it works like charm, the only problem is that once the file is read completely, it doesnt stop the while, it stays there stalled. How could I make the while to stop once the dd read all the file?

BTW: Note my machine is embed linux, it doesnt have all the comands and tools as a normal ubuntu machine would have.

Thanks

Output dd --version

BusyBox v1.20.2 (MUSE) multi-call binary.

Usage: dd [if=FILE] [of=FILE] [bs=N] [count=N] [skip=N]
        [seek=N]

Copy a file with converting and formatting

        if=FILE         Read from FILE instead of stdin
        of=FILE         Write to FILE instead of stdout
        bs=N            Read and write N bytes at a time
        count=N         Copy only N input blocks
        skip=N          Skip N input blocks
        seek=N          Skip N output blocks

Numbers may be suffixed by c (x1), w (x2), b (x512), kD (x1000), k (x1024),
MD (x1000000), M (x1048576), GD (x1000000000) or G (x1073741824)

Body:
Since you have if and of, why not use them,

test.sh:

dd if=$1 of=/dev/ttyO5 count=1000 bs=1 2>/dev/null

output:

root@localhost~# ./test.sh file.txt
The quick brown fox jumps over the bashy dog.
root@localhost~#


问:
How to sum all data in an excel file that contains specific data
Hope someone can help me out on this.

I have an excel file which has different data. Here's a screenshot of the actual data: http://prntscr.com/fg0q2m

What I want to happen is this:

I want to get the sum of all specific "Service Presence Status:API Name" which has the same value per user.

Example: I want to get the total duration Christian Aguda used the status "Available for Email" for each specific day.

Hope you can shed some light, folks.

Thanks!

答:
Use
SUMIFS formula to get sum of your defined criteria
COUNTIFS formula to get count of your defined criteria

Below mentioned link of sumifs formula example
https://exceljet.net/excel-functions/excel-sumifs-function


问:
How to change ionic app structure. cli 3 same cli2
I want to change structure of an app. How to set $urlRouterProvider.otherwise('/login');? How to find app.js?

Cli 3:

Cli 2:

答:
According to the CLi 3 image, you have created an Ionic 3 project.
To start an ionic 1 project check here,
Do:</p>

```<code>ionic start mynewapp blank --type ionic1
</code>```

Body:
According to the CLi 3 image, you have created an Ionic 3 project.
To start an ionic 1 project check here,
Do:

ionic start mynewapp blank --type ionic1


问:
Can't remove readonly from a html select using jQuery
I'm trying to dynamically remove the 'readonly' attribute from some HTML elements.

I've created a [JSFiddle here][1] to show my issue, here is my code snippet:

$('#theButton').on('click', function() {
  $('#mySelect').removeProp('readonly');
  $('#textInput').removeProp('readonly');
  //stop the form posting back
  return false;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <label>Some input fields</label>
  <input type='text' class='form-control' id='textInput' readonly>
  <select id='mySelect' readonly class='form-control input-sm '>
    <option>1</option>
    <option>2</option>
    </select>
  <button class='btn btn-primary' id='theButton'>
    Enable Button
    </button>
</form></code>```

答:
You should use the attr function of jQuery:

```<code>$('#mySelect').attr("readonly", false);
$('#textInput').attr("readonly", false);
</code>```

While using prop instead will work too, the best practice for your situation is to use attr.

Body:
I'm trying to dynamically remove the 'readonly' attribute from some HTML elements.

I've created a [JSFiddle here][1] to show my issue, here is my code snippet:

$('#theButton').on('click', function() {
  $('#mySelect').removeProp('readonly');
  $('#textInput').removeProp('readonly');
  //stop the form posting back
  return false;
})

<form>
  Some input fields
  <input type='text' class='form-control' id='textInput' readonly>
  <select id='mySelect' readonly class='form-control input-sm '>
    <option>1</option>
    <option>2</option>
    </select>
  <button class='btn btn-primary' id='theButton'>
    Enable Button
    </button>
</form>

Body:
You should use the attr function of jQuery:

$('#mySelect').attr("readonly", false);
$('#textInput').attr("readonly", false);

While using prop instead will work too, the best practice for your situation is to use attr.


问:
Custom Domain AWS API-Gateway 403
Custom domain has been mapped with AWS API-Gateway and using my custom domain name randomly gives following error.

```<code><html>
    <body>
        <h1>403 Forbidden</h1>
Request forbidden by administrative rules.
    </body>
</html>
</code>```

I have tried different domain mappings and have also used root (/) as a default but changing mappings does not improve reliability. Using AWS URL (https://xxxxxx.execute-api.xxxxx.amazonaws.com) always works relibily so I think it is a custom domain problem.

I can reproduce this with the custom domain on using Postman and Curl command, using AWS URL never gave an error.

答: The problem was our DNS and not AWS, DNS was showing random results due to the wildcard.</p>

Title: Custom Domain AWS API-Gateway 403

Body:
Custom domain has been mapped with AWS API-Gateway and using my custom domain name randomly gives following error.

403 Forbidden

Request forbidden by administrative rules.

I have tried different domain mappings and have also used root (/) as a default but changing mappings does not improve reliability. Using AWS URL (https://xxxxxx.execute-api.xxxxx.amazonaws.com) always works relibily so I think it is a custom domain problem.

I can reproduce this with the custom domain on using Postman and Curl command, using AWS URL never gave an error.


问:
how to find two different strings in the same line in matlab
I have a cell obtained from text scan and I want to find the index of lines containing particular string,

```<code>fid = fopen('data.txt');
E = textscan(fid, '%s', 'Delimiter', '\n');
</code>```

and I wanted to know the line numbers (index) of those lines which have a specific text, e.g. I wanted to find the rows that have the keyword "2016":

```<code>rows = find(contains(E{1},"2016" );
</code>```

but I want to find the index of those lines which have two keywords "2016" and "Mathew Perry" (only those lines which have both the keywords).

I tried using this code but does not work

```<code>rows = find(contains(E{1},"2016" && contains(E{1},"Mathew Perry");
</code>```

the error I get is:

Operands to the || and && operators must be convertible to logical scalar values.

答:
To find a single string:

```<code>idx = strfind(E{1}, '2016');
idx = find(not(cellfun('isempty', idx)));
</code>```

Use strfind instead of find. YOu may try the above with and/or. If it works fine, then no problem; if not, get the indices separately for each word and get the intersection of the indices.

Body:
I have a cell obtained from text scan and I want to find the index of lines containing particular string,

fid = fopen('data.txt');
E = textscan(fid, '%s', 'Delimiter', '\n');

and I wanted to know the line numbers (index) of those lines which have a specific text, e.g. I wanted to find the rows that have the keyword "2016":

rows = find(contains(E{1},"2016" );

but I want to find the index of those lines which have two keywords "2016" and "Mathew Perry" (only those lines which have both the keywords).

I tried using this code but does not work

rows = find(contains(E{1},"2016" && contains(E{1},"Mathew Perry");

the error I get is:

Operands to the || and && operators must be convertible to logical scalar values.

Body:
To find a single string:

idx = strfind(E{1}, '2016');
idx = find(not(cellfun('isempty', idx)));

Use strfind instead of find. YOu may try the above with and/or. If it works fine, then no problem; if not, get the indices separately for each word and get the intersection of the indices.


问:
How to stop a value from going into negative value
I'm developing an incremental game here is the link for visual reference:

https://code.sololearn.com/WF65X6DEns7o/#css

The problem i have is that buttons can be clicked unlimited times and INCOME value will go into the negative.

How can disable the button if the player doesn't have enough INCOME to click the button

function buttonOne() {
  a++;
  document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
  income -= 500;
  document.getElementById("HeaderLabel").innerHTML = " OK, good, now let's   watch as your money starts to generate slowly but surely.
 After all no   empire was built in a day.
 When you have enough money you can buy more   units. " ;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar1");
    var width = 1;
    var id = setInterval(frame, 4);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 1000)
}

function buttonTwo() {
  b++;
  document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
  income -= 1000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar2");
    var width = 1;
    var id = setInterval(frame, 9);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 2000)
}

function buttonThree() {
  c++;
  document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
  income -= 2000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar3");
    var width = 1;
    var id = setInterval(frame, 19);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 3000)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="gameMoneyBG">
  <div id="gameMoney"> Income : $ 500 </div</div>

    <button id="buttonOne" onclick="buttonOne()">
          <b>Small Units</b></button>
    <div id="progbar1">
      <div id="myprogbar1"> </div>
    </div>
    <br /> <br />
    <div id="btnLabel1"> Units Owned : 0 </div>
    <div id="costLabel1">
      Unit Cost : $ 500 </div>

    <br /><br />

    <button id="buttonTwo" onclick="buttonTwo()"><b>Large Units</b></button>
    <div id="progbar2">
      <div id="myprogbar2"> </div>
    </div>
    <br /><br />
    <div id="btnLabel2"> Units Owned : 0 </div>
    <div id="costLabel2"> Unit Cost : $ 1000 </div>

    <br /><br />

    <button id="buttonThree" onclick="buttonThree()"><b>City Lofts</b></button>
    <div id="progbar3">
      <div id="myprogbar3"> </div>
    </div>
    <br /><br />
    <div id="btnLabel3"> Lofts Owned : 0 </div>
    <div id="costLabel3"> Loft Cost : $ 2000 </div></code>```

答:
Lets beautify your code a bit:

```<code>var values=[
  {value:0,sign,bar,desc:"Units",cost:0},
  {value:0,sign,bar,desc:"Units",cost:500},
  {value:0,sign,bar,desc:"Lofts",cost:2000}
];

//init the dom on load
window.addEventListener("load",function(){
//assign all labels
[document.getElementById("btnLabel1"),document.getElementById("btnLabel2"),document.getElementById("btnLabel3")].forEach((el,i)=>values[i].sign=el);

//assign all progressbars:
[document.getElementById("myprogbar1"),document.getElementById("myprogbar2"),document.getElementById("myprogbar3")].forEach((el,i)=>values[i].bar=el);
});

function increase(id){
 //check if user can effort
 if(income<values[id].cost) return alert("Sorry you cant effort :(");
 //decrease income
 income-=values[id].cost;
 //set label
  values[id].sign.innerHTML = values[id].desc+" Owned :  " + (++values[id].value);
  //show some cool animation:
  var width=1;
  values[id].animation=values[id].animation || setInterval(function(){
    width=(1+width)%100;
    values[id].bar.style.width = width + '%';
  },10);
}

function buttonOne() {
   increase(0);
   document.getElementById("HeaderLabel").innerHTML = "<b> OK, good, now lets watch as your money starts togenerate slowly but surely. <p> After all no empire was built in a day. <p> When you have enough money you can buy more units." ;
 }

function buttonTwo() {
 increase(1);
}

function buttonThree() {
  increase(2);
}
</code>```

You may increase income:

```<code>window.setInterval(_=>income++,10);
</code>```

Body:
I'm developing an incremental game here is the link for visual reference:

https://code.sololearn.com/WF65X6DEns7o/#css

The problem i have is that buttons can be clicked unlimited times and INCOME value will go into the negative.

How can disable the button if the player doesn't have enough INCOME to click the button

function buttonOne() {
  a++;
  document.getElementById("btnLabel1").innerHTML = " Units Owned :  " + a;
  income -= 500;
  document.getElementById("HeaderLabel").innerHTML = " OK, good, now let's   watch as your money starts to generate slowly but surely.
 After all no   empire was built in a day.
 When you have enough money you can buy more   units. " ;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar1");
    var width = 1;
    var id = setInterval(frame, 4);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 1000)
}

function buttonTwo() {
  b++;
  document.getElementById("btnLabel2").innerHTML = " Units Owned :  " + b;
  income -= 1000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar2");
    var width = 1;
    var id = setInterval(frame, 9);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 2000)
}

function buttonThree() {
  c++;
  document.getElementById("btnLabel3").innerHTML = " Lofts Owned :  " + c;
  income -= 2000;

  window.setInterval(function move() {
    var elem = document.getElementById("myprogbar3");
    var width = 1;
    var id = setInterval(frame, 19);

    function frame() {
      if (width >= 100) {
        clearInterval(id);
      } else {
        width++;
        elem.style.width = width + '%';
      }
    }
  }, 3000)
}

 Income : $ 500 </div

    <button id="buttonOne" onclick="buttonOne()">
          Small Units</button>

 Units Owned : 0

      Unit Cost : $ 500

    <button id="buttonTwo" onclick="buttonTwo()">Large Units</button>

 Units Owned : 0

 Unit Cost : $ 1000

    <button id="buttonThree" onclick="buttonThree()">City Lofts</button>

 Lofts Owned : 0

 Loft Cost : $ 2000

Body:
Lets beautify your code a bit:

var values=[
  {value:0,sign,bar,desc:"Units",cost:0},
  {value:0,sign,bar,desc:"Units",cost:500},
  {value:0,sign,bar,desc:"Lofts",cost:2000}
];

//init the dom on load
window.addEventListener("load",function(){
//assign all labels
[document.getElementById("btnLabel1"),document.getElementById("btnLabel2"),document.getElementById("btnLabel3")].forEach((el,i)=>values[i].sign=el);

//assign all progressbars:
[document.getElementById("myprogbar1"),document.getElementById("myprogbar2"),document.getElementById("myprogbar3")].forEach((el,i)=>values[i].bar=el);
});

function increase(id){
 //check if user can effort
 if(income<values[id].cost) return alert("Sorry you cant effort :(");
 //decrease income
 income-=values[id].cost;
 //set label
  values[id].sign.innerHTML = values[id].desc+" Owned :  " + (++values[id].value);
  //show some cool animation:
  var width=1;
  values[id].animation=values[id].animation || setInterval(function(){
    width=(1+width)%100;
    values[id].bar.style.width = width + '%';
  },10);
}

function buttonOne() {
   increase(0);
   document.getElementById("HeaderLabel").innerHTML = "<b> OK, good, now lets watch as your money starts togenerate slowly but surely. <p> After all no empire was built in a day. <p> When you have enough money you can buy more units." ;
 }

function buttonTwo() {
 increase(1);
}

function buttonThree() {
  increase(2);
}

You may increase income:

window.setInterval(_=>income++,10);


问:
Unable to render image uploaded within Electron app, built with electron-forge
I have a file uploader for users to store images, which I'm saving content to a folder within the application data directory (app.getPath('userData')). This all works fine.
When I attempt to load the image using a basic image tag, with the src pointing to the correct location within the application data directory, it fails to render.
This only occurs after I've packaged the app using electron-forge (make & package). I've only attempted to make for OS-X (darwin x-64). I'm guessing it has something to do with asar, but I can't seem to get this working. I've attempted to use the file protocol for the image source too.
Any idea how to correctly do this?</p>

答: I found the easiest way is to serve all content up from a server bound to localhost</p>


问:
elasticsearch must query combine OR?
I have been trying to use a must query with bool but I am failing to get the results.

In pseudo-SQL:

```<code>SELECT * FROM info WHERE (ulevel= '1.3.10' or ulevel= '1.3.6') AND (@timestamp between '2017-06-05T07:00:00.000Z' and '2017-06-05T07:00:00.000Z')
</code>```

Here is what I have:

```<code>"query": {
    "bool": {
        "must": [
            {
                 "query_string": {
                        "default_field": "_all",
                        "query": "*"
                                    },
                 "range": {
                         "@timestamp": {
                               "from": "2017-06-05T07:00:00.000Z",
                               "to": "2017-06-05T07:20:00.000Z"
                                        }
                     },
                "bool": {
                    "should": [
                        {"term": { "ulevel": "1.3.10"}},
                         {"term": { "ulevel": "1.3.6"}}
                             ]
                       }
            }
        ]
    }
  }
</code>```

Does anyone have a solution?

Thank you so much.

答:
You can use terms query for the first part and the range query for the second part

```<code>GET _search
{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "ulevel": [
              "1.3.10",
              "1.3.6"
            ]
          }
        },
        {
          "range": {
            "@timestamp": {
              "gte": "2017-06-05T07:00:00.000Z",
              "lte": "2017-06-05T07:20:00.000Z"
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 20
}
</code>```

Some Notes :

Filters documents that have fields that match any of the provided terms (not analyzed)

Also you can use some date spesific formulation with rage filter. Please check the range query page https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html#ranges-on-dates more information.

Update:

Added from and size for comment question.

Title: elasticsearch must query combine OR?

Body:
I have been trying to use a must query with bool but I am failing to get the results.

In pseudo-SQL:

SELECT * FROM info WHERE (ulevel= '1.3.10' or ulevel= '1.3.6') AND (@timestamp between '2017-06-05T07:00:00.000Z' and '2017-06-05T07:00:00.000Z')

Here is what I have:

"query": {
    "bool": {
        "must": [
            {
                 "query_string": {
                        "default_field": "_all",
                        "query": "*"
                                    },
                 "range": {
                         "@timestamp": {
                               "from": "2017-06-05T07:00:00.000Z",
                               "to": "2017-06-05T07:20:00.000Z"
                                        }
                     },
                "bool": {
                    "should": [
                        {"term": { "ulevel": "1.3.10"}},
                         {"term": { "ulevel": "1.3.6"}}
                             ]
                       }
            }
        ]
    }
  }

Does anyone have a solution?

Thank you so much.

Body:
You can use terms query for the first part and the range query for the second part

GET _search
{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "ulevel": [
              "1.3.10",
              "1.3.6"
            ]
          }
        },
        {
          "range": {
            "@timestamp": {
              "gte": "2017-06-05T07:00:00.000Z",
              "lte": "2017-06-05T07:20:00.000Z"
            }
          }
        }
      ]
    }
  },
  "from": 0,
  "size": 20
}

Some Notes :

Filters documents that have fields that match any of the provided terms (not analyzed)

Also you can use some date spesific formulation with rage filter. Please check the range query page https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html#ranges-on-dates more information.

Update:

Added from and size for comment question.


问:
how to get only user's photo list by Listview django
All.

I want to use Listview to show only user's photo list not other user's photo list. but it doesn't work. user can get other user's photo.

this is views.py

```<code>class PhotoListView(ListView):
model = Photo

def get(self, *args, **kwargs):

    #if user connect to other user's page, go to the user's page.
    if kwargs['username'] != self.request.user.username:
         return redirect('index')

    #to get only user's photo list.
    username = self.request.user.username
    return super(PhotoListView, self).get(username=username, *args, **kwargs)
</code>```

this is model.py

```<code>class Photo(models.Model):
    user = models.ForeignKey(User)
    image_file = ProcessedImageField(upload_to='%Y/%m/%d/orig', format='JPEG', options={'quality': 100})
    source = TaggableManager(through=Taggedsource, related_name='source')
    subject = TaggableManager(through=Taggedsubject, related_name='subject')
    description = models.TextField(max_length=500, blank=True)
    comments = models.PositiveSmallIntegerField(default=0, null=True)
    posted_on = models.DateTimeField(default=datetime.now)
</code>```

答:
You should edit the get_queryset method:

```<code>class PhotoListView(ListView):
    model = Photo

    def get_queryset(self):
        photos = super().get_queryset()
        username = self.request.user.username
        photos = photos.objects.filter(user=username)
        return photos

    def get(self, *args, **kwargs):

        #if user connect to other user's page, go to the user's page.
        if kwargs['username'] != self.request.user.username:
            return redirect('index')
</code>```

Body:
All.

I want to use Listview to show only user's photo list not other user's photo list. but it doesn't work. user can get other user's photo.

this is views.py

class PhotoListView(ListView):
model = Photo

def get(self, *args, **kwargs):

    #if user connect to other user's page, go to the user's page.
    if kwargs['username'] != self.request.user.username:
         return redirect('index')

    #to get only user's photo list.
    username = self.request.user.username
    return super(PhotoListView, self).get(username=username, *args, **kwargs)

this is model.py

class Photo(models.Model):
    user = models.ForeignKey(User)
    image_file = ProcessedImageField(upload_to='%Y/%m/%d/orig', format='JPEG', options={'quality': 100})
    source = TaggableManager(through=Taggedsource, related_name='source')
    subject = TaggableManager(through=Taggedsubject, related_name='subject')
    description = models.TextField(max_length=500, blank=True)
    comments = models.PositiveSmallIntegerField(default=0, null=True)
    posted_on = models.DateTimeField(default=datetime.now)

Body:
You should edit the get_queryset method:

class PhotoListView(ListView):
    model = Photo

    def get_queryset(self):
        photos = super().get_queryset()
        username = self.request.user.username
        photos = photos.objects.filter(user=username)
        return photos

    def get(self, *args, **kwargs):

        #if user connect to other user's page, go to the user's page.
        if kwargs['username'] != self.request.user.username:
            return redirect('index')