问:
Flash text field displaying incorrect characters
I've come across a strange error with a contact details form developed with Flash CS5 Prof. My keyboard layout is set up as English (UK) and pressing shift-2 gives me an ", shift-' gives me a @ in Chrome, Notepad, Word etc. In a text field on the flash form, entering shift-2 gives me @ but shift-' gives me ". I understand this is how the US keyboard is mapped out but it is confusing to my users.

How can I change the text field so that it works correctly for my keyboard layout?

答:
i didn't find a way to specify a locale in Flash, however the following code does what you want:</p>

```<code>package {
    import flash.display.Sprite;
    public class NewClass extends Sprite {
        public function NewClass() {
            addChild(new TextFieldReplacingChars());
        }
    }
}

import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.TextEvent;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;

class TextFieldReplacingChars extends Sprite {
    private var tf:TextField;
    private var toReplace:Object;
    private var str1:String = '';
    private var str2:String = '';
    private var pressedKeyCount: int = 0;
    private var timer:Timer;
    public function TextFieldReplacingChars() {
        tf = new TextField();
        addChild(tf);
        tf.type = 'input';
        tf.addEventListener(TextEvent.TEXT_INPUT, ontext);
        tf.addEventListener(KeyboardEvent.KEY_DOWN, onPress);
        tf.addEventListener(KeyboardEvent.KEY_UP, onRelease);
        toReplace = new Object();
        toReplace['"'] = '@';
        toReplace['@'] = '"';
        timer = new Timer(1, 1);
        timer.addEventListener(TimerEvent.TIMER_COMPLETE, updateText);
    }

    private function onRelease(e:KeyboardEvent):void {
        pressedKeyCount -= pressedKeyCount > 0 ? 1 : 0;
    }

    private function onPress(e:KeyboardEvent):void {
        pressedKeyCount += toReplace[String.fromCharCode(e.charCode)] ? 1 : 0;
    }

    private function ontext(e:TextEvent):void {
        if (toReplace[e.text] && pressedKeyCount > 0) {
            str1 = tf.text.substring(0, tf.caretIndex) + toReplace[e.text];
            str2 = tf.text.substring(tf.caretIndex, tf.text.length);
            timer.start();
        }
    }

    private function updateText(e:TimerEvent):void {
        tf.text = str1 + str2;
        tf.setSelection(str1.length, str1.length);
    }
}
</code>```

Body:
i didn't find a way to specify a locale in Flash, however the following code does what you want:

package {
    import flash.display.Sprite;
    public class NewClass extends Sprite {
        public function NewClass() {
            addChild(new TextFieldReplacingChars());
        }
    }
}

import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.TextEvent;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.Timer;

class TextFieldReplacingChars extends Sprite {
    private var tf:TextField;
    private var toReplace:Object;
    private var str1:String = '';
    private var str2:String = '';
    private var pressedKeyCount: int = 0;
    private var timer:Timer;
    public function TextFieldReplacingChars() {
        tf = new TextField();
        addChild(tf);
        tf.type = 'input';
        tf.addEventListener(TextEvent.TEXT_INPUT, ontext);
        tf.addEventListener(KeyboardEvent.KEY_DOWN, onPress);
        tf.addEventListener(KeyboardEvent.KEY_UP, onRelease);
        toReplace = new Object();
        toReplace['"'] = '@';
        toReplace['@'] = '"';
        timer = new Timer(1, 1);
        timer.addEventListener(TimerEvent.TIMER_COMPLETE, updateText);
    }

    private function onRelease(e:KeyboardEvent):void {
        pressedKeyCount -= pressedKeyCount > 0 ? 1 : 0;
    }

    private function onPress(e:KeyboardEvent):void {
        pressedKeyCount += toReplace[String.fromCharCode(e.charCode)] ? 1 : 0;
    }

    private function ontext(e:TextEvent):void {
        if (toReplace[e.text] && pressedKeyCount > 0) {
            str1 = tf.text.substring(0, tf.caretIndex) + toReplace[e.text];
            str2 = tf.text.substring(tf.caretIndex, tf.text.length);
            timer.start();
        }
    }

    private function updateText(e:TimerEvent):void {
        tf.text = str1 + str2;
        tf.setSelection(str1.length, str1.length);
    }
}


来源: stackexchange

问:
is there package exist in python to do RWR(random walk with restart)
is there some package or function that to compute RWR in python?
i want to compute RWR using weighted graph.
but i can't find RWR package in python.
plz tell me that package name if exist in python.
or please see me some example RWR in python.
thank you.</p>

答:
I would suggest you start here: SciPy Cookbook » Other examples » Brownian Motion.

If you are really looking for a comprehensive package, you might want to check out MMTK. But to be honest that is probably not what you are looking for (as it comes more from a Molecular Dynamics approach). There is no library for random walks for the simple reason that the integrator for the stochastic differential equation is easily written in 3 lines (by drawing random numbers from a normal distribution and adding them each step).

ContentLicense: CC BY-SA 3.0


问:
Overlay lines with a varying number of points from a list using ggplot2
I'd like to plot multiple lines with a varying number of points per line, with different colors using ggplot2. My MWE is given by

```<code>test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i) # Note - different number of points per line!!!!
}
</code>```

Note that The length for each vector in list are different. Then, is not possible to transform in data.frame.

答:
As there were some remarks about the for loops, here is an alternate and more sophisticated approach in a modern idiom (i.e. purrr from the tidyverse).

Creates an id vector as a factor (ids) so as to avoid warnings about combining levels later.

Sets up a function (mkdf) to make a data frame from an id variable and a vector of data.

Uses map2 from purrr to merge ids and the original data list with mkdf

Uses bind_rows from dplyr to merge the resulting list of data frames into one.

Plots it.

The code:

```<code>library(tidyr)

# dummpy up some wide data (but of different lengths) in a **list** of curves
test <- list()
for(i in 1:5){
  test[[i]] <- rnorm(10 - i)
}

# helper data (could do inline, but it would be harder to read)
ids <- as.factor(sprintf("id-%d",1:length(test)))             # curve ids as factors
mkdf <- function(x,y) data.frame(xx=1:length(x),yy=x,key=y)   # makes into dataframe

df <- test %>% map2(ids,mkdf) %>%  bind_rows()   #single pipe using purrr and dplyr

# plot it
ggplot(df) + geom_line(aes(x=xx,y=yy,color=key))
</code>```

A plot. I reduced the datasizes to make it easier to see:

Body:
I'd like to plot multiple lines with a varying number of points per line, with different colors using ggplot2. My MWE is given by

test <- list()
length(test) <- 10
for(i in 1:10){
  test[[i]] <- rnorm(100 - i) # Note - different number of points per line!!!!
}

Note that The length for each vector in list are different. Then, is not possible to transform in data.frame.

Body:
As there were some remarks about the for loops, here is an alternate and more sophisticated approach in a modern idiom (i.e. purrr from the tidyverse).

Creates an id vector as a factor (ids) so as to avoid warnings about combining levels later.

Sets up a function (mkdf) to make a data frame from an id variable and a vector of data.

Uses map2 from purrr to merge ids and the original data list with mkdf

Uses bind_rows from dplyr to merge the resulting list of data frames into one.

Plots it.

The code:

library(tidyr)

# dummpy up some wide data (but of different lengths) in a **list** of curves
test <- list()
for(i in 1:5){
  test[[i]] <- rnorm(10 - i)
}

# helper data (could do inline, but it would be harder to read)
ids <- as.factor(sprintf("id-%d",1:length(test)))             # curve ids as factors
mkdf <- function(x,y) data.frame(xx=1:length(x),yy=x,key=y)   # makes into dataframe

df <- test %>% map2(ids,mkdf) %>%  bind_rows()   #single pipe using purrr and dplyr

# plot it
ggplot(df) + geom_line(aes(x=xx,y=yy,color=key))

A plot. I reduced the datasizes to make it easier to see:


问:
Extjs 4.2 grid's state does not restore in Ext.window.Window view
I use ExtJS version is 4.2. I'm trying to save the state of a grid, which is item of a window. When I close the window, state of the grid is saved in cookies, but it doesn't get restored when window is opened again. What did I miss?

This is my code:

```<code>Ext.onReady(function () {
    Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));

    Ext.create('Ext.data.Store', {
        storeId: 'simpsonsStore',
        fields: ['name', 'email', 'phone'],
        data: {
            'items': [{
                'name': 'Lisa',
                "email": "lisa@simpsons.com",
                "phone": "555-111-1224"
            }, {
                'name': 'Bart',
                "email": "bart@simpsons.com",
                "phone": "555-222-1234"
            }, {
                'name': 'Homer',
                "email": "home@simpsons.com",
                "phone": "555-222-1244"
            }, {
                'name': 'Marge',
                "email": "marge@simpsons.com",
                "phone": "555-222-1254"
            }]
        },
        proxy: {
            type: 'memory',
            reader: {
                type: 'json',
                root: 'items'
            }
        }
    });

    Ext.create('Ext.container.Viewport', {
        items: [
            Ext.create('Ext.Button', {
                text: 'Click me',
                listeners: {
                    'click': function () {
                        var grid = Ext.create('Ext.grid.Panel', {
                            title: 'Simpsons',
                            store: Ext.data.StoreManager.lookup('simpsonsStore'),
                            columns: [{
                                text: 'Name',
                                dataIndex: 'name'
                            }, {
                                text: 'Email',
                                dataIndex: 'email',
                                flex: 1
                            }, {
                                text: 'Phone',
                                dataIndex: 'phone'
                            }],

                            stateful: true,
                            stateId: 'some_state_id'
                        });

                        var win = Ext.create('Ext.window.Window', {
                            title: 'Hello',
                            height: 200,
                            width: 900,
                            layout: 'fit',
                            items: grid
                        });

                        win.show();
                    }
                }
            })
        ]
    });
})
</code>```

Here is the fiddle: https://fiddle.sencha.com/#view/editor&fiddle/20sf

答:
On every button click you create a new window with entirely new grid which just seems the same but for the state manager is absolutely another grid. You may check that by logging grid component through the ComponentManager and seeing a different grid id each time you click the button:

```<code>console.log(Ext.ComponentQuery.query('grid'));
</code>```

To solve your problem I would recommend you to:

pull off the grid and window creation phase outside the button click

change window on close behaviour from destroy to hide by setting
    closeAction parameter to 'hide'

make your window component modal to prevent a user from another button click
    until the window is closed.

You may find corrected fiddle here and code below:

```<code>Ext.onReady(function () {
    Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));

    var store = Ext.create('Ext.data.Store', {
        storeId: 'simpsonsStore',
        fields: ['name', 'email', 'phone'],
        data: {
            'items': [{
                'name': 'Lisa',
                "email": "lisa@simpsons.com",
                "phone": "555-111-1224"
            }, {
                'name': 'Bart',
                "email": "bart@simpsons.com",
                "phone": "555-222-1234"
            }, {
                'name': 'Homer',
                "email": "home@simpsons.com",
                "phone": "555-222-1244"
            }, {
                'name': 'Marge',
                "email": "marge@simpsons.com",
                "phone": "555-222-1254"
            }]
        },
        proxy: {
            type: 'memory',
            reader: {
                type: 'json',
                root: 'items'
            }
        }
    });

    var grid = Ext.create('Ext.grid.Panel', {
        title: 'Simpsons',
        store: store,
        columns: [{
            text: 'Name',
            dataIndex: 'name'
        }, {
            text: 'Email',
            dataIndex: 'email',
            flex: 1
        }, {
            text: 'Phone',
            dataIndex: 'phone'
        }],

        stateful: true,
        stateId: 'some_state_id'
    });

    var win = Ext.create('Ext.window.Window', {
        title: 'Hello',
        height: 200,
        width: 400,
        modal: true,
        layout: 'fit',
        closeAction: 'hide',
        items: grid
    });

    Ext.create('Ext.container.Viewport', {
        items: [
            Ext.create('Ext.Button', {
                text: 'Click me',
                listeners: {
                    'click': function () {
                        // console.log(Ext.ComponentQuery.query('grid'));
                        win.show();
                    }
                }
            })
        ]
    });
})
</code>```

Body:
I use ExtJS version is 4.2. I'm trying to save the state of a grid, which is item of a window. When I close the window, state of the grid is saved in cookies, but it doesn't get restored when window is opened again. What did I miss?

This is my code:

Ext.onReady(function () {
    Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));

    Ext.create('Ext.data.Store', {
        storeId: 'simpsonsStore',
        fields: ['name', 'email', 'phone'],
        data: {
            'items': [{
                'name': 'Lisa',
                "email": "lisa@simpsons.com",
                "phone": "555-111-1224"
            }, {
                'name': 'Bart',
                "email": "bart@simpsons.com",
                "phone": "555-222-1234"
            }, {
                'name': 'Homer',
                "email": "home@simpsons.com",
                "phone": "555-222-1244"
            }, {
                'name': 'Marge',
                "email": "marge@simpsons.com",
                "phone": "555-222-1254"
            }]
        },
        proxy: {
            type: 'memory',
            reader: {
                type: 'json',
                root: 'items'
            }
        }
    });

    Ext.create('Ext.container.Viewport', {
        items: [
            Ext.create('Ext.Button', {
                text: 'Click me',
                listeners: {
                    'click': function () {
                        var grid = Ext.create('Ext.grid.Panel', {
                            title: 'Simpsons',
                            store: Ext.data.StoreManager.lookup('simpsonsStore'),
                            columns: [{
                                text: 'Name',
                                dataIndex: 'name'
                            }, {
                                text: 'Email',
                                dataIndex: 'email',
                                flex: 1
                            }, {
                                text: 'Phone',
                                dataIndex: 'phone'
                            }],

                            stateful: true,
                            stateId: 'some_state_id'
                        });

                        var win = Ext.create('Ext.window.Window', {
                            title: 'Hello',
                            height: 200,
                            width: 900,
                            layout: 'fit',
                            items: grid
                        });

                        win.show();
                    }
                }
            })
        ]
    });
})

Here is the fiddle: https://fiddle.sencha.com/#view/editor&fiddle/20sf

Body:
On every button click you create a new window with entirely new grid which just seems the same but for the state manager is absolutely another grid. You may check that by logging grid component through the ComponentManager and seeing a different grid id each time you click the button:

console.log(Ext.ComponentQuery.query('grid'));

To solve your problem I would recommend you to:

pull off the grid and window creation phase outside the button click

change window on close behaviour from destroy to hide by setting
    closeAction parameter to 'hide'

make your window component modal to prevent a user from another button click
    until the window is closed.

You may find corrected fiddle here and code below:

Ext.onReady(function () {
    Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));

    var store = Ext.create('Ext.data.Store', {
        storeId: 'simpsonsStore',
        fields: ['name', 'email', 'phone'],
        data: {
            'items': [{
                'name': 'Lisa',
                "email": "lisa@simpsons.com",
                "phone": "555-111-1224"
            }, {
                'name': 'Bart',
                "email": "bart@simpsons.com",
                "phone": "555-222-1234"
            }, {
                'name': 'Homer',
                "email": "home@simpsons.com",
                "phone": "555-222-1244"
            }, {
                'name': 'Marge',
                "email": "marge@simpsons.com",
                "phone": "555-222-1254"
            }]
        },
        proxy: {
            type: 'memory',
            reader: {
                type: 'json',
                root: 'items'
            }
        }
    });

    var grid = Ext.create('Ext.grid.Panel', {
        title: 'Simpsons',
        store: store,
        columns: [{
            text: 'Name',
            dataIndex: 'name'
        }, {
            text: 'Email',
            dataIndex: 'email',
            flex: 1
        }, {
            text: 'Phone',
            dataIndex: 'phone'
        }],

        stateful: true,
        stateId: 'some_state_id'
    });

    var win = Ext.create('Ext.window.Window', {
        title: 'Hello',
        height: 200,
        width: 400,
        modal: true,
        layout: 'fit',
        closeAction: 'hide',
        items: grid
    });

    Ext.create('Ext.container.Viewport', {
        items: [
            Ext.create('Ext.Button', {
                text: 'Click me',
                listeners: {
                    'click': function () {
                        // console.log(Ext.ComponentQuery.query('grid'));
                        win.show();
                    }
                }
            })
        ]
    });
})


问:
Iterate over a List of Maps using s:iterator
I'm trying to iterate through a List of Maps using s:iterator. I can iterate through the List without problems, but I can not get it to iterate through the entries of the map. So far I've got this:

```<code>[..]
<s:iterator value="records" status="recordsStatus" var="record">
        <s:if test="#recordsStatus.index ==0">
            <tr>
                <td colspan="*"></td>
            </tr>
        </s:if>
        <tr>
            <s:iterator value="record.entrySet()" status="fieldStatus">
            <td>
                <s:property value="key"/>/<s:property value="value"/>
            </td>
            </s:iterator>
        </tr>
    </s:iterator>
[..]
</code>```

The tag generates the

```<code><tr></tr>
</code>```

for each entry, but it is not going throug the second iterator, so I suppose I'm doing something wrong with the value attribute. Can you help me with it?

Thanks

Jose

答:
Here is a demo that loops through lists of map:

import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class mapTest extends ActionSupport {
  public List<Map> listmap;

  public String execute(){
    listmap = new ArrayList();
    Map map = new HashMap();
    map.put("a", "alpha");
    map.put("b", "bravo");
    map.put("c", "charlie");
    listmap.add(map);
    Map map2 = new HashMap();
    map2.put("d", "delta");
    map2.put("e", "echo");
    map2.put("f", "foxtrot");
    listmap.add(map2);
    return SUCCESS;
  }
}
```

<p>Here is the JSP to render it:</p>

<pre class="lang-xml prettyprint-override"><code><%@taglib prefix="s" uri="/struts-tags"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <body>
        <h1>Map Test</h1>
        <table>
            <thead>
                <tr>
                    <th>List #</th>
                    <th>key</th>
                    <th>value</th>
                </tr>
            </thead>
            <tbody>
                <s:iterator value="listmap" status="stat">
                    <s:iterator>
                        <tr>
                            <th><s:property value="#stat.index"/></th>
                            <td><s:property value="key"/></td>
                            <td><s:property value="value"/></td>
                        </tr>
                    </s:iterator>
                </s:iterator>
            </tbody>
        </table>
    </body>
</html>
</code>```

Note the inner iterator is context sensitive it will use the last value pushed onto the stack. The status attribute gives us a IteratorStatus object each iteration which is useful if we want to know the current iteration.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to iterate through a List of Maps using s:iterator. I can iterate through the List without problems, but I can not get it to iterate through the entries of the map. So far I've got this:

[..]
<s:iterator value="records" status="recordsStatus" var="record">
        <s:if test="#recordsStatus.index ==0">

        </s:if>

            <s:iterator value="record.entrySet()" status="fieldStatus">

                <s:property value="key"/>/<s:property value="value"/>

            </s:iterator>

    </s:iterator>
[..]

The tag generates the

for each entry, but it is not going throug the second iterator, so I suppose I'm doing something wrong with the value attribute. Can you help me with it?

Thanks

Jose

Body:
Here is a demo that loops through lists of map:

import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class mapTest extends ActionSupport {
  public List<Map> listmap;

  public String execute(){
    listmap = new ArrayList();
    Map map = new HashMap();
    map.put("a", "alpha");
    map.put("b", "bravo");
    map.put("c", "charlie");
    listmap.add(map);
    Map map2 = new HashMap();
    map2.put("d", "delta");
    map2.put("e", "echo");
    map2.put("f", "foxtrot");
    listmap.add(map2);
    return SUCCESS;
  }
}

Here is the JSP to render it:

<%@taglib prefix="s" uri="/struts-tags"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <body>
        <h1>Map Test</h1>
        <table>
            <thead>
                <tr>
                    <th>List #</th>
                    <th>key</th>
                    <th>value</th>
                </tr>
            </thead>
            <tbody>
                <s:iterator value="listmap" status="stat">
                    <s:iterator>
                        <tr>
                            <th><s:property value="#stat.index"/></th>
                            <td><s:property value="key"/></td>
                            <td><s:property value="value"/></td>
                        </tr>
                    </s:iterator>
                </s:iterator>
            </tbody>
        </table>
    </body>
</html>

Note the inner iterator is context sensitive it will use the last value pushed onto the stack. The status attribute gives us a IteratorStatus object each iteration which is useful if we want to know the current iteration.


问:
Couldn't find ionic.config.json file. Are you in an Ionic project?
I am new to Ionic and trying to run ionic serve to test my application but I keep getting this error:

```<code>Couldn't find ionic.config.json file. Are you in an Ionic project?
</code>```

On running ionic info, I get the following:

```<code> $ ionic info
******************************************************
 Dependency warning - for the CLI to run correctly,
 it is highly recommended to install/upgrade the following:

 Please update your Cordova CLI to version  >=4.2.0 `npm install -g cordova`

******************************************************

Your system information:

Cordova CLI: undefined
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.1.7
OS: Windows 7
Node Version: v4.4.5
</code>```

Tried it with Couldn't find ionic.config.json file but couldn't resolve the issue.

I am also getting this trace while creating an application with ionic start myApp tabs:

```<code>Installing npm packages (may take a minute or two)...
Error with start Error: spawn UNKNOWN
    at exports._errnoException (util.js:870:11)
    at ChildProcess.spawn (internal/child_process.js:298:11)
    at Object.exports.spawn (child_process.js:362:9)
    at spawn (C:\Users\user\AppData\Roaming\npm\node_modules\ionic\node_modules\                                                            ionic-app-lib\node_modules\cross-spawn\index.js:17:18)
    at Object.runSpawnCommand (C:\Users\user\AppData\Roaming\npm\node_modules\io                                                            nic\node_modules\ionic-app-lib\lib\start.js:56:17)
    at C:\Users\user\AppData\Roaming\npm\node_modules\ionic\node_modules\ionic-a                                                            pp-lib\lib\start.js:104:20
    at _fulfilled (C:\Users\user\AppData\Roaming\npm\node_modules\ionic\node_mod                                                            ules\q\q.js:787:54)
    at self.promiseDispatch.done (C:\Users\user\AppData\Roaming\npm\node_modules                                                            \ionic\node_modules\q\q.js:816:30)
    at Promise.promise.promiseDispatch (C:\Users\user\AppData\Roaming\npm\node_m                                                            odules\ionic\node_modules\q\q.js:749:13)
    at C:\Users\user\AppData\Roaming\npm\node_modules\ionic\node_modules\q\q.js:                                                            557:44
</code>```

Can someone please help here.

答:
Make sure your node version is above v6. Then in the root of your ionic project run ionic info.

It should give you a prompt something like "Looks like this is an Ionic Angular project, would you like to install @ionic/cli-plugin-ionic-angular and continue?"

Type yes

It should have ran the following command for you: npm install --save-dev --save-exact @ionic/cli-plugin-ionic-angular@latest

Now you can run ionic serve and it will work.

p.s above is from my experience, had the same issue and the above sorted it out. Hope this is useful.

Body:
I am new to Ionic and trying to run ionic serve to test my application but I keep getting this error:

Couldn't find ionic.config.json file. Are you in an Ionic project?

On running ionic info, I get the following:

 $ ionic info
******************************************************
 Dependency warning - for the CLI to run correctly,
 it is highly recommended to install/upgrade the following:

 Please update your Cordova CLI to version  >=4.2.0 `npm install -g cordova`

******************************************************

Your system information:

Cordova CLI: undefined
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.1.7
OS: Windows 7
Node Version: v4.4.5

Tried it with Couldn't find ionic.config.json file but couldn't resolve the issue.

I am also getting this trace while creating an application with ionic start myApp tabs:

Installing npm packages (may take a minute or two)...
Error with start Error: spawn UNKNOWN
    at exports._errnoException (util.js:870:11)
    at ChildProcess.spawn (internal/child_process.js:298:11)
    at Object.exports.spawn (child_process.js:362:9)
    at spawn (C:\Users\user\AppData\Roaming\npm\node_modules\ionic\node_modules\                                                            ionic-app-lib\node_modules\cross-spawn\index.js:17:18)
    at Object.runSpawnCommand (C:\Users\user\AppData\Roaming\npm\node_modules\io                                                            nic\node_modules\ionic-app-lib\lib\start.js:56:17)
    at C:\Users\user\AppData\Roaming\npm\node_modules\ionic\node_modules\ionic-a                                                            pp-lib\lib\start.js:104:20
    at _fulfilled (C:\Users\user\AppData\Roaming\npm\node_modules\ionic\node_mod                                                            ules\q\q.js:787:54)
    at self.promiseDispatch.done (C:\Users\user\AppData\Roaming\npm\node_modules                                                            \ionic\node_modules\q\q.js:816:30)
    at Promise.promise.promiseDispatch (C:\Users\user\AppData\Roaming\npm\node_m                                                            odules\ionic\node_modules\q\q.js:749:13)
    at C:\Users\user\AppData\Roaming\npm\node_modules\ionic\node_modules\q\q.js:                                                            557:44

Can someone please help here.


问:
Swift3 Use of unresolved identifier 'Date'
I am trying to get Date in Swift3 using

```<code>let date = Date()
</code>```

but it is showing "error: use of unresolved identifier 'Date'" How to resolve it?

答:
import foundation  doesn't work
but
import Foundation work perfectly

modules are case sensitive .

Body:
I am trying to get Date in Swift3 using

let date = Date()

but it is showing "error: use of unresolved identifier 'Date'" How to resolve it?


问:
Rails not indexing locations
So I tried to add this code to first the views and then the controller. It didn't work and gave me an error : undefined method save for 4:Fixnum.

Code:

```<code><% unless location.user.interests.blank? %>
  <% @merged_array = location.user.interests.split(',').uniq +
                       current_user.interests.split(',').uniq %>
  <% location.score = @merged_array.length - @merged_array.uniq.length %>
  <% location.score.save %>
<% else %>
  <% location.score = 0 %>
  <% location.score.save %>
<% end %>
</code>```

But then I removed it from both controller and views..... Now the index page isn't showing the locations at all I checked and the show page is working and records still exist

答:
This is really not the way it should work.

Just read a bit about the MVC pattern - it's worth it!

You shouldn't check in production credentials into your repository - especially not if it is public.

Checkout https://github.com/bkeepers/dotenv to keep your keys and passwords privately.

You should change your passwords immediately!

The error you got is because location.score is an integer not an object - location.save! will save the object with its new score.

PS: You don't want to be the guy who let production creds into the guide for new employees. https://www.reddit.com/r/cscareerquestions/comments/6ez8ag/accidentally_destroyed_production_database_on/

Beside of that, Keep going!

ContentLicense: CC BY-SA 4.0

Title: Rails not indexing locations

Body:
So I tried to add this code to first the views and then the controller. It didn't work and gave me an error : undefined method save for 4:Fixnum.

Code:

<% unless location.user.interests.blank? %>
  <% @merged_array = location.user.interests.split(',').uniq +
                       current_user.interests.split(',').uniq %>
  <% location.score = @merged_array.length - @merged_array.uniq.length %>
  <% location.score.save %>
<% else %>
  <% location.score = 0 %>
  <% location.score.save %>
<% end %>

But then I removed it from both controller and views..... Now the index page isn't showing the locations at all I checked and the show page is working and records still exist


问:
Android text veiw in linear layout
I am having trouble placing two textveiw below each other. I tried using
android:Layout_below="@+id/title" but the second textview always gets placed far off and not below first text view. How do I place the two textveiws exactly below each other?

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#453b4da7"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/ThumbnailView"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_margin="0dp"
                android:background="@drawable/ic_launcher" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ThumbnailView"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="loading City"
                android:textColor="#FF040404"
                android:textSize="15dip"
                android:textStyle="bold"
                android:typeface="sans" />

            <TextView
                android:id="@+id/location"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_marginTop="20dip"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="Loading Locality"
                android:textColor="#343434"
                android:textSize="10dip" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>
</code>```

答:
You used to linear layout and have different orientation. Just give orientation vertical to linear layout and put image view in another linear layout that should be horizontal with a vertical linear layout.
Pseudo code is like this

```<code>Linear layout horizontal
 Child 1 : Image View
 Child 2 : Linear layout vertical
          c1: text view
          c2: text view
</code>```

Hope this will helpful and sorry if pseudo code is not so clear.

Title: Android text veiw in linear layout

Body:
I am having trouble placing two textveiw below each other. I tried using
android:Layout_below="@+id/title" but the second textview always gets placed far off and not below first text view. How do I place the two textveiws exactly below each other?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#453b4da7"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/ThumbnailView"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_margin="0dp"
                android:background="@drawable/ic_launcher" />

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/ThumbnailView"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="loading City"
                android:textColor="#FF040404"
                android:textSize="15dip"
                android:textStyle="bold"
                android:typeface="sans" />

            <TextView
                android:id="@+id/location"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/title"
                android:layout_marginTop="20dip"
                android:layout_toRightOf="@+id/ThumbnailView"
                android:text="Loading Locality"
                android:textColor="#343434"
                android:textSize="10dip" />

        </LinearLayout>

    </LinearLayout>

</FrameLayout>

Body:
You used to linear layout and have different orientation. Just give orientation vertical to linear layout and put image view in another linear layout that should be horizontal with a vertical linear layout.
Pseudo code is like this

Linear layout horizontal
 Child 1 : Image View
 Child 2 : Linear layout vertical
          c1: text view
          c2: text view

Hope this will helpful and sorry if pseudo code is not so clear.


问:
SQL ORACLE Get week numbers from multiple datetime rows
I have 70.000 rows of data, including a date time column (YYYY-MM-DD HH24-MM-SS.).
I want to split this data into 3 separate columns; Hour, day and Week number.

The date time column name is 'REGISTRATIONDATE' from the table 'CONTRACTS'.

This is what I have so far for the day and hour columns:

```<code>SELECT substr(REGISTRATIONDATE, 0, 10) AS "Date",
substr(REGISTRATIONDATE, 11, 9) AS "Hour"
FROM CONTRACTS;
</code>```

I have seen the options to get a week number for specific dates, this assignment concerns 70.000 dates so this is not an option.

答:
You (the OP) still have to explain what week number to assign to the first few days in a year, until the first Monday of the year. Do you assign a week number for the prior calendar year? In a Comment I asked about January 1, 2017, as an example; that was a Sunday. The week from January 2 to January 8 of 2017 is "week 1" according to your definition; what week number do you assign to Sunday, January 1, 2017?

The straightforward calculation below assigns to it week number 0. Other than that, the computation is trivial.

Notes: To find the Monday of the week for any given date dt, we can use trunc(dt, 'iw'). iw stands for ISO Week, standard week which starts on Monday and ends on Sunday.

Then: To find the first Monday of the year, we can start with the date January 7 and ask for the Monday of the week in which January 7 falls. (I won't explain that one - it's easy logic and it has nothing to do with programming.)

To input a fixed date, the best way is with the date literal syntax: date '2017-01-07' for January 7. Please check the Oracle documentation for "date literals" if you are not familiar with it.

So: to find the week number for any date dt, compute

```<code>1 + ( trunc(dt, 'iw') - trunc(date '2017-01-07', 'iw') ) / 7
</code>```

This formula finds the Monday of the ISO Week of dt and subtracts the first Monday of the year - using Oracle date arithmetic, where the difference between two dates is the number of days between them. So to find the number of weeks we divide by 7; and to have the first Monday be assigned the number 1, instead of 0, we need to add 1 to the result of dividing by 7.

The other issue you will have to address is to convert your strings into dates. The best solution would be to fix the data model itself (change the data type of the column so that it is DATE instead of VARCHAR2); then all the bits of data you need could be extracted more easily, you would make sure you don't have dates like '2017-02-29 12:30:00' in your data (currently, if you do, you will have a very hard time making any date calculations work), queries will be a lot faster, etc. Anyway, that's an entirely different issue so I'll leave it out of this discussion.

Body:
I have 70.000 rows of data, including a date time column (YYYY-MM-DD HH24-MM-SS.).
I want to split this data into 3 separate columns; Hour, day and Week number.

The date time column name is 'REGISTRATIONDATE' from the table 'CONTRACTS'.

This is what I have so far for the day and hour columns:

SELECT substr(REGISTRATIONDATE, 0, 10) AS "Date",
substr(REGISTRATIONDATE, 11, 9) AS "Hour"
FROM CONTRACTS;

I have seen the options to get a week number for specific dates, this assignment concerns 70.000 dates so this is not an option.

Body:
You (the OP) still have to explain what week number to assign to the first few days in a year, until the first Monday of the year. Do you assign a week number for the prior calendar year? In a Comment I asked about January 1, 2017, as an example; that was a Sunday. The week from January 2 to January 8 of 2017 is "week 1" according to your definition; what week number do you assign to Sunday, January 1, 2017?

The straightforward calculation below assigns to it week number 0. Other than that, the computation is trivial.

Notes: To find the Monday of the week for any given date dt, we can use trunc(dt, 'iw'). iw stands for ISO Week, standard week which starts on Monday and ends on Sunday.

Then: To find the first Monday of the year, we can start with the date January 7 and ask for the Monday of the week in which January 7 falls. (I won't explain that one - it's easy logic and it has nothing to do with programming.)

To input a fixed date, the best way is with the date literal syntax: date '2017-01-07' for January 7. Please check the Oracle documentation for "date literals" if you are not familiar with it.

So: to find the week number for any date dt, compute

1 + ( trunc(dt, 'iw') - trunc(date '2017-01-07', 'iw') ) / 7

This formula finds the Monday of the ISO Week of dt and subtracts the first Monday of the year - using Oracle date arithmetic, where the difference between two dates is the number of days between them. So to find the number of weeks we divide by 7; and to have the first Monday be assigned the number 1, instead of 0, we need to add 1 to the result of dividing by 7.

The other issue you will have to address is to convert your strings into dates. The best solution would be to fix the data model itself (change the data type of the column so that it is DATE instead of VARCHAR2); then all the bits of data you need could be extracted more easily, you would make sure you don't have dates like '2017-02-29 12:30:00' in your data (currently, if you do, you will have a very hard time making any date calculations work), queries will be a lot faster, etc. Anyway, that's an entirely different issue so I'll leave it out of this discussion.


问:
How "perfect" does a database have to be?
I'm designing a website to track weight lifting and calories. I've never designed my own database before and I figured I should get is as spot on as possible before I start coding. Every time I think I'm done, I get antsy that it's not perfect. I've mostly fleshed it out in MySQL Workbench but I still have a few questions.

How important is it to make the
database "perfect" before hand? How
hard is it to re-factor a database
later?

What does the engine option do? Right
now all tables are defaulting to
InnoDB engine? Any issues with this?

Are dataypes changeable after data
entry? Maybe not going from VARCHAR
to INT, but what about VARCHAR(45) to
VARCHAR(255)?

What are basic database rules that HAVE to
be followed for a successful design?

I've also attached my ERM diagram. If anyone could point out any obvious irregularities it would be greatly appreciated.

答: Start as perfect as you can make it, then make it as imperfect as you need it.</p>


问:
How do I calculate power-of in C#?
I'm not that great with maths and C# doesn't seem to provide a power-of function
so I was wondering if anyone knows how I would run a calculation like this:</p>

```<code>var dimensions = ((100*100) / (100.00^3.00));
</code>```

答:
Do not use Math.Pow

When i use

```<code>for (int i = 0; i < 10e7; i++)
{
    var x3 = x * x * x;
    var y3 = y * y * y;
}
</code>```

It only takes 230 ms whereas the following takes incredible 7050 ms:

```<code>for (int i = 0; i < 10e7; i++)
{
    var x3 = Math.Pow(x, 3);
    var y3 = Math.Pow(x, 3);
}
</code>```

Title: How do I calculate power-of in C#?

Body:
I'm not that great with maths and C# doesn't seem to provide a power-of function
so I was wondering if anyone knows how I would run a calculation like this:

var dimensions = ((100*100) / (100.00^3.00));

Body:
Do not use Math.Pow

When i use

for (int i = 0; i < 10e7; i++)
{
    var x3 = x * x * x;
    var y3 = y * y * y;
}

It only takes 230 ms whereas the following takes incredible 7050 ms:

for (int i = 0; i < 10e7; i++)
{
    var x3 = Math.Pow(x, 3);
    var y3 = Math.Pow(x, 3);
}


问:
Compare this.state to a function to apply style
I am using a function to filter values.

If I map over the function filteredMovies, it removes the genre buttons and movies which do not apply.

However, instead of removing them I want to a custom className. I want to apply a different style to <Filter1> & <Movies>. What is the correct way to do this?

I've put this inside a codesandbox (https://codesandbox.io/s/76ZjOyBvA)

Example 1:

Compare this.state.movies

```<code>  {this.uniqueGenres1(this.state.movies).map(e => (
    <Filter1
      key={e.id}
    />
  ))}
</code>```

To filteredMovies

```<code>  {this.uniqueGenres1(filteredMovies).map(e => (
    <Filter1
      key={e.id}
    />
  ))}
</code>```

For the values that do NOT appear in filteredMovies, apply a different className

答:
Use the className attribute of React:

```<code>class Filter1 extends React.Component {
  handleClick = () => {
    this.props.onChange(this.props.genre.name);
  };

  render() {
    const { genre, isActive } = this.props;

return (
  <button onClick={this.handleClick} className={isActive? 'active' : 'inactive'}>
    {genre.name}
    {' '}
    <strong>{isActive ? 'Active' : 'Inactive'}</strong>
  </button>
);
</code>```

}
}

Also, don't forget to change 'filteredMovies' to 'movies' in the second map:

```<code>         <h3> Using filteredMovies function</h3>
  {this.uniqueGenres1(movies).map(e => (
    <Filter1
      key={e.id}
      genre={e}
      isActive={!!selectedFilters[e.name]}
      value={e.type}
      onChange={this.handleChange}
    />
  ))}
</code>```

Update:

To apply a css style to the
s rather than hiding them, change the relevant sections in your code to these:

```<code>class Result extends React.Component {
  render() {
    const { result, isActive } = this.props;

    return (
      <div>
        <li className={isActive? 'active' : 'inactive'}>
          {result.name} {' '}
          ({result.genres.map(x => x.name).join(', ')}){' '}
        </li>

      </div>
    );
  }
}

    {movies.map(movie =>  {
  var isActive = !!filteredMovies.find(filteredrMovie => filteredrMovie.name === movie.name);
  return (
      <Result key={movie.id} result={movie} isActive={isActive} />
    )
})}
</code>```

It basically uses the JS find function to know if a movie from the filtered lists exists in the entire one. Then it passes the result as a prop to the Result component.

Update2:

In order to style your buttons based on rather or not they exist in the results rather than if they active:

```<code><h3>Using filteredResults function</h3>
        {this.uniqueGenres(filteredResults).map(genre => {
          const isExisting = !!this.uniqueGenres(allFilters).find(
            genre1 => genre1 === genre,
          );
         return (
          <Filter1
            key={genre.id}
            genre={genre}
            isActive={!!selectedFilters[genre.name]}
            isExisting={isExisting}
            onChange={genre.handleChange}
          />
         )})}
</code>```

Replace 'allFilters' with the correct name of the variable that contains the complete list.

Update3:

It's working for me now after changing the code of Filter1 component, so it will resolve the className based on 'isExisting':

```<code>class Filter1 extends React.Component {
  handleClick = () => {
    this.props.onChange(this.props.genre);
  };

  render() {
    const { genre, isActive, isExisting } = this.props;

    return (
      <button onClick={this.handleClick} className={isExisting ? 'existing' : 'notExisting'}>
        {genre.name}
        {' '}
        <strong>{isActive ? 'Active' : 'Inactive'}</strong>
      </button>
    );
  }
}
</code>```

Body:
I am using a function to filter values.

If I map over the function filteredMovies, it removes the genre buttons and movies which do not apply.

However, instead of removing them I want to a custom className. I want to apply a different style to <Filter1> & <Movies>. What is the correct way to do this?

I've put this inside a codesandbox (https://codesandbox.io/s/76ZjOyBvA)

Example 1:

Compare this.state.movies

  {this.uniqueGenres1(this.state.movies).map(e => (
    <Filter1
      key={e.id}
    />
  ))}

To filteredMovies

  {this.uniqueGenres1(filteredMovies).map(e => (
    <Filter1
      key={e.id}
    />
  ))}

For the values that do NOT appear in filteredMovies, apply a different className

Body:
Use the className attribute of React:

class Filter1 extends React.Component {
  handleClick = () => {
    this.props.onChange(this.props.genre.name);
  };

  render() {
    const { genre, isActive } = this.props;

return (
  <button onClick={this.handleClick} className={isActive? 'active' : 'inactive'}>
    {genre.name}
    {' '}
    <strong>{isActive ? 'Active' : 'Inactive'}</strong>
  </button>
);

}
}

Also, don't forget to change 'filteredMovies' to 'movies' in the second map:

         <h3> Using filteredMovies function</h3>
  {this.uniqueGenres1(movies).map(e => (
    <Filter1
      key={e.id}
      genre={e}
      isActive={!!selectedFilters[e.name]}
      value={e.type}
      onChange={this.handleChange}
    />
  ))}

Update:

To apply a css style to the <li>s rather than hiding them, change the relevant sections in your code to these:

class Result extends React.Component {
  render() {
    const { result, isActive } = this.props;

    return (
      <div>
        <li className={isActive? 'active' : 'inactive'}>
          {result.name} {' '}
          ({result.genres.map(x => x.name).join(', ')}){' '}
        </li>

      </div>
    );
  }
}

    {movies.map(movie =>  {
  var isActive = !!filteredMovies.find(filteredrMovie => filteredrMovie.name === movie.name);
  return (
      <Result key={movie.id} result={movie} isActive={isActive} />
    )
})}

It basically uses the JS find function to know if a movie from the filtered lists exists in the entire one. Then it passes the result as a prop to the Result component.

Update2:

In order to style your buttons based on rather or not they exist in the results rather than if they active:

<h3>Using filteredResults function</h3>
        {this.uniqueGenres(filteredResults).map(genre => {
          const isExisting = !!this.uniqueGenres(allFilters).find(
            genre1 => genre1 === genre,
          );
         return (
          <Filter1
            key={genre.id}
            genre={genre}
            isActive={!!selectedFilters[genre.name]}
            isExisting={isExisting}
            onChange={genre.handleChange}
          />
         )})}

Replace 'allFilters' with the correct name of the variable that contains the complete list.

Update3:

It's working for me now after changing the code of Filter1 component, so it will resolve the className based on 'isExisting':

class Filter1 extends React.Component {
  handleClick = () => {
    this.props.onChange(this.props.genre);
  };

  render() {
    const { genre, isActive, isExisting } = this.props;

    return (
      <button onClick={this.handleClick} className={isExisting ? 'existing' : 'notExisting'}>
        {genre.name}
        {' '}
        <strong>{isActive ? 'Active' : 'Inactive'}</strong>
      </button>
    );
  }
}


问:
Auto add alt on images
When I add

```<code>$(document).ready(function() {
$('#readerareaimg img').each(function(){
var filename = $img.attr('src')
$img.attr('title', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
$img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
});
</code>```

My website will generate alt and title tags automatically on images based on their file name, but I want to add any word before the file name.
For example file name is comic.jpg and I will display alt="comic", but i want that alt to become alt="read comic".

Can someone explain how to make this? Please, sir :3

答:
You can use '+' sign in the where you put value of attribute. </p>

```<code>$img.attr('alt', 'required word'+filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
</code>```

<p>or </p>

```<code>$img.attr('alt',filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.'))+'required word');
</code>```

Title: Auto add alt on images

Body:
When I add

$(document).ready(function() {
$('#readerareaimg img').each(function(){
var filename = $img.attr('src')
$img.attr('title', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
$img.attr('alt', filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));
});

My website will generate alt and title tags automatically on images based on their file name, but I want to add any word before the file name.
For example file name is comic.jpg and I will display alt="comic", but i want that alt to become alt="read comic".

Can someone explain how to make this? Please, sir :3

Body:
You can use '+' sign in the where you put value of attribute.

$img.attr('alt', 'required word'+filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.')));

or

$img.attr('alt',filename.substring((filename.lastIndexOf('/'))+1, filename.lastIndexOf('.'))+'required word');


问:
Write a recursive function that takes an array and displays the elements in reverse order without starting the index of the array at the end
My question is: Am I doing this right or not?
Because no one can tell me exactly...

Write a recursive function that takes an array and displays the elements in reverse order
without starting the index of the array at the end. (In other words, don’t write the equivalent of
a loop that starts printing at the end of the array.)

```<code>int bleah(int arr[], int number)
{
    cout << arr[number] << ' ';
    if (number <= 0)
    {
        return 1;
    }
    cout << arr[number] << ' ';
    return bleah(arr, number - 1);
}

int main()
{
    int arr[31] = {0};
    for (int i = 0; i <= 30; i++)
    {
        arr[i] = i;
    }
    bleah(arr, 30);

    cin.get();
    cin.ignore();
    return 0;
}
</code>```

答:
You are doing it exactlly like you didn't want to. you said you was asked to write a recursive function that not starting at the end, but you send the last cell.

try use the recursive like this:

```<code>void bleah(int arr[], int number)
{
    if (number != arr.length()-1)
        bleah(arr, number + 1);
    cout << arr[number] << ' ';
}
</code>```

and call it:

```<code>bleah(arr, 0);
</code>```

Body:
My question is: Am I doing this right or not?
Because no one can tell me exactly...

Write a recursive function that takes an array and displays the elements in reverse order
without starting the index of the array at the end. (In other words, don’t write the equivalent of
a loop that starts printing at the end of the array.)

int bleah(int arr[], int number)
{
    cout << arr[number] << ' ';
    if (number <= 0)
    {
        return 1;
    }
    cout << arr[number] << ' ';
    return bleah(arr, number - 1);
}

int main()
{
    int arr[31] = {0};
    for (int i = 0; i <= 30; i++)
    {
        arr[i] = i;
    }
    bleah(arr, 30);

    cin.get();
    cin.ignore();
    return 0;
}

Body:
You are doing it exactlly like you didn't want to. you said you was asked to write a recursive function that not starting at the end, but you send the last cell.

try use the recursive like this:

void bleah(int arr[], int number)
{
    if (number != arr.length()-1)
        bleah(arr, number + 1);
    cout << arr[number] << ' ';
}

and call it:

bleah(arr, 0);


问:
Electron webview preload log DOM
I am using a webview in my index.html file in my Electron program. The webview has a preloader and I simply want to be able to manipulate the DOM of the webview (not index.html).

I have this code in my preloader. But the console.log outputs the document of index.html and not the document of the webview. How can I output the contents of the webview?

preload.js

```<code>document.addEventListener('DOMContentLoaded', function(event) {
  console.log(document);
});
</code>```

答:
The webview will emit console-message events every time it console.logs something, you just have to listen to them. See docs for webview-tag:

```<code>const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
  console.log('Guest page logged a message:', e.message)
})
</code>```

Title: Electron webview preload log DOM

Body:
I am using a webview in my index.html file in my Electron program. The webview has a preloader and I simply want to be able to manipulate the DOM of the webview (not index.html).

I have this code in my preloader. But the console.log outputs the document of index.html and not the document of the webview. How can I output the contents of the webview?

preload.js

document.addEventListener('DOMContentLoaded', function(event) {
  console.log(document);
});

Body:
The webview will emit console-message events every time it console.logs something, you just have to listen to them. See docs for webview-tag:

const webview = document.querySelector('webview')
webview.addEventListener('console-message', (e) => {
  console.log('Guest page logged a message:', e.message)
})


问:
Setting an xts Index
Build an xts object with two rows.

```<code>library(xts)
junk<-xts(c(1,2),as.Date(c("2010-01-01","2010-05-01")))
junk
>            [,1]
> 2010-01-01    1
> 2010-05-01    2
</code>```

Why doesn't the following change the index for the first row?

```<code>time(junk[1])<-as.Date("2010-02-01")
junk
>            [,1]
> 2010-01-01    1
> 2010-05-01    2
</code>```

I realize that the following works, but why doesn't the above work?

```<code>time(junk)[1]<-as.Date("2010-02-01")
junk
>            [,1]
> 2010-02-01    1
> 2010-05-01    2
</code>```

Thanks,

Bill

答:
```<code>time(junk[1]) <- as.Date("2010-02-01")
</code>```

The above doesn't change the index of the first row of junk because subsetting creates a new object--with no reference to junk--and time<-.xts replaces the index of the new object.

Title: Setting an xts Index

Body:
Build an xts object with two rows.

library(xts)
junk<-xts(c(1,2),as.Date(c("2010-01-01","2010-05-01")))
junk
>            [,1]
> 2010-01-01    1
> 2010-05-01    2

Why doesn't the following change the index for the first row?

time(junk[1])<-as.Date("2010-02-01")
junk
>            [,1]
> 2010-01-01    1
> 2010-05-01    2

I realize that the following works, but why doesn't the above work?

time(junk)[1]<-as.Date("2010-02-01")
junk
>            [,1]
> 2010-02-01    1
> 2010-05-01    2

Thanks,

Bill

Body:
time(junk[1]) <- as.Date("2010-02-01")

The above doesn't change the index of the first row of junk because subsetting creates a new object--with no reference to junk--and time<-.xts replaces the index of the new object.


问:
Android TimerTask crashes when called twice
I'm calling my TimerTask (m_timer) upon a button click:

m_timer.schedule(m_progressUpdater, 0, 500);

Which kicks off my run method:

```<code>    @Override
    public void run() {

        //do some stuff
        progressBar.setProgress(currentProgress);

        if (progress >= 100) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    CompleteTask();
                }
            });
        }
    }
</code>```

I can call this once and it works perfectly.  When I call it again, my app stops responding.  I'm thinking that I need to cancel the task in my CompleteTask() method, but I've tried cancelling both the TimerTask and the Timer, and it still crashes.  Anyone know what the problem might be?

答:
When you reschedule a Timer, it throws:

```<code>java.lang.IllegalStateException: TimerTask is scheduled already
</code>```

It seems that you can only use a timer for once.

In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following:

```<code>// if you have already started a TimerTask,
// you must(?) terminate the timer before rescheduling it again.
if(m_timer != null)
    m_timer.cancel();

m_timer = new Timer();
m_progressUpdater = new myTimerTask();
m_timer.schedule(m_progressUpdater, 0, 500);
</code>```

Body:
I'm calling my TimerTask (m_timer) upon a button click:

m_timer.schedule(m_progressUpdater, 0, 500);

Which kicks off my run method:

    @Override
    public void run() {

        //do some stuff
        progressBar.setProgress(currentProgress);

        if (progress >= 100) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    CompleteTask();
                }
            });
        }
    }

I can call this once and it works perfectly.  When I call it again, my app stops responding.  I'm thinking that I need to cancel the task in my CompleteTask() method, but I've tried cancelling both the TimerTask and the Timer, and it still crashes.  Anyone know what the problem might be?

Body:
When you reschedule a Timer, it throws:

java.lang.IllegalStateException: TimerTask is scheduled already

It seems that you can only use a timer for once.

In order to reschedule a Timer, you need to simply create a new instance of it, each time. like the following:

// if you have already started a TimerTask,
// you must(?) terminate the timer before rescheduling it again.
if(m_timer != null)
    m_timer.cancel();

m_timer = new Timer();
m_progressUpdater = new myTimerTask();
m_timer.schedule(m_progressUpdater, 0, 500);


问:
SVG - animate/move dots along path
I'm looking for a way to move dots along existing path in order to get animation that looks like this:

I was thinking about working with dasharray but wasn't able to get this exact behavior.

Here is an example of something I tried, but as you can see it doesn't really work:

path.link {
  stroke-width: 3px;
  stroke-dasharray: 5 5;
  stroke: black;
}
path.link-anim {
  stroke-width: 3px;
  animation: link-anim 5s linear infinite;
}
path.red {
  stroke: red;
}
path.blue {
  stroke: blue;
}
path.green {
  stroke: green;
}
path.pink {
  stroke: pink;
}
@keyframes link-anim {
    0% {
        stroke-dashoffset: 0;
        stroke-dasharray: 5 5 100%;
    }
    100% {
        stroke-dashoffset: 100%;
        stroke-dasharray: 100% 5 5;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="450" height="450">
  <g>
    <path class="link" d="M10,10L100,10"></path>
    <path class="link-anim red" d="M10,10L100,10"></path>
  </g>
  <g>
    <path class="link" d="M50,50L200,50"></path>
    <path class="link-anim blue" d="M50,50L200,50"></path>
  </g>
  <g>
    <path class="link" d="M75,75L75,200"></path>
    <path class="link-anim green" d="M75,75L75,200"></path>
  </g>
  <g>
    <path class="link" d="M85,85L450,450"></path>
    <path class="link-anim pink" d="M85,85L450,450"></path>
  </g>
</svg></code>```

Note - the angle of the line is not something I care about. I should have written this from the start. What I need is the 3 dots to move forward (and only those 3 dots).

答:
You can simply duplicate your paths, and set the stroke dash-array of the top one to only contain the 3 dots you need.

Then you can animate the dashoffset property of these top paths.

Note that it's not really modular, the dashoffset, dash-array and steps() timing function need to be calculated according to the path length.

path, circle {
  stroke-width: 4px;
  fill: transparent;
}

.bg {
  stroke: white;
  stroke-dasharray: 4 12;
}

.move {
  stroke: red;
  animation: link-anim 3s infinite steps(21);
  stroke-dasharray: 4 12 4 12 4 300;
}

@keyframes link-anim {
  0% {
    stroke-dashoffset: 368;
  }
  100% {
    stroke-dashoffset: 32;
  }
}

body {
  background: lightblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="500" height="330">
  <defs>
  <path id="v_path" d="M30,20V288"/>
  <path id="h_path" d="M30,20H358"/>
  <path id="d_path" d="M30,20L228 228"/>
  <circle id="c_path" cx="150" cy="150" r="53.4"/>
  </defs>
    <use class="bg" xlink:href="#v_path"/>
    <use class="move" xlink:href="#v_path"/>

    <use class="bg" xlink:href="#h_path"/>
    <use class="move" xlink:href="#h_path"/>

    <use class="bg" xlink:href="#d_path"/>
    <use class="move" xlink:href="#d_path"/>

    <use class="bg" xlink:href="#c_path"/>
    <use class="move" xlink:href="#c_path"/>

</svg></code>```

Title: SVG - animate/move dots along path

Body:
I'm looking for a way to move dots along existing path in order to get animation that looks like this:

I was thinking about working with dasharray but wasn't able to get this exact behavior.

Here is an example of something I tried, but as you can see it doesn't really work:

path.link {
  stroke-width: 3px;
  stroke-dasharray: 5 5;
  stroke: black;
}
path.link-anim {
  stroke-width: 3px;
  animation: link-anim 5s linear infinite;
}
path.red {
  stroke: red;
}
path.blue {
  stroke: blue;
}
path.green {
  stroke: green;
}
path.pink {
  stroke: pink;
}
@keyframes link-anim {
    0% {
        stroke-dashoffset: 0;
        stroke-dasharray: 5 5 100%;
    }
    100% {
        stroke-dashoffset: 100%;
        stroke-dasharray: 100% 5 5;
    }
}

<svg width="450" height="450">
  <g>
    <path class="link" d="M10,10L100,10"></path>
    <path class="link-anim red" d="M10,10L100,10"></path>
  </g>
  <g>
    <path class="link" d="M50,50L200,50"></path>
    <path class="link-anim blue" d="M50,50L200,50"></path>
  </g>
  <g>
    <path class="link" d="M75,75L75,200"></path>
    <path class="link-anim green" d="M75,75L75,200"></path>
  </g>
  <g>
    <path class="link" d="M85,85L450,450"></path>
    <path class="link-anim pink" d="M85,85L450,450"></path>
  </g>
</svg>

Note - the angle of the line is not something I care about. I should have written this from the start. What I need is the 3 dots to move forward (and only those 3 dots).

Body:
You can simply duplicate your paths, and set the stroke dash-array of the top one to only contain the 3 dots you need.

Then you can animate the dashoffset property of these top paths.

Note that it's not really modular, the dashoffset, dash-array and steps() timing function need to be calculated according to the path length.

path, circle {
  stroke-width: 4px;
  fill: transparent;
}

.bg {
  stroke: white;
  stroke-dasharray: 4 12;
}

.move {
  stroke: red;
  animation: link-anim 3s infinite steps(21);
  stroke-dasharray: 4 12 4 12 4 300;
}

@keyframes link-anim {
  0% {
    stroke-dashoffset: 368;
  }
  100% {
    stroke-dashoffset: 32;
  }
}

body {
  background: lightblue;
}

<svg width="500" height="330">
  <defs>
  <path id="v_path" d="M30,20V288"/>
  <path id="h_path" d="M30,20H358"/>
  <path id="d_path" d="M30,20L228 228"/>
  <circle id="c_path" cx="150" cy="150" r="53.4"/>
  </defs>
    <use class="bg" xlink:href="#v_path"/>
    <use class="move" xlink:href="#v_path"/>

    <use class="bg" xlink:href="#h_path"/>
    <use class="move" xlink:href="#h_path"/>

    <use class="bg" xlink:href="#d_path"/>
    <use class="move" xlink:href="#d_path"/>

    <use class="bg" xlink:href="#c_path"/>
    <use class="move" xlink:href="#c_path"/>

</svg>


问:
android - Keep bluetooth connection between activities?
let's say i have 2 activities called Activity A and Activity B

i display list of devices on Activity A that users can connect to.
when users clicked one of the devices, it will connected to selected bluetooth device and exchange some data first to verify credentials (i.e. login). i have done this part.

when the data is correct i want to move to Activity B where all the main menu is there but i want to keep that connection made before in Activity A so that i don't need to disconnect and reconnect the connection again.

how to do that ? i'm new about this, please help me..

i use this library for the connection :
https://github.com/Polidea/RxAndroidBle

thanks before :)

答: In principle, I would move all Bluetooth code to a Service. Then you would not be tied to any specific activity.</p>


问:
Handling Select2 with Selenium webdriver
I've been banging my head against the wall trying to select a option from a ajax enabled select2 select list with the selenium webdriver. I've managed to get it working with the IE webdriver but not firefox. Here is my hacky solution for IE

```<code> public static void SetSelect2Option(this IWebDriver driver, By locator, string subContainerClass, string searchTerm, TimeSpan? ajaxWaitTimeSpan = null)
    {
        var select2Product = driver.FindElement(locator);
        select2Product.Click();
        var searchBox = driver.FindElement(By.CssSelector(subContainerClass + " .select2-input"));
        searchBox.SendKeys(searchTerm);
        if (ajaxWaitTimeSpan != null)
        {
            driver.Manage().Timeouts().ImplicitlyWait(ajaxWaitTimeSpan.Value);
        }
        var selectedItem = driver.FindElements(By.CssSelector(subContainerClass + " .select2-results li")).First();
        selectedItem.Click();
        selectedItem.SendKeys(Keys.Enter);
    }
</code>```

In Firefox, this solution works up until the point of the SendKeys call where it just hangs and moves on to the next step without actually firing select2's events to populate the selected item.

I've also tired using the http://code.google.com/p/selenium/wiki/AdvancedUserInteractions api with similar results.

Has anyone run into a similar issue before?

答:
```<code>protected void SelectOptionForSelect2(IWebDriver driver, string id, string text)
{
  var element = driver.FindElement(By.Id(id)).FindElement(By.XPath("following-sibling::*[1]"));
  element.Click();

  element = driver.FindElement(By.CssSelector("input[type=search]"));
  element.SendKeys(text);

  Thread.Sleep(1000);
  element.SendKeys(Keys.Enter);
}
</code>```

Body:
I've been banging my head against the wall trying to select a option from a ajax enabled select2 select list with the selenium webdriver. I've managed to get it working with the IE webdriver but not firefox. Here is my hacky solution for IE

 public static void SetSelect2Option(this IWebDriver driver, By locator, string subContainerClass, string searchTerm, TimeSpan? ajaxWaitTimeSpan = null)
    {
        var select2Product = driver.FindElement(locator);
        select2Product.Click();
        var searchBox = driver.FindElement(By.CssSelector(subContainerClass + " .select2-input"));
        searchBox.SendKeys(searchTerm);
        if (ajaxWaitTimeSpan != null)
        {
            driver.Manage().Timeouts().ImplicitlyWait(ajaxWaitTimeSpan.Value);
        }
        var selectedItem = driver.FindElements(By.CssSelector(subContainerClass + " .select2-results li")).First();
        selectedItem.Click();
        selectedItem.SendKeys(Keys.Enter);
    }

In Firefox, this solution works up until the point of the SendKeys call where it just hangs and moves on to the next step without actually firing select2's events to populate the selected item.

I've also tired using the http://code.google.com/p/selenium/wiki/AdvancedUserInteractions api with similar results.

Has anyone run into a similar issue before?


问:
Java Code Formatting
I'm using FreeMarker to generate java code, but as most of it is dynamically generated it's difficult to control the code formation.

I want to get code well formatted. Does anyone knows a lib or something like a pretty printer for java code?

答: The simplest approach would be to paste your code in the eclipse java IDE and do a ctrl+f on your selected code. which would format your code in easily readable form.</p>

Title: Java Code Formatting


问:
Android ContentObserver onChange() only returns false
I'm trying to implement a ContentObserver for CallLog.Calls content provider. I mean, If I make a call, or receive a call, etc, the observer must notify me that the CallLog.Calls content provider has changed. But the onchange method only returns false, even with the observers registered, and notified. Maybe I'm doing something wrong.

This is my code. It's an Activity.

```<code>package com.psyhclo;

public class RatedCalls extends ListActivity {

private static final String LOG_TAG = "RatedCallsObserver";
private Handler handler = new Handler();
private RatedCallsContentObserver callsObserver = null;
private SQLiteDatabase db;
private CallDataHelper dh = null;
StringBuilder sb = new StringBuilder();
OpenHelper openHelper = new OpenHelper(RatedCalls.this);

class RatedCallsContentObserver extends ContentObserver {
    public RatedCallsContentObserver(Handler h) {
        super(h);
    }

    public void onChange(boolean selfChange) {
        Log.d(LOG_TAG, "RatedCallsContentObserver.onChange( " + selfChange
                + ")");
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    registerContentObservers();
    fillList();
}

@Override
public void onStart() {

    super.onStart();
    registerContentObservers();

}

@Override
public void onStop() {

    super.onStop();
    unregisterContentObservers();

}

private void fillList() {

    Cursor cursor = getContentResolver().query(
            android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
            android.provider.CallLog.Calls.DATE + " DESC ");

    cursor.setNotificationUri(getBaseContext().getContentResolver(),
            android.provider.CallLog.Calls.CONTENT_URI);

    dh = new CallDataHelper(this);
    db = openHelper.getWritableDatabase();

    startManagingCursor(cursor);
    int numberColumnId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.NUMBER);
    int durationId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.DURATION);
    int contactNameId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
    int dateId = cursor.getColumnIndex(android.provider.CallLog.Calls.DATE);
    int numTypeId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
    // int contactIdColumnId =
    // cursor.getColumnIndex(android.provider.ContactsContract.RawContacts.CONTACT_ID);

    Date dt = new Date();
    int hours = dt.getHours();
    int minutes = dt.getMinutes();
    int seconds = dt.getSeconds();
    String currTime = hours + ":" + minutes + ":" + seconds;

    ArrayList<String> callList = new ArrayList<String>();
    if (cursor.moveToFirst()) {

        do {

            String contactNumber = cursor.getString(numberColumnId);
            String contactName = cursor.getString(contactNameId);
            String duration = cursor.getString(durationId);
            String callDate = DateFormat.getDateInstance().format(dateId);
            String numType = cursor.getString(numTypeId);

            ContentValues values = new ContentValues();

            values.put("contact_id", 1);
            values.put("contact_name", contactName);
            values.put("number_type", numType);
            values.put("contact_number", contactNumber);
            values.put("duration", duration);
            values.put("date", callDate);
            values.put("current_time", currTime);
            values.put("cont", 1);

            getBaseContext().getContentResolver().notifyChange(
                    android.provider.CallLog.Calls.CONTENT_URI, null);
            this.db.insert(CallDataHelper.TABLE_NAME, null, values);

            Toast.makeText(getBaseContext(), "Inserted!", Toast.LENGTH_LONG);
            callList.add("Contact Number: " + contactNumber
                    + "\nContact Name: " + contactName + "\nDuration: "
                    + duration + "\nDate: " + callDate);

        } while (cursor.moveToNext());
    }
    setListAdapter(new ArrayAdapter<String>(this, R.layout.listitem,
            callList));
    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            Toast.makeText(getApplicationContext(),
                    ((TextView) view).getText(), Toast.LENGTH_SHORT).show();

        }
    });

}

private void registerContentObservers() {
    ContentResolver cr = getContentResolver();
    callsObserver = new RatedCallsContentObserver(handler);
    cr.registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI,
            true, callsObserver);
}

private void unregisterContentObservers() {

    ContentResolver cr = getContentResolver();
    if (callsObserver != null) { // just paranoia
        cr.unregisterContentObserver(callsObserver);
        callsObserver = null;
    }

}
}
</code>```

答:
This is the answer for this question.

Android onChange() method only returns false

Body:
I'm trying to implement a ContentObserver for CallLog.Calls content provider. I mean, If I make a call, or receive a call, etc, the observer must notify me that the CallLog.Calls content provider has changed. But the onchange method only returns false, even with the observers registered, and notified. Maybe I'm doing something wrong.

This is my code. It's an Activity.

package com.psyhclo;

public class RatedCalls extends ListActivity {

private static final String LOG_TAG = "RatedCallsObserver";
private Handler handler = new Handler();
private RatedCallsContentObserver callsObserver = null;
private SQLiteDatabase db;
private CallDataHelper dh = null;
StringBuilder sb = new StringBuilder();
OpenHelper openHelper = new OpenHelper(RatedCalls.this);

class RatedCallsContentObserver extends ContentObserver {
    public RatedCallsContentObserver(Handler h) {
        super(h);
    }

    public void onChange(boolean selfChange) {
        Log.d(LOG_TAG, "RatedCallsContentObserver.onChange( " + selfChange
                + ")");
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    registerContentObservers();
    fillList();
}

@Override
public void onStart() {

    super.onStart();
    registerContentObservers();

}

@Override
public void onStop() {

    super.onStop();
    unregisterContentObservers();

}

private void fillList() {

    Cursor cursor = getContentResolver().query(
            android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
            android.provider.CallLog.Calls.DATE + " DESC ");

    cursor.setNotificationUri(getBaseContext().getContentResolver(),
            android.provider.CallLog.Calls.CONTENT_URI);

    dh = new CallDataHelper(this);
    db = openHelper.getWritableDatabase();

    startManagingCursor(cursor);
    int numberColumnId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.NUMBER);
    int durationId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.DURATION);
    int contactNameId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
    int dateId = cursor.getColumnIndex(android.provider.CallLog.Calls.DATE);
    int numTypeId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
    // int contactIdColumnId =
    // cursor.getColumnIndex(android.provider.ContactsContract.RawContacts.CONTACT_ID);

    Date dt = new Date();
    int hours = dt.getHours();
    int minutes = dt.getMinutes();
    int seconds = dt.getSeconds();
    String currTime = hours + ":" + minutes + ":" + seconds;

    ArrayList<String> callList = new ArrayList<String>();
    if (cursor.moveToFirst()) {

        do {

            String contactNumber = cursor.getString(numberColumnId);
            String contactName = cursor.getString(contactNameId);
            String duration = cursor.getString(durationId);
            String callDate = DateFormat.getDateInstance().format(dateId);
            String numType = cursor.getString(numTypeId);

            ContentValues values = new ContentValues();

            values.put("contact_id", 1);
            values.put("contact_name", contactName);
            values.put("number_type", numType);
            values.put("contact_number", contactNumber);
            values.put("duration", duration);
            values.put("date", callDate);
            values.put("current_time", currTime);
            values.put("cont", 1);

            getBaseContext().getContentResolver().notifyChange(
                    android.provider.CallLog.Calls.CONTENT_URI, null);
            this.db.insert(CallDataHelper.TABLE_NAME, null, values);

            Toast.makeText(getBaseContext(), "Inserted!", Toast.LENGTH_LONG);
            callList.add("Contact Number: " + contactNumber
                    + "\nContact Name: " + contactName + "\nDuration: "
                    + duration + "\nDate: " + callDate);

        } while (cursor.moveToNext());
    }
    setListAdapter(new ArrayAdapter<String>(this, R.layout.listitem,
            callList));
    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            Toast.makeText(getApplicationContext(),
                    ((TextView) view).getText(), Toast.LENGTH_SHORT).show();

        }
    });

}

private void registerContentObservers() {
    ContentResolver cr = getContentResolver();
    callsObserver = new RatedCallsContentObserver(handler);
    cr.registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI,
            true, callsObserver);
}

private void unregisterContentObservers() {

    ContentResolver cr = getContentResolver();
    if (callsObserver != null) { // just paranoia
        cr.unregisterContentObserver(callsObserver);
        callsObserver = null;
    }

}
}


问:
Sum HashMap, ArrayList values (from CSV)
I'm trying to make a java program where I first read the lines from csv file then add the second column to hashmap and the third column is the value.

There are duplicate product_id's (second column) in the file  which have different values so I have added the values to array list.
Now i have to figure out how to actually sum these values from arraylist and then write the output to csv file (new).

Input CSV (just the beginning of file):

```<code>466152;Product_69105;1
466152;Product_69133;6
466152;Product_69214;2
466152;Product_69216;2
466154;Product_01007;1
466154;Product_01083;1
466154;Product_01136;1
466154;Product_01155;1
466154;Product_01488;1
466154;Product_01491;1
466154;Product_01499;2
466154;Product_01513;1
466154;Product_01593;1
466154;Product_01646;1
466154;Product_01656;1
466154;Product_01688;1
466154;Product_01703;1
466154;Product_01770;1
466154;Product_01804;1
466154;Product_01909;1
</code>```

.....

My output now:

```<code>Product_03067 [2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 2]
Product_82332 [1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 3, 3, 2, 1, 2, 1, 1, 2, 1, 1]
Product_69594 [1, 1, 1, 1, 1, 1, 2, 2, 1, 1]
Product_82330 [1, 1, 1, 1, 3]
Product_03618 [1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 2, 2, 3, 1, 1, 1, 1,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2]
</code>```

....

Wanted output:

```<code>Product_03067, 20
Product_82332, 29
Product_69594, 12
Product_82330, 7
</code>```

.....

```<code>Public class Tilausmäärä {

Map<String, List<Integer>> tuotteet;
String Tilausrivit = "tilausrivit.csv";
String Tilausrivit_2 = "abc.csv";

public Tilausmäärä() throws FileNotFoundException, IOException {
    tuotteet = new HashMap<>();
    readTilausrivitFile();
}

  public void readTilausrivitFile() throws FileNotFoundException, IOException {

    BufferedReader in = new BufferedReader(new FileReader(Tilausrivit));
    String line;

    while ((line = in.readLine()) != null) {
        String columns[] = line.split(";");
        String key = columns[1];
        int valueInt;
        List<Integer> valueList = null;

        try {
            valueInt = Integer.parseInt(columns[2]);
        } catch (NumberFormatException e) {
            System.out.println(e);
            continue;
        }

        if (tuotteet.containsKey(key)) {
            valueList = tuotteet.get(key);
        } else {
            valueList = new ArrayList<>();
            tuotteet.put(key, valueList );
        }
        valueList.add(valueInt);

    }

    in.close();
}

public static void main(String[] args) {
    try {
        Tilausmäärä tm = new Tilausmäärä();
        for (String k : tm.tuotteet.keySet()) {
            System.out.println(k + " " + tm.tuotteet.get(k));
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

}

Could use some help so any good ideas appreciated.

Thanks!

答:
There are duplicate product_id's (second column) in the file which
  have different values so I have added the values to array list.

You could direct sum the values with the same product id.

The lists you are using don't seem required.

Your tuotteet map that is probably declared as Map<String, List<Integer>> could be Map<String, Integer> where the Integer value would be the sum.

The actual code where you populate the ArrayList :

```<code> if (tuotteet.containsKey(key)) {
     valueList = tuotteet.get(key);
 } else {
     valueList = new ArrayList<>();
     tuotteet.put(key, valueList );
 }
 valueList.add(valueInt);
</code>```

could be :

```<code>  Integer actualValue = tuotteet.get(key);
  if (actualValue == null){
      tuotteet.put(key, valueInt);
  }
  else {
      tuotteet.put(key, actualValue + valueInt);
  }
</code>```

Body:
I'm trying to make a java program where I first read the lines from csv file then add the second column to hashmap and the third column is the value.

There are duplicate product_id's (second column) in the file  which have different values so I have added the values to array list.
Now i have to figure out how to actually sum these values from arraylist and then write the output to csv file (new).

Input CSV (just the beginning of file):

466152;Product_69105;1
466152;Product_69133;6
466152;Product_69214;2
466152;Product_69216;2
466154;Product_01007;1
466154;Product_01083;1
466154;Product_01136;1
466154;Product_01155;1
466154;Product_01488;1
466154;Product_01491;1
466154;Product_01499;2
466154;Product_01513;1
466154;Product_01593;1
466154;Product_01646;1
466154;Product_01656;1
466154;Product_01688;1
466154;Product_01703;1
466154;Product_01770;1
466154;Product_01804;1
466154;Product_01909;1

.....

My output now:

Product_03067 [2, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 2]
Product_82332 [1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 3, 3, 2, 1, 2, 1, 1, 2, 1, 1]
Product_69594 [1, 1, 1, 1, 1, 1, 2, 2, 1, 1]
Product_82330 [1, 1, 1, 1, 3]
Product_03618 [1, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 2, 2, 2, 3, 1, 1, 1, 1,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2]

....

Wanted output:

Product_03067, 20
Product_82332, 29
Product_69594, 12
Product_82330, 7

.....

Public class Tilausmäärä {

Map<String, List<Integer>> tuotteet;
String Tilausrivit = "tilausrivit.csv";
String Tilausrivit_2 = "abc.csv";

public Tilausmäärä() throws FileNotFoundException, IOException {
    tuotteet = new HashMap<>();
    readTilausrivitFile();
}

  public void readTilausrivitFile() throws FileNotFoundException, IOException {

    BufferedReader in = new BufferedReader(new FileReader(Tilausrivit));
    String line;

    while ((line = in.readLine()) != null) {
        String columns[] = line.split(";");
        String key = columns[1];
        int valueInt;
        List<Integer> valueList = null;

        try {
            valueInt = Integer.parseInt(columns[2]);
        } catch (NumberFormatException e) {
            System.out.println(e);
            continue;
        }

        if (tuotteet.containsKey(key)) {
            valueList = tuotteet.get(key);
        } else {
            valueList = new ArrayList<>();
            tuotteet.put(key, valueList );
        }
        valueList.add(valueInt);

    }

    in.close();
}

public static void main(String[] args) {
    try {
        Tilausmäärä tm = new Tilausmäärä();
        for (String k : tm.tuotteet.keySet()) {
            System.out.println(k + " " + tm.tuotteet.get(k));
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Could use some help so any good ideas appreciated.

Thanks!

Body:
There are duplicate product_id's (second column) in the file which
  have different values so I have added the values to array list.

You could direct sum the values with the same product id.

The lists you are using don't seem required.

Your tuotteet map that is probably declared as Map<String, List<Integer>> could be Map<String, Integer> where the Integer value would be the sum.

The actual code where you populate the ArrayList :

 if (tuotteet.containsKey(key)) {
     valueList = tuotteet.get(key);
 } else {
     valueList = new ArrayList<>();
     tuotteet.put(key, valueList );
 }
 valueList.add(valueInt);

could be :

  Integer actualValue = tuotteet.get(key);
  if (actualValue == null){
      tuotteet.put(key, valueInt);
  }
  else {
      tuotteet.put(key, actualValue + valueInt);
  }


问:
How to adjust the size of a plot in PyQt?
I have the following code which I found here. I reduced the code a bit to make it more suitable to my question.

```<code>import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject
from PyQt5.QtWidgets import *
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width = 5, height = 3, dpi=100):

        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.updateGeometry(self)

class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)
        self.axes.set_ylabel('label2')
        self.axes.set_xlabel('label1')
        self.axes.grid(True)

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumWidth(800)
        self.setMinimumHeight(300)
        self.setMaximumWidth(800)
        self.setMaximumHeight(300)

        self.main_widget = QWidget(self)

        self.sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)

        l = QVBoxLayout(self.main_widget)
        l.addWidget(self.sc)
        self.setCentralWidget(self.main_widget)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    aw = ApplicationWindow()
    aw.setWindowTitle("PyQt5 Matplotlib Example")
    aw.show()
    app.exec_()
</code>```

The problem is that the plot is shown in principle correctly but the x-label is missing (fell out of the frame which is displayed). So, how can I adjust the size of the axes object to make PyQt also display the x-label?

I know that the figure size is adjustable through the 'figsize' argument. But so far I could not find a similar command for a diagram inside of the figure.

Also, I heard of the gridspec package of matplotlib but I think it is not suitable here since I only have one plot to display.

答:
You may want to read the thight layout guide.

So one option is to call

```<code>self.fig.tight_layout()
</code>```

You can also adjust the subplot parameters

```<code>self.fig.subplots_adjust(0.2, 0.2, 0.8, 0.8) # left,bottom,right,top
</code>```

You can also set the position of the axes

```<code>self.axes.set_position([0.2, 0.2, 0.6, 0.6]) # left,bottom,width,height
</code>```

Body:
I have the following code which I found here. I reduced the code a bit to make it more suitable to my question.

import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject
from PyQt5.QtWidgets import *
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width = 5, height = 3, dpi=100):

        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.updateGeometry(self)

class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)
        self.axes.set_ylabel('label2')
        self.axes.set_xlabel('label1')
        self.axes.grid(True)

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumWidth(800)
        self.setMinimumHeight(300)
        self.setMaximumWidth(800)
        self.setMaximumHeight(300)

        self.main_widget = QWidget(self)

        self.sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)

        l = QVBoxLayout(self.main_widget)
        l.addWidget(self.sc)
        self.setCentralWidget(self.main_widget)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    aw = ApplicationWindow()
    aw.setWindowTitle("PyQt5 Matplotlib Example")
    aw.show()
    app.exec_()

The problem is that the plot is shown in principle correctly but the x-label is missing (fell out of the frame which is displayed). So, how can I adjust the size of the axes object to make PyQt also display the x-label?

I know that the figure size is adjustable through the 'figsize' argument. But so far I could not find a similar command for a diagram inside of the figure.

Also, I heard of the gridspec package of matplotlib but I think it is not suitable here since I only have one plot to display.

Body:
You may want to read the thight layout guide.

So one option is to call

self.fig.tight_layout()

You can also adjust the subplot parameters

self.fig.subplots_adjust(0.2, 0.2, 0.8, 0.8) # left,bottom,right,top

You can also set the position of the axes

self.axes.set_position([0.2, 0.2, 0.6, 0.6]) # left,bottom,width,height


答:
From what I understand from your code (a part of it is missing), you should have the total number as a value in the tuotteet map (whose definition is missing from the code you posted) and not the list. If the element is already in the map, you should increment its value, otherwise you should set its value to the current value.

Something like this:

```<code>Map<String, Integer> tuotteet;
...
    try {
        valueInt = Integer.parseInt(columns[2]);
    } catch (NumberFormatException e) {
        System.out.println(e);
        continue;
    }

    Integer val = null;
    if (tuotteet.containsKey(key)) {
        val = tuotteet.get(key) + valueInt;
    } else {
        val = valueInt;
    }
    tuotteet.put(key, val );
</code>```

Title: Sum HashMap, ArrayList values (from CSV)

Body:
From what I understand from your code (a part of it is missing), you should have the total number as a value in the tuotteet map (whose definition is missing from the code you posted) and not the list. If the element is already in the map, you should increment its value, otherwise you should set its value to the current value.

Something like this:

Map<String, Integer> tuotteet;
...
    try {
        valueInt = Integer.parseInt(columns[2]);
    } catch (NumberFormatException e) {
        System.out.println(e);
        continue;
    }

    Integer val = null;
    if (tuotteet.containsKey(key)) {
        val = tuotteet.get(key) + valueInt;
    } else {
        val = valueInt;
    }
    tuotteet.put(key, val );