答:
There is a difference between INotifyCollectionChanged and INotifyPropertyChanged.

When a value of a propery in an object changes, it should notify others using INotifyPropertyChanged interface implementation.

On the other hand, when number of items or items themselves change in a collection, it should let others know using INotifyCollectionChanged implementation.

Now, in your case, value of a property of an object in your collection changes. That is supposed to raise PropertyChanged event, not CollectionChanged event.

Title: what is notifycollectionchangedaction reset value

Body:
I have an observable collection...SelectableDataContext<T>..And in the generic class SelectableDataContext<T> is...having two private member variables

Private T item.

Private bool isSelected.

When the IsSelected property changes...My collection's changed property is not firing .

I think it should fire...because it's Reset in INotifyCollectionChangedAction.


来源: stackexchange

问:
Find value located in the last record using VBA
I know this has probably been asked thousands of times before, but I seem to be having trouble finding an existing question that addresses this question in a wy I can understand.

My question in how can I access a value located in the last record of a table? For example, if this is my table:

```<code>personID personName personNumber
1        Sally      PR32
2        Emily      PR33
3        Joseph     PR34
</code>```

I want to access the value "PR34" (and then be able to manipulate it if possible). I know how to find the last record with Dmax, but I'm struggling to figure out how to find a value within it. I'm ultimately trying to take the value, parse the string down to just the numbers, and increment it by one (and then append the letters back on).

答:
You can do this in a query as well:

```<code>UPDATE T
SET T.personNumber = "PR" & CLng(Replace([personNumber], "PR", "")) + 1
WHERE (((T.personID)=(SELECT Max(personID) FROM T)));
</code>```

Where T is the name of your Table.

ContentLicense: CC BY-SA 3.0

Body:
I know this has probably been asked thousands of times before, but I seem to be having trouble finding an existing question that addresses this question in a wy I can understand.

My question in how can I access a value located in the last record of a table? For example, if this is my table:

personID personName personNumber
1        Sally      PR32
2        Emily      PR33
3        Joseph     PR34

I want to access the value "PR34" (and then be able to manipulate it if possible). I know how to find the last record with Dmax, but I'm struggling to figure out how to find a value within it. I'm ultimately trying to take the value, parse the string down to just the numbers, and increment it by one (and then append the letters back on).

Body:
You can do this in a query as well:

UPDATE T
SET T.personNumber = "PR" & CLng(Replace([personNumber], "PR", "")) + 1
WHERE (((T.personID)=(SELECT Max(personID) FROM T)));

Where T is the name of your Table.


问:
StringBuilder and string equality check
I am trying this sample of code and OpTest when System.Console.WriteLine(s == t); it returns false. Can somebody explain this?

```<code>public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "строка";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
    System.Console.Write(sb);
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}
</code>```

答:
This happens because you are using a generic method and you specifically restrict the generic parameter to type of class.

By default, generic types do not have the equality operator == defined.

Restricting the possible types of <T>to class makes the use of s == t possible. However, now it will use the default implementation specified by the class restriction and that is using reference equality.

Since one of your strings comes from the StringBuilder it will create a new reference although the string's contents are the same.

If you use the same string literal in both cases, it will however return true because the literal is only generated once and then that will be referenced each time it is used.

Title: StringBuilder and string equality check

Body:
I am trying this sample of code and OpTest when System.Console.WriteLine(s == t); it returns false. Can somebody explain this?

public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "строка";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
    System.Console.Write(sb);
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}


问:
In between doesn't work with multiple AND's - MYSQL
```<code>SELECT price from items Where categoryId = 11724 AND price BETWEEN 10 AND 20
</code>```

Result:

 price

17.99
18.95
20.0
17.99
18.95

Above query works fine but adding another clause doesn't show desired results

```<code>SELECT price from items
Where categoryId = 11724
    AND ( brand = 'Akaso' OR brand = 'Andoer')
    and price BETWEEN 10 AND 20
</code>```

Result: 0 rows found

```<code>SELECT price from items
Where categoryId = 11724
    AND brand = 'Akaso' OR brand = 'Andoer'
    and price BETWEEN 10 AND 20
</code>```

Result:
 price

17.99
78.95
77.0
80.99
102.95

Have tried with and (column and column) for each clause. price type is VARCHAR
 CHANGED TO Decimal(10,2)
Where am i doing wrong?

答:
Thanks to all for replying. this worked for me after changing VARCHAR type to Decimal:

```<code>SELECT price,categoryId,brand from items
Where categoryId = 11724
and (brand = 'Akaso' OR brand = 'Andoer')
and (price BETWEEN 40 AND 50)

SELECT price,categoryId,brand from items
Where (categoryId = 11724)
and (brand = 'Akaso' OR brand = 'Andoer')
and (price BETWEEN 40 AND 50)

SELECT price,categoryId,brand from items
Where categoryId = 11724
and (brand = 'Akaso' OR brand = 'Andoer')
and price BETWEEN 40 AND 50
</code>```

Below Didn't work:

```<code>SELECT price,categoryId,brand from items
Where categoryId = 11724
and brand = 'Akaso' OR brand = 'Andoer'
and (price BETWEEN 40 AND 50)
</code>```

Curious to know difference between 3rd and 4th queries.

Body:
SELECT price from items Where categoryId = 11724 AND price BETWEEN 10 AND 20

Result:

 price

17.99
18.95
20.0
17.99
18.95

Above query works fine but adding another clause doesn't show desired results

SELECT price from items
Where categoryId = 11724
    AND ( brand = 'Akaso' OR brand = 'Andoer')
    and price BETWEEN 10 AND 20

Result: 0 rows found

SELECT price from items
Where categoryId = 11724
    AND brand = 'Akaso' OR brand = 'Andoer'
    and price BETWEEN 10 AND 20

Result:
 price

17.99
78.95
77.0
80.99
102.95

Have tried with and (column and column) for each clause. price type is VARCHAR
 CHANGED TO Decimal(10,2)
Where am i doing wrong?

Body:
Thanks to all for replying. this worked for me after changing VARCHAR type to Decimal:

SELECT price,categoryId,brand from items
Where categoryId = 11724
and (brand = 'Akaso' OR brand = 'Andoer')
and (price BETWEEN 40 AND 50)

SELECT price,categoryId,brand from items
Where (categoryId = 11724)
and (brand = 'Akaso' OR brand = 'Andoer')
and (price BETWEEN 40 AND 50)

SELECT price,categoryId,brand from items
Where categoryId = 11724
and (brand = 'Akaso' OR brand = 'Andoer')
and price BETWEEN 40 AND 50

Below Didn't work:

SELECT price,categoryId,brand from items
Where categoryId = 11724
and brand = 'Akaso' OR brand = 'Andoer'
and (price BETWEEN 40 AND 50)

Curious to know difference between 3rd and 4th queries.


问:
Accessing this.state in React-Native
Hi I'm new to React so bear with me. I'm want to store geoposition as a state. Seems nifty since any change in position will trigger a render, which is exactly what I want. During development I have a button that manual triggers the event by accessing the lastPosition. But when I do. The state is "undefined". Any clue why?

```<code>export default class FetchProject extends Component {
    constructor(props) {
        super(props);
        this.state = {
            initialPosition: 'unknown',
            lastPosition: 'unknown',
        };
    }

    //code that sets lastposition
    componentDidMount() {
        ....
    }

    _onPressGET (){
        console.log("PressGET -> " + this.state); //undefined
        var northing=this.state.initialPosition.coords.latitude;
        //triggers error
    }

    render() {
       return (
           <View style={styles.container}>
               <TouchableHighlight onPress = {this._onPressGET} style = {styles.button}>
                  <Text>Fetch mailbox</Text>
               </TouchableHighlight>
           </View>
       );
    }
}
</code>```

答:
Quoted from React Docs:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.

ContentLicense: CC BY-SA 4.0

Title: Accessing this.state in React-Native

Body:
Hi I'm new to React so bear with me. I'm want to store geoposition as a state. Seems nifty since any change in position will trigger a render, which is exactly what I want. During development I have a button that manual triggers the event by accessing the lastPosition. But when I do. The state is "undefined". Any clue why?

export default class FetchProject extends Component {
    constructor(props) {
        super(props);
        this.state = {
            initialPosition: 'unknown',
            lastPosition: 'unknown',
        };
    }

    //code that sets lastposition
    componentDidMount() {
        ....
    }

    _onPressGET (){
        console.log("PressGET -> " + this.state); //undefined
        var northing=this.state.initialPosition.coords.latitude;
        //triggers error
    }

    render() {
       return (
           <View style={styles.container}>
               <TouchableHighlight onPress = {this._onPressGET} style = {styles.button}>
                  <Text>Fetch mailbox</Text>
               </TouchableHighlight>
           </View>
       );
    }
}


问:
Is there a shared folder in Windows to which non-elevated users have write access?
I know that commonappdata (All Users) can hold system-wide application settings, but under Vista/7 non-elevated users can't write to that directory.

Is there a folder which is shared among users and any non-admin user can write to it?

Here is why I need this:
My app is installed in PF directory by an Inno Setup installer with elevated rights. Then when the actual non-admin user runs the program, it copies its settings to the user's AppData directory using another non-elevated Inno Setup installer. Upon deinstalling the program (initiated by the system-wide installer with admin rights) I want to uninstall the program's files from each users' AppData directory.

I can think of two solutions:
1. Getting a list of Windows users and iterating through their AppData dirs (seems way too complicated)
2. Storing the paths to the uninstallers in the above mentioned common user data directory.

Any ideas?

Thanks!

答: Would stuff under C:\Users\Public\ qualify for what you need?</p>

ContentLicense: CC BY-SA 2.5


问:
How can I iteratively apply the function on a data in c++?
I'm just looking for a general pseudo-code type in which if I have a data type of vector<vector<double>> Xand it needs to iteratively go through a function myFunction(vector<vector<double>> &X) that returns the same data type until a certain condition on X is met or until n'th iterations.

So, suppose let X(1) = myFunction(X), then feed it again to get

X(2) = myFunction(X(1)), then feed it again to get

X(3) = myFunction(X(2)), and repreat until certain conditions say

myCondition(X(k)) = true or until n'th iteration has been done and stops at X(n)

How could I implement it?

答:
Have you tried something like the following:

```<code>std::vector<std::vector<double>> x;
unsigned int numIterators = 100u; // for example
do
{
    x = myFunction(x);
} while(!Condition(x) && --numIterators)
</code>```

And bool Condition(const std::vector<std::vector<double>>&) checks the condition that you want to stop the loop.

Body:
Have you tried something like the following:

std::vector<std::vector<double>> x;
unsigned int numIterators = 100u; // for example
do
{
    x = myFunction(x);
} while(!Condition(x) && --numIterators)

And bool Condition(const std::vector<std::vector<double>>&) checks the condition that you want to stop the loop.


问:
Scrapy - scraping comments skips the text after

I am able to retrieve the text before the
 tag but not the text after it.

This is the website that I am trying to scrape the comments from:
http://hamusoku.com/archives/9589071.html#comments

Starting from  some comments include the
 tag which I think means that the user hit enter. Is there a way to get the text before and after the
 tag as a single comment?

Here is a sample of the source code

```<code><li="comment-body"> ==$0
    "
    愛の言葉も、この瞬間は辛い。"
    <br>
    "
    胸が締め付けられそうだ。"
</code>```

This is my code:

```<code>import scrapy

class HamusoSpider(scrapy.Spider):
    name = 'hamuso'
    start_urls = ['http://hamusoku.com/archives/9589071.html#comments/']

    def parse(self, response):
        for com in response.css('li.comment-body'):
        item = {
        'comment': com.css('li::text').extract_first()
        }
        yield item
</code>```

This is the output that I am getting in the shell:

```<code>{'comment': '\n\t\n\tかなしいなぁ'}
{'comment': '\n\t\n\t海老蔵…つらいな'}
{'comment': '\n\t\n\t海老蔵には頑張って欲しいな'}
{'comment': '\n\t\n\t御冥福をお祈りします'}
{'comment': '\n\t\n\t泣かすなや。'}
{'comment': '\n\t\n\t海老蔵これからしっかりせなアカンぞ'}
{'comment': '\n\t\n\t愛の言葉も、この瞬間は辛い。'}
{'comment': '\n\t\n\tただただ涙が止まらない会見だった'}
</code>```

The last two comments both have a
 tag and in both cases the second part of the comment is omitted.

I would really really appreciate any help with this.

答:
I have ran your spider and realised that when you extraxt_first(), you only get the first item or first comment the rest, which are after the
 tags are unreacheable.

To solve this, use extract() this will return a list of all the comments in the comment-body

```<code>import scrapy

class HamusoSpider(scrapy.Spider):
    name = 'hamuso'
    start_urls = ['http://hamusoku.com/archives/9589071.html#comments/']
    def parse(self, response):
        for com in response.css('li.comment-body'):
            item = {'comment': com.css('li::text').extract()}
            yield item
</code>```

the output I get for the last comment on your output is

```<code>{'comment': ['\n\t\n\tただただ涙が止まらない会見だった', '\n本当に短い人生だったけど豊かな人生だったのがわかる']}
{'comment': ['\n\t\n\t愛の言葉も、この瞬間は辛い。', '\n胸が締め付けられそうだ。']}
</code>```

Title: Scrapy - scraping comments skips the text after <br>

Body:
I am able to retrieve the text before the
 tag but not the text after it.

This is the website that I am trying to scrape the comments from:
http://hamusoku.com/archives/9589071.html#comments

Starting from  some comments include the
 tag which I think means that the user hit enter. Is there a way to get the text before and after the
 tag as a single comment?

Here is a sample of the source code

 ==$0
    "
    愛の言葉も、この瞬間は辛い。"

    "
    胸が締め付けられそうだ。"

This is my code:

import scrapy

class HamusoSpider(scrapy.Spider):
    name = 'hamuso'
    start_urls = ['http://hamusoku.com/archives/9589071.html#comments/']

    def parse(self, response):
        for com in response.css('li.comment-body'):
        item = {
        'comment': com.css('li::text').extract_first()
        }
        yield item

This is the output that I am getting in the shell:

{'comment': '\n\t\n\tかなしいなぁ'}
{'comment': '\n\t\n\t海老蔵…つらいな'}
{'comment': '\n\t\n\t海老蔵には頑張って欲しいな'}
{'comment': '\n\t\n\t御冥福をお祈りします'}
{'comment': '\n\t\n\t泣かすなや。'}
{'comment': '\n\t\n\t海老蔵これからしっかりせなアカンぞ'}
{'comment': '\n\t\n\t愛の言葉も、この瞬間は辛い。'}
{'comment': '\n\t\n\tただただ涙が止まらない会見だった'}

The last two comments both have a
 tag and in both cases the second part of the comment is omitted.

I would really really appreciate any help with this.

Body:
I have ran your spider and realised that when you extraxt_first(), you only get the first item or first comment the rest, which are after the <br> tags are unreacheable.

To solve this, use extract() this will return a list of all the comments in the comment-body

import scrapy

class HamusoSpider(scrapy.Spider):
    name = 'hamuso'
    start_urls = ['http://hamusoku.com/archives/9589071.html#comments/']
    def parse(self, response):
        for com in response.css('li.comment-body'):
            item = {'comment': com.css('li::text').extract()}
            yield item

the output I get for the last comment on your output is

{'comment': ['\n\t\n\tただただ涙が止まらない会見だった', '\n本当に短い人生だったけど豊かな人生だったのがわかる']}
{'comment': ['\n\t\n\t愛の言葉も、この瞬間は辛い。', '\n胸が締め付けられそうだ。']}


问:
Div onclick event not called in Mozilla
I have this in my code:

```<code><div class="someClass">
    <div id="22" class="otherClass" onclick="goToEdit();">Title</div>
    <div class="parent">Other title</div>
</div>
</code>```

And:

```<code>function goToEdit()
{
    tree.selectItem($(event.target).attr('id'));
    btnMyButton_onclick();
}
</code>```

In Chrome everything works fine, but in Mozilla it doesn't react to the click event. Why?

答:
I too was facing same problem , but this code helped me.

I was testing on Mozilla Firefox and Chrome, it worked on both.

```<code><input type="button" onclick="return goBack();" class="btn btn-warning cancel" value=" Cancel" style="color:white" />

<script>
function goBack() {
    window.history.back();
}
</script>
</code>```

Title: Div onclick event not called in Mozilla

Body:
I have this in my code:

Title

Other title

And:

function goToEdit()
{
    tree.selectItem($(event.target).attr('id'));
    btnMyButton_onclick();
}

In Chrome everything works fine, but in Mozilla it doesn't react to the click event. Why?

Body:
I too was facing same problem , but this code helped me.

I was testing on Mozilla Firefox and Chrome, it worked on both.

<input type="button" onclick="return goBack();" class="btn btn-warning cancel" value=" Cancel" style="color:white" />

<script>
function goBack() {
    window.history.back();
}
</script>


问:
how to implement double click in android
I am doing a project in which i want to display  a particular message on single  touch and another message on double touch using android.How can i implement it.

My sample code is below

```<code>if(firstTap){
            thisTime = SystemClock.timeMillis();
            firstTap = false;
        }else{
            prevTime = thisTime;
            thisTime = SystemClock.uptimeMillis();

            //Check that thisTime is greater than prevTime
            //just incase system clock reset to zero
            if(thisTime > prevTime){

                //Check if times are within our max delay
                if((thisTime - prevTime) <= DOUBLE_CLICK_MAX_DELAY){

                    //We have detected a double tap!
                    Toast.makeText(AddLocation.this, "DOUBLE TAP DETECTED!!!", Toast.LENGTH_LONG).show();
                    //PUT YOUR LOGIC HERE!!!!

                }else{
                    //Otherwise Reset firstTap
                    firstTap = true;
                }
            }else{
                firstTap = true;
            }
        }
        return false;
</code>```

答:
I have Implemented the code on which the Background color and text color changes on clicking the screen twice(Double Tap) here is the code...</p>

```<code>        int i = 0;
        reader.setOnClickListener(new View.OnClickListener() {
            int i = 0;
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                i++;
                Handler handler = new Handler();
                Runnable r = new Runnable() {

                    @Override
                    public void run() {
                        i = 0;
                    }
                };

                if (i == 1) {
                    //Single click
                    handler.postDelayed(r, 250);
                } else if (i == 2) {

                    if(color==1) {

                        reader.setTextColor(0xFF000000);
                        reader.setBackgroundColor(0xFFFFFFFF);
                        color = 2;
                    }else if(color==2)
                    {
                        reader.setTextColor(0xFFFFFFFF);
                        reader.setBackgroundColor(0xFF000000);
                        color=1;
                    }
                    i = 0;

                }

            }
        });
</code>```

Body:
I am doing a project in which i want to display  a particular message on single  touch and another message on double touch using android.How can i implement it.

My sample code is below

if(firstTap){
            thisTime = SystemClock.timeMillis();
            firstTap = false;
        }else{
            prevTime = thisTime;
            thisTime = SystemClock.uptimeMillis();

            //Check that thisTime is greater than prevTime
            //just incase system clock reset to zero
            if(thisTime > prevTime){

                //Check if times are within our max delay
                if((thisTime - prevTime) <= DOUBLE_CLICK_MAX_DELAY){

                    //We have detected a double tap!
                    Toast.makeText(AddLocation.this, "DOUBLE TAP DETECTED!!!", Toast.LENGTH_LONG).show();
                    //PUT YOUR LOGIC HERE!!!!

                }else{
                    //Otherwise Reset firstTap
                    firstTap = true;
                }
            }else{
                firstTap = true;
            }
        }
        return false;

Body:
I have Implemented the code on which the Background color and text color changes on clicking the screen twice(Double Tap) here is the code...

        int i = 0;
        reader.setOnClickListener(new View.OnClickListener() {
            int i = 0;
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                i++;
                Handler handler = new Handler();
                Runnable r = new Runnable() {

                    @Override
                    public void run() {
                        i = 0;
                    }
                };

                if (i == 1) {
                    //Single click
                    handler.postDelayed(r, 250);
                } else if (i == 2) {

                    if(color==1) {

                        reader.setTextColor(0xFF000000);
                        reader.setBackgroundColor(0xFFFFFFFF);
                        color = 2;
                    }else if(color==2)
                    {
                        reader.setTextColor(0xFFFFFFFF);
                        reader.setBackgroundColor(0xFF000000);
                        color=1;
                    }
                    i = 0;

                }

            }
        });


问:
Expected JsonObject but was JsonPrimitive
I am using retrofit to parse JSON. I'm getting an exception while parsing a JSON response. My response is dynamic means that when I'm getting a successful response the response key is successful, but when I'm getting a fail response it turns to an error. How can I parse that response?

When I'm getting a fail response it's giving me a proper result, but when I'm getting a successful response it's going to end in failure and gives me an exception that Expected JsonObject but was JsonPrimitive.

答:
Jsonobject and jsonprimitive is different type each other .

JsonObject { "name":"John", "age":30, "car":null }

JsonPrimitive (string, number, boolean)

Your response model is wrong . try this .

http://www.jsonschema2pojo.org/


问:
Hide a React component in existing web project
I'm currently trying to integrate a React component into a legacy web project (a huge html index file and some js scripts using mostly jquery).

I am trying to add the rendered react component into a separate tab. Now the problem is that I cannot control the visibility of the top level React component.

Say I have the following src code in html:

```<code>...
<div id="wrapper">
    <div id="react-component"></div>
</div>
...
</code>```

I render the inner component using React. Now is there any way to control the visibility of either "#wrapper" or "#react-component" ? jquery does not help.

I am relatively new to React and it seems that integrating it into old project can be a huge pain.

答:
Create a js file and export a default function to help you rendering react components.

Like this

```<code>import React from 'react';
import ReactDOM from 'react-dom';
export default function(component, container , props = {}, callback){

    React.createElement(component , props);
    ReactDOM.render(component, container, callback);

}
</code>```

Your component will look like this

```<code>import React,{PropTypes} from 'react';

class MySampleComponent extends React.Component{

   static propTypes ={
      hide : PropTypes.bool
   }
   static defaultProps= {
      hide : false
   }

   render(){
      return(
         <div style={display : this.props.hide : 'none' : 'block'}> </div>

      );

   }

}
</code>```

Import the above function to render your component in js file which you will add in index.html

```<code>import render from './pathto/RenderHelper'
import MyComponent from './MyComponent'

class IndexPage {

  constructor(){
     this.renderUI();
  }

  renderUI(){
    var container = document.getElementById('react-component');
    render(MyComponent, container, {hide : false});
  }
}
</code>```

Note you need to add your page.index.js file to webpack.config.js entry so that webpack can compile it, like this.

```<code>entry: { page.index : 'location/to/page.index.js' }
</code>```

Hope this helps.

Body:
I'm currently trying to integrate a React component into a legacy web project (a huge html index file and some js scripts using mostly jquery).

I am trying to add the rendered react component into a separate tab. Now the problem is that I cannot control the visibility of the top level React component.

Say I have the following src code in html:

...

...

I render the inner component using React. Now is there any way to control the visibility of either "#wrapper" or "#react-component" ? jquery does not help.

I am relatively new to React and it seems that integrating it into old project can be a huge pain.

Body:
Create a js file and export a default function to help you rendering react components.

Like this

import React from 'react';
import ReactDOM from 'react-dom';
export default function(component, container , props = {}, callback){

    React.createElement(component , props);
    ReactDOM.render(component, container, callback);

}

Your component will look like this

import React,{PropTypes} from 'react';

class MySampleComponent extends React.Component{

   static propTypes ={
      hide : PropTypes.bool
   }
   static defaultProps= {
      hide : false
   }

   render(){
      return(
         <div style={display : this.props.hide : 'none' : 'block'}> </div>

      );

   }

}

Import the above function to render your component in js file which you will add in index.html

import render from './pathto/RenderHelper'
import MyComponent from './MyComponent'

class IndexPage {

  constructor(){
     this.renderUI();
  }

  renderUI(){
    var container = document.getElementById('react-component');
    render(MyComponent, container, {hide : false});
  }
}

Note you need to add your page.index.js file to webpack.config.js entry so that webpack can compile it, like this.

entry: { page.index : 'location/to/page.index.js' }

Hope this helps.


问:
Is there a way to change the __add__ method in python to be able to add a string and an int using only the + operator?
Is there a way to rewrite the __add__ method in the str class so that this operation is possible without an exception occurring:

```<code>"apple" + 123
</code>```

This error keeps popping up:

```<code>TypeError: Can't convert 'int' object to str implicitly
</code>```

答:
You can use a function in your program to check before adding.
For example:
    def check(object1):
         if type(object1)==int:
             return str(object1)
         else:
             return object1
print 'string'+check(123)

gives output:>>> string123>>>

You cannot overide the add() method but you can use your own user defined class to change the way add() works in your defined class's objects. If you need the code ask me.
EDIT

```<code>def check(object1):
     if type(object1)==int:
         return str(object1)
     else:
         return object1
print 'string'+check(123)
</code>```

Body:
Is there a way to rewrite the __add__ method in the str class so that this operation is possible without an exception occurring:

"apple" + 123

This error keeps popping up:

TypeError: Can't convert 'int' object to str implicitly

Body:
You can use a function in your program to check before adding.
For example:
    def check(object1):
         if type(object1)==int:
             return str(object1)
         else:
             return object1
print 'string'+check(123)

gives output:>>> string123>>>

You cannot overide the add() method but you can use your own user defined class to change the way add() works in your defined class's objects. If you need the code ask me.
EDIT

def check(object1):
     if type(object1)==int:
         return str(object1)
     else:
         return object1
print 'string'+check(123)


问:
Fetch the questions from json in Angular

(function() {
'use strict';
angular
    .module('app.interview', [])
    .controller('InterviewController', InterviewController)
    .factory('Interview', Interview);
InterviewController.$inject = ['$scope', 'Interview'];
Interview.$inject = ['$http'];

function Interview($http) {
    var service = {};
    service.fetchQuestion = fetchQuestion;
    return service;

    function fetchQuestion() {
        return $http.get('/app/interview/questions.json');
    }
}
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="ad-container">
    <h1 class="text-center headtext">Interview Questions</h1>
    <form name="interviewForm">
        <p></p>
    </form>
</div></code>```

Here is my json

```<code>{
  "Q1": "What is a pointer on pointer?",
  "Q2": "Write about yourself?",
  "Q3": "write a program to find multiplication of two number?",
  "Q4": "write a program to find addition of two number?",
  "Q5": "write a program to find subtraction of two number?",
  "Q6": "write a program to find percentage?",
  "Q7": "write a program to find addition of two number?",
  "Q8": "write a program to find addition of two number?"
}
</code>```

How to fetch a sigle question from the json and show in html?

答:
```<code><div class="ad-container">
<h1 class="text-center headtext">Interview Questions</h1>
<form name="interviewForm" ng-if="!showSubmit">
    <p ng-bind="question['Q'+ind]"></p>
    <textarea cols="85" rows="10" placeholder="Write your answer here" ng-model="answer['Q'+ind]"></textarea>
</form>
<md-button style="float:right" class="md-raised md-primary flr8" ng-click="nextQuestion()" ng-if="!showSubmit">NEXT</md-button>
<!--<md-button style="float:right" class="md-raised md-primary flr8"  ng-if="showSubmit">SUBMIT</md-button>-->

<md-card aria-label="Obmondo" class="login-card">
    <form name="info" ng-if="showSubmit">
        <md-card-header class="color2">
            <md-card-header-text>
                <span class="md-title">AKASH</span>
            </md-card-header-text>
        </md-card-header>

        <md-card-content>
            <md-input-container class="md-block">
                <input name="name" ng-model="user.name" type="text" placeholder="Name" ng-required="true">
                <div ng-messages="info.name.$error" role="alert">
                    <div ng-message="required">This is required</div>
                </div>
                <div ng-messages="login.email.$error">
                    <div ng-message="required">This is required.</div>
                </div>
            </md-input-container>
            <md-input-container class="md-block">
                <input name="email" ng-model="user.email" type="email" placeholder="Email (required)" ng-required="true"
                       minlength="4" maxlength="100" ng-pattern="/^.+@.+\..+$/" />
                <div ng-messages="info.email.$error" role="alert">
                    <div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
                        Your email must be between 4 and 100 characters long and look like an e-mail address.
                    </div>
                </div>
                <div ng-messages="info.email.$error">
                    <div ng-message="required">This is required.</div>
                </div>
            </md-input-container>
            <md-input-container class="md-block">
                <input name="phome" ng-model="user.phone" type="tel" placeholder="Phone" ng-required="true">
                <div ng-messages="info.name.$error" role="alert">
                    <div ng-message="required">This is required</div>
                </div>
                <div ng-messages="info.phone.$error">
                    <div ng-message="required">This is required.</div>
                </div>
            </md-input-container>
            <md-button class="md-raised login-btn text-center" type="submit">Submit</md-button>
        </md-card-content>
    </form>
</md-card>
</code>```

```<code>(function () {
'use strict';
angular
    .module('app.interview', [])
    .controller('InterviewController', InterviewController)
    .factory('Interview', Interview);
InterviewController.$inject = ['$scope', 'Interview'];

function InterviewController($scope, Interview) {
    var originatorEv;

    $scope.ind = 1;
    $scope.question = {};

    $scope.nextQuestion = function () {
        if (Object.keys($scope.question).length-1 > $scope.ind){
            $scope.ind++;
        }else {
            $scope.showSubmit = true;
        }
    };

    Interview.fetchQuestion()
        .then(function (response) {
            console.log(response);
            $scope.question = response.data;
        })
        .catch(function () {
            $scope.question = {};
        });
}

Interview.$inject = ['$http'];

function Interview($http) {
    var service = {};
    service.fetchQuestion = fetchQuestion;
    return service;
    function fetchQuestion() {
        return $http.get('/app/interview/questions.json');
    }
}
</code>```

})();

Body:
(function() {
'use strict';
angular
    .module('app.interview', [])
    .controller('InterviewController', InterviewController)
    .factory('Interview', Interview);
InterviewController.$inject = ['$scope', 'Interview'];
Interview.$inject = ['$http'];

function Interview($http) {
    var service = {};
    service.fetchQuestion = fetchQuestion;
    return service;

    function fetchQuestion() {
        return $http.get('/app/interview/questions.json');
    }
}
})();

Interview Questions

    <form name="interviewForm">

    </form>

Here is my json

{
  "Q1": "What is a pointer on pointer?",
  "Q2": "Write about yourself?",
  "Q3": "write a program to find multiplication of two number?",
  "Q4": "write a program to find addition of two number?",
  "Q5": "write a program to find subtraction of two number?",
  "Q6": "write a program to find percentage?",
  "Q7": "write a program to find addition of two number?",
  "Q8": "write a program to find addition of two number?"
}

How to fetch a sigle question from the json and show in html?

Body:
<div class="ad-container">
<h1 class="text-center headtext">Interview Questions</h1>
<form name="interviewForm" ng-if="!showSubmit">
    <p ng-bind="question['Q'+ind]"></p>
    <textarea cols="85" rows="10" placeholder="Write your answer here" ng-model="answer['Q'+ind]"></textarea>
</form>
<md-button style="float:right" class="md-raised md-primary flr8" ng-click="nextQuestion()" ng-if="!showSubmit">NEXT</md-button>
<!--<md-button style="float:right" class="md-raised md-primary flr8"  ng-if="showSubmit">SUBMIT</md-button>-->

<md-card aria-label="Obmondo" class="login-card">
    <form name="info" ng-if="showSubmit">
        <md-card-header class="color2">
            <md-card-header-text>
                <span class="md-title">AKASH</span>
            </md-card-header-text>
        </md-card-header>

        <md-card-content>
            <md-input-container class="md-block">
                <input name="name" ng-model="user.name" type="text" placeholder="Name" ng-required="true">
                <div ng-messages="info.name.$error" role="alert">
                    <div ng-message="required">This is required</div>
                </div>
                <div ng-messages="login.email.$error">
                    <div ng-message="required">This is required.</div>
                </div>
            </md-input-container>
            <md-input-container class="md-block">
                <input name="email" ng-model="user.email" type="email" placeholder="Email (required)" ng-required="true"
                       minlength="4" maxlength="100" ng-pattern="/^.+@.+\..+$/" />
                <div ng-messages="info.email.$error" role="alert">
                    <div ng-message-exp="['required', 'minlength', 'maxlength', 'pattern']">
                        Your email must be between 4 and 100 characters long and look like an e-mail address.
                    </div>
                </div>
                <div ng-messages="info.email.$error">
                    <div ng-message="required">This is required.</div>
                </div>
            </md-input-container>
            <md-input-container class="md-block">
                <input name="phome" ng-model="user.phone" type="tel" placeholder="Phone" ng-required="true">
                <div ng-messages="info.name.$error" role="alert">
                    <div ng-message="required">This is required</div>
                </div>
                <div ng-messages="info.phone.$error">
                    <div ng-message="required">This is required.</div>
                </div>
            </md-input-container>
            <md-button class="md-raised login-btn text-center" type="submit">Submit</md-button>
        </md-card-content>
    </form>
</md-card>

(function () {
'use strict';
angular
    .module('app.interview', [])
    .controller('InterviewController', InterviewController)
    .factory('Interview', Interview);
InterviewController.$inject = ['$scope', 'Interview'];

function InterviewController($scope, Interview) {
    var originatorEv;

    $scope.ind = 1;
    $scope.question = {};

    $scope.nextQuestion = function () {
        if (Object.keys($scope.question).length-1 > $scope.ind){
            $scope.ind++;
        }else {
            $scope.showSubmit = true;
        }
    };

    Interview.fetchQuestion()
        .then(function (response) {
            console.log(response);
            $scope.question = response.data;
        })
        .catch(function () {
            $scope.question = {};
        });
}

Interview.$inject = ['$http'];

function Interview($http) {
    var service = {};
    service.fetchQuestion = fetchQuestion;
    return service;
    function fetchQuestion() {
        return $http.get('/app/interview/questions.json');
    }
}

})();


问:
What is fairness in multi-threading programming?
What is thread fairness or fairness in concurrent/multi-threaded programming?

I have googled, there is loads of info on multi-threading but not exactly on fairness.

Can some one explain. An example is most welcome.

答:
A measure, probably, of how equally every thread gets a chance at execution.

A round-robin approach would be the most fair multi-threading approach. This is because here every thread is guaranteed to get a chance at execution.

A priority-based one, would be less fair, but preferred in some scenarios. Lower priority threads may get pushed to the bottom of the pile.


问:
Why does pausing my project during debugging stop other programs?
I am working on a .Net project and it just works fine, however I noticed that when I pause the program while debugging, some other files that are completely not related to the project cannot open. Examples of these files are the ones that open in MS Access, MS Internet Explorer...

Once I click on the run button, the files open immediately.

Is there any suggestion on why this file freezing occurs?

The following image illustrates this issue (The files in the red square do not open while pausing the debugger, they open once the program is run).

答:
The culprit here is almost certainly that something in the process of opening the files is using DDE. The problem with DDE is that it works by using broadcast messages. These messages have to be processed by every top-level window on the desktop. And if one of those top-level window's message loop isn't currently processing messages, but is instead paused in the debugger, then DDE kindof breaks down.

DDE was fine for its day - before pre-emptive multi-tasking was added to windows. Which was a long time ago, but unfortunately some programs do still use it.


问:
Draw trajectory from data stream in real-time using wxpython
I want to use wxpython to show the trajectory of a random walk in real-time. However, the panel is updated only once at the end showing the entire random walk instead of updating step by step and showing the time course.

My first idea was to use wx.ClientDC().DrawPoint() but the result was as described above where I did not see single points being drawn but only the final result was shown.

So instead I thought about using wx.MemoryDC to draw the trajectory to a bitmap stored in memory and then use wx.ClientDC.DrawBitmap() to copy the buffered image to the screen at set time intervals in case flipping the image was the bottleneck. The result is still the same so I am hoping for you help.

The purpose of this exercise is to replace the random walk with positional data coming from an eye tracker with a frame rate of 1000 Hz and I would like to be able to visualize the trajectory in as close to real-time as possible (the monitor's frame rate is 120Hz).

This is my code (most of it comes from here):

```<code>import wx
import random
import time
from time import asctime

#-------------------------------------------------------------------

def jmtime():
    return '[' + asctime()[11:19] + '] '

#-------------------------------------------------------------------
class MyDrawingArea(wx.Window):

    def __init__(self, parent, id):
        sty = wx.NO_BORDER
        wx.Window.__init__(self, parent, id, style=sty)
        self.parent = parent
        self.SetBackgroundColour(wx.WHITE)
        self.SetCursor(wx.CROSS_CURSOR)

        # Some initalisation, just to reminds the user that a variable
        # called self.BufferBmp exists. See self.OnSize().
        self.BufferBmp = None

        wx.EVT_SIZE(self, self.OnSize)
        wx.EVT_PAINT(self, self.OnPaint)
        wx.EVT_LEFT_DOWN(self,self.OnClick)

    def OnSize(self, event):
        print jmtime() + 'OnSize in MyDrawingArea'
        # Get the size of the drawing area in pixels.
        self.wi, self.he = self.GetSizeTuple()
        # Create BufferBmp and set the same size as the drawing area.
        self.BufferBmp = wx.EmptyBitmap(self.wi, self.he)
        memdc = wx.MemoryDC()
        memdc.SelectObject(self.BufferBmp)
        # Drawing job
        ret = self.DoSomeDrawing(memdc)
        if not ret:  #error
            self.BufferBmp = None
            wx.MessageBox('Error in drawing', 'CommentedDrawing', wx.OK | wx.ICON_EXCLAMATION)

    def OnPaint(self, event):
        print jmtime() + 'OnPaint in MyDrawingArea'
        dc = wx.PaintDC(self)
        dc.BeginDrawing()
        if self.BufferBmp != None:
            print jmtime() + '...drawing'
            dc.DrawBitmap(self.BufferBmp, 0, 0, True)
        else:
            print jmtime() + '...nothing to draw'
        dc.EndDrawing()

    def OnClick(self,event):
        pos = event.GetPosition()
        dc = wx.ClientDC(self)
        dc.SetPen(wx.Pen(wx.BLACK,1,wx.SOLID))

        dcwi, dche = dc.GetSizeTuple()
        x = pos.x
        y = pos.y
        time_start = time.time()

        memdc = wx.MemoryDC()
        memdc.SelectObject(self.BufferBmp)
        memdc.SetPen(wx.Pen(wx.BLACK,1,wx.SOLID))
        count = 1
        runtime = 5
        while (time.time() - time_start) < runtime:
            x,y = random_walk(x,y,dcwi,dche)
            memdc.DrawPoint(x,y)
            if (time.time() - time_start) > count * runtime * 0.1:
                print jmtime() + 'Random walk in MyDrawingArea'
                count += 1
                dc.BeginDrawing()
                dc.DrawBitmap(self.BufferBmp, 0, 0, True)
                dc.EndDrawing()
        dc.BeginDrawing()
        dc.DrawBitmap(self.BufferBmp, 0, 0, True)
        dc.EndDrawing()

    # End of def OnClick

    def DoSomeDrawing(self, dc):
        try:
            print jmtime() + 'DoSomeDrawing in MyDrawingArea'

            dc.BeginDrawing()

            #~ raise OverflowError #for test

            # Clear everything
            dc.SetBrush(wx.Brush(wx.WHITE, wx.SOLID))
            dc.Clear()

            dc.EndDrawing()
            return True

        except:
            return False

#-------------------------------------------------------------------

class MyPanel(wx.Panel):

    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize)

        self.drawingarea = MyDrawingArea(self, -1)

        self.SetAutoLayout(True)

        gap = 30 #in pixels
        lc = wx.LayoutConstraints()
        lc.top.SameAs(self, wx.Top, gap)
        lc.left.SameAs(self, wx.Left, gap)
        lc.right.SameAs(self, wx.Width, gap)
        lc.bottom.SameAs(self, wx.Bottom, gap)
        self.drawingarea.SetConstraints(lc)

#-------------------------------------------------------------------

# Usual frame. Can be resized, maximized and minimized.
# The frame contains one panel.
class MyFrame(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'CommentedDrawing', wx.Point(0, 0), wx.Size(500, 400))
        self.panel = MyPanel(self, -1)

        wx.EVT_CLOSE(self, self.OnCloseWindow)

    def OnCloseWindow(self, event):
        print jmtime() + 'OnCloseWindow in MyFrame'
        self.Destroy()

#-------------------------------------------------------------------

class MyApp(wx.App):

    def OnInit(self):
        frame = MyFrame(None, -1)
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

#-------------------------------------------------------------------

def random_walk(x,y,sizex = 250, sizey = 200):

    rn = random.randrange(0,2)
    x_new = x + (1-rn) - rn
    while x_new < 0 or x_new > sizex:
        rn = random.randrange(0,2)
        x_new = x + (1-rn) - rn

    rn = random.randrange(0,2)
    y_new = y + (1-rn) - rn
    while y_new < 0 or y_new > sizex:
        rn = random.randrange(0,2)
        y_new = y + (1-rn) - rn

    return x_new, y_new

# end of def random_walk

#-------------------------------------------------------------------

def main():
    print 'main is running...'
    app = MyApp(0)
    app.MainLoop()

#-------------------------------------------------------------------

if __name__ == "__main__" :
    main()

#eof-------------------------------------------------------------------
</code>```

答:
This is the solution I came up with. Instead of using dc.DrawBitmap() to copy the buffered image to the screen I used Update() and Refresh() to trigger a paint event. However, what I still don't understand is why I cannot use DrawBitmap() to accomplish the same.

The only difference is that OnPaint() uses PaintDC() and in OnClick() I use ClientDC().

Anyways, this is my current code for OnClick():

```<code>def OnClick(self,event):
    pos = event.GetPosition()
    x = pos.x
    y = pos.y
    time_start = time.time()

    memdc = wx.MemoryDC()
    memdc.SelectObject(self.BufferBmp)
    dcwi, dche = memdc.GetSizeTuple()
    memdc.SetPen(wx.Pen(wx.BLACK,1,wx.SOLID))
    runtime = 10
    while (time.time() - time_start) < runtime:
        x,y = random_walk(x,y,dcwi,dche)
        memdc.SelectObject(self.BufferBmp)
        memdc.DrawPoint(x,y)
        memdc.SelectObject(wx.NullBitmap)
        self.Update()
        self.Refresh()
    print jmtime() + 'Random walk in MyDrawingArea done'
</code>```

Body:
I want to use wxpython to show the trajectory of a random walk in real-time. However, the panel is updated only once at the end showing the entire random walk instead of updating step by step and showing the time course.

My first idea was to use wx.ClientDC().DrawPoint() but the result was as described above where I did not see single points being drawn but only the final result was shown.

So instead I thought about using wx.MemoryDC to draw the trajectory to a bitmap stored in memory and then use wx.ClientDC.DrawBitmap() to copy the buffered image to the screen at set time intervals in case flipping the image was the bottleneck. The result is still the same so I am hoping for you help.

The purpose of this exercise is to replace the random walk with positional data coming from an eye tracker with a frame rate of 1000 Hz and I would like to be able to visualize the trajectory in as close to real-time as possible (the monitor's frame rate is 120Hz).

This is my code (most of it comes from here):

import wx
import random
import time
from time import asctime

#-------------------------------------------------------------------

def jmtime():
    return '[' + asctime()[11:19] + '] '

#-------------------------------------------------------------------
class MyDrawingArea(wx.Window):

    def __init__(self, parent, id):
        sty = wx.NO_BORDER
        wx.Window.__init__(self, parent, id, style=sty)
        self.parent = parent
        self.SetBackgroundColour(wx.WHITE)
        self.SetCursor(wx.CROSS_CURSOR)

        # Some initalisation, just to reminds the user that a variable
        # called self.BufferBmp exists. See self.OnSize().
        self.BufferBmp = None

        wx.EVT_SIZE(self, self.OnSize)
        wx.EVT_PAINT(self, self.OnPaint)
        wx.EVT_LEFT_DOWN(self,self.OnClick)

    def OnSize(self, event):
        print jmtime() + 'OnSize in MyDrawingArea'
        # Get the size of the drawing area in pixels.
        self.wi, self.he = self.GetSizeTuple()
        # Create BufferBmp and set the same size as the drawing area.
        self.BufferBmp = wx.EmptyBitmap(self.wi, self.he)
        memdc = wx.MemoryDC()
        memdc.SelectObject(self.BufferBmp)
        # Drawing job
        ret = self.DoSomeDrawing(memdc)
        if not ret:  #error
            self.BufferBmp = None
            wx.MessageBox('Error in drawing', 'CommentedDrawing', wx.OK | wx.ICON_EXCLAMATION)

    def OnPaint(self, event):
        print jmtime() + 'OnPaint in MyDrawingArea'
        dc = wx.PaintDC(self)
        dc.BeginDrawing()
        if self.BufferBmp != None:
            print jmtime() + '...drawing'
            dc.DrawBitmap(self.BufferBmp, 0, 0, True)
        else:
            print jmtime() + '...nothing to draw'
        dc.EndDrawing()

    def OnClick(self,event):
        pos = event.GetPosition()
        dc = wx.ClientDC(self)
        dc.SetPen(wx.Pen(wx.BLACK,1,wx.SOLID))

        dcwi, dche = dc.GetSizeTuple()
        x = pos.x
        y = pos.y
        time_start = time.time()

        memdc = wx.MemoryDC()
        memdc.SelectObject(self.BufferBmp)
        memdc.SetPen(wx.Pen(wx.BLACK,1,wx.SOLID))
        count = 1
        runtime = 5
        while (time.time() - time_start) < runtime:
            x,y = random_walk(x,y,dcwi,dche)
            memdc.DrawPoint(x,y)
            if (time.time() - time_start) > count * runtime * 0.1:
                print jmtime() + 'Random walk in MyDrawingArea'
                count += 1
                dc.BeginDrawing()
                dc.DrawBitmap(self.BufferBmp, 0, 0, True)
                dc.EndDrawing()
        dc.BeginDrawing()
        dc.DrawBitmap(self.BufferBmp, 0, 0, True)
        dc.EndDrawing()

    # End of def OnClick

    def DoSomeDrawing(self, dc):
        try:
            print jmtime() + 'DoSomeDrawing in MyDrawingArea'

            dc.BeginDrawing()

            #~ raise OverflowError #for test

            # Clear everything
            dc.SetBrush(wx.Brush(wx.WHITE, wx.SOLID))
            dc.Clear()

            dc.EndDrawing()
            return True

        except:
            return False

#-------------------------------------------------------------------

class MyPanel(wx.Panel):

    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id, wx.DefaultPosition, wx.DefaultSize)

        self.drawingarea = MyDrawingArea(self, -1)

        self.SetAutoLayout(True)

        gap = 30 #in pixels
        lc = wx.LayoutConstraints()
        lc.top.SameAs(self, wx.Top, gap)
        lc.left.SameAs(self, wx.Left, gap)
        lc.right.SameAs(self, wx.Width, gap)
        lc.bottom.SameAs(self, wx.Bottom, gap)
        self.drawingarea.SetConstraints(lc)

#-------------------------------------------------------------------

# Usual frame. Can be resized, maximized and minimized.
# The frame contains one panel.
class MyFrame(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'CommentedDrawing', wx.Point(0, 0), wx.Size(500, 400))
        self.panel = MyPanel(self, -1)

        wx.EVT_CLOSE(self, self.OnCloseWindow)

    def OnCloseWindow(self, event):
        print jmtime() + 'OnCloseWindow in MyFrame'
        self.Destroy()

#-------------------------------------------------------------------

class MyApp(wx.App):

    def OnInit(self):
        frame = MyFrame(None, -1)
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

#-------------------------------------------------------------------

def random_walk(x,y,sizex = 250, sizey = 200):

    rn = random.randrange(0,2)
    x_new = x + (1-rn) - rn
    while x_new < 0 or x_new > sizex:
        rn = random.randrange(0,2)
        x_new = x + (1-rn) - rn

    rn = random.randrange(0,2)
    y_new = y + (1-rn) - rn
    while y_new < 0 or y_new > sizex:
        rn = random.randrange(0,2)
        y_new = y + (1-rn) - rn

    return x_new, y_new

# end of def random_walk

#-------------------------------------------------------------------

def main():
    print 'main is running...'
    app = MyApp(0)
    app.MainLoop()

#-------------------------------------------------------------------

if __name__ == "__main__" :
    main()

#eof-------------------------------------------------------------------

Body:
This is the solution I came up with. Instead of using dc.DrawBitmap() to copy the buffered image to the screen I used Update() and Refresh() to trigger a paint event. However, what I still don't understand is why I cannot use DrawBitmap() to accomplish the same.

The only difference is that OnPaint() uses PaintDC() and in OnClick() I use ClientDC().

Anyways, this is my current code for OnClick():

def OnClick(self,event):
    pos = event.GetPosition()
    x = pos.x
    y = pos.y
    time_start = time.time()

    memdc = wx.MemoryDC()
    memdc.SelectObject(self.BufferBmp)
    dcwi, dche = memdc.GetSizeTuple()
    memdc.SetPen(wx.Pen(wx.BLACK,1,wx.SOLID))
    runtime = 10
    while (time.time() - time_start) < runtime:
        x,y = random_walk(x,y,dcwi,dche)
        memdc.SelectObject(self.BufferBmp)
        memdc.DrawPoint(x,y)
        memdc.SelectObject(wx.NullBitmap)
        self.Update()
        self.Refresh()
    print jmtime() + 'Random walk in MyDrawingArea done'


问:
CORS issue between Angular2 and WebAPI application on two different servers
I've come across an issue with CORS between an Angular2 application and a WebAPI application when my Angular2 app is running on my own machine but the WebAPI app is running on IIS on a web server. Interestingly, everything works fine if I run both the applications on my own machine

I get the following error in Chrome:-

XMLHttpRequest cannot load http://fowebtst01l:81/FilePusher.Service/api/version. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

I've installed the CORS nuget package in my WebAPI application and enabled it in my WebApiConfig class using

```<code>            var attrib = new EnableCorsAttribute("*", "*", "*") {SupportsCredentials = true};
        config.EnableCors(attrib);
</code>```

I've also added this code into my Global.asax.cs file:-

```<code>        protected void Application_BeginRequest()
    {
        if (Request.HttpMethod == "OPTIONS")
        {
            string header = Request.Headers.GetValues("Origin")[0];

            Response.StatusCode = (int)HttpStatusCode.OK;
            Response.AppendHeader("Access-Control-Allow-Origin", header);
            Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            Response.AppendHeader("Access-Control-Allow-Credentials", "true");
            Response.End();
        }
    }
</code>```

But to no avail. Can anyone help with this?

Note that if I remove the code to enable CORS and instead add in the following settings into my Web.config then I get this error when running everything locally:-

```<code><httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true"/>
    <add name="Access-Control-Allow-Headers" value="X-Requested-With, origin, content-type, accept" />
  </customHeaders>
</httpProtocol>
</code>```

Thanks

答: I managed to solve this by adding the Authorize attribute to both of my controllers that I was calling from Angular2. By using withCredentials in my http calls in my Angular2 app, I had to also add the Authorize attribute on my controllers in order to get it to work. I also had to enable Anonymous authentication as well as Integrated/Windows Authentication on IIS in order to get this to all work</p>

Body:
I've come across an issue with CORS between an Angular2 application and a WebAPI application when my Angular2 app is running on my own machine but the WebAPI app is running on IIS on a web server. Interestingly, everything works fine if I run both the applications on my own machine

I get the following error in Chrome:-

XMLHttpRequest cannot load http://fowebtst01l:81/FilePusher.Service/api/version. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401.

I've installed the CORS nuget package in my WebAPI application and enabled it in my WebApiConfig class using

            var attrib = new EnableCorsAttribute("*", "*", "*") {SupportsCredentials = true};
        config.EnableCors(attrib);

I've also added this code into my Global.asax.cs file:-

        protected void Application_BeginRequest()
    {
        if (Request.HttpMethod == "OPTIONS")
        {
            string header = Request.Headers.GetValues("Origin")[0];

            Response.StatusCode = (int)HttpStatusCode.OK;
            Response.AppendHeader("Access-Control-Allow-Origin", header);
            Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            Response.AppendHeader("Access-Control-Allow-Credentials", "true");
            Response.End();
        }
    }

But to no avail. Can anyone help with this?

Note that if I remove the code to enable CORS and instead add in the following settings into my Web.config then I get this error when running everything locally:-

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD, OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true"/>
    <add name="Access-Control-Allow-Headers" value="X-Requested-With, origin, content-type, accept" />
  </customHeaders>
</httpProtocol>

Thanks


问:
Generate all possible choices of elements each from a distinct set
Suppose that we have k sets each of which contains q elements. I want to generate all possible sets in which we select exactly 1 element from each set. Assume that the sets are represented as a table where each row is a set and its columns are its elements. Also assume that all elements are indexed row-wise like this

Set 1: 1 2 3

Set 2: 4 5 6

Set 3: 7 8 9

The thing is that k,q may vary so I cannot use nested for loops. I work in C++ and this structure is actually a std::vector of std::vector of int, but I am not asking for code here, just an idea on how to do this.

答:
You can use backtracking here to generate all subsets

```<code>  void func(vector<vector<int> > arr,int row,vector<int> &temp,vector<vector<int> > &ans)
  {
    if(row>=arr.size())
    {
        ans.push_back(temp);    //You have generated one of the answers.store it
        return;
    }
    for(int i=0;i<arr[row].size();i++)
    {
        temp.push_back(arr[row][i]);  //Pick an element from current set
        func(arr,row+1,temp,ans);     //recurse for next set
        temp.pop_back();              //Remove from current set to include next element from this set(for loop)
    }
  }
</code>```

Working code: http://ideone.com/RvHMNT

Body:
You can use backtracking here to generate all subsets

  void func(vector<vector<int> > arr,int row,vector<int> &temp,vector<vector<int> > &ans)
  {
    if(row>=arr.size())
    {
        ans.push_back(temp);    //You have generated one of the answers.store it
        return;
    }
    for(int i=0;i<arr[row].size();i++)
    {
        temp.push_back(arr[row][i]);  //Pick an element from current set
        func(arr,row+1,temp,ans);     //recurse for next set
        temp.pop_back();              //Remove from current set to include next element from this set(for loop)
    }
  }

Working code: http://ideone.com/RvHMNT


问:
putting recyclerview in other Listview
This is the file i am inflating in other recyclerview and i have also attached another recyclerview in it, but i can't set it.

I have also searched some references but can't find the right one. Help me out here how to do it.

Thank you.

```<code><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_margin="10dp"
    android:elevation="3dp"
    app:cardBackgroundColor="#b7a2d6"
    app:cardCornerRadius="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/lesson_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="LessonName"
            android:textColor="#fff"
            android:textSize="25sp"
            android:textStyle="bold" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerViewChapters"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/lesson_name"
            android:padding="10dp" />
    </RelativeLayout>
</android.support.v7.widget.CardView>
</code>```

SubjectActivity:

```<code>public class SubjectActivity extends AppCompatActivity {

    private RecyclerView lessonNamerecyclerView, recyclerViewChapters;

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

        lessonNamerecyclerView = (RecyclerView) findViewById(R.id.recyclerViewLesson);
        recyclerViewChapters = (RecyclerView) findViewById(R.id.recyclerViewChapters);

        lessonNamerecyclerView.setLayoutManager(new LinearLayoutManager(this));
        lessonNamerecyclerView.setAdapter(new LessonAdapter());

        recyclerViewChapters.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
        recyclerViewChapters.setAdapter(new DemoVideoAdapter());

    }

}
</code>```

答:
I have implemented something similar i made a main listview instead of recycle view and made horizontal recycleview as row of llistview. Adding some code snippets Hope it help.

```<code>Main Activity - only simple list view
 listview= (ListView) findViewById(R.id.listView);
    ListAdapter adapter=new ListAdapter(this);
    listview.setAdapter(adapter);

List Adapter
public class ListAdapter extends BaseAdapter {
private Context context;

private int lengt=4;
private String[] names={"Item 1","Item 2","Item 3 ","Item 4","Item 5"};
LayoutInflater layoutInflater;
RecyclerAdapter recyclerAdapter;
public ListAdapter(Context context){
    this.context=context;
    layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    recyclerAdapter=new RecyclerAdapter(context);
}

@Override
public int getCount() {
    return lengt;
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    View view1=layoutInflater.inflate(R.layout.recyclelayout,null,false);
    // here was text view
   // TextView tittle=(TextView)view1.findViewById(R.id.textView);
   // tittle.setText(names[i]);
   // TextView se=(TextView)view1.findViewById(R.id.textView2);
   // se.setText("See All >");
    RecyclerView recyclerView=(RecyclerView)view1.findViewById(R.id.recycler);
    recyclerView.setAdapter(recyclerAdapter);

    LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false);
    recyclerView.setLayoutManager(linearLayoutManager);
    return view1;
}
</code>```

}

xml of row of listview that is recyclelayout

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:clipToPadding="false">
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:id="@+id/recycler">
</android.support.v7.widget.RecyclerView>
</code>```

And the Recycleview adapter class is this.

```<code>class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerHolder> {
public int[] image={R.drawable.ic_close_24dp,R.drawable.ic_more_vert_24dp,R.drawable.ic_play_arrow_24dp,R.drawable.ic_skip_next_24dp};
private Context context;
public RecyclerAdapter(Context context){
    this.context=context;
}
@Override
public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclercontent,parent,false);
    RecyclerHolder vh=new RecyclerHolder(v);
    return vh;
}

@Override
public void onBindViewHolder(RecyclerHolder holder, int position) {
    holder.imageView.setImageResource(image[position]);
}

@Override
public int getItemCount() {
    return image.length;
}

public class RecyclerHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    public ImageView imageView;
    public CardView cardView;
    public RecyclerHolder(View itemView) {
        super(itemView);
        imageView=(ImageView)itemView.findViewById(R.id.imageView2);
        cardView=(CardView)itemView.findViewById(R.id.carview);
        imageView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == imageView.getId()) {
            Toast.makeText(view.getContext(),"Item Pressed =" + String.valueOf(getAdapterPosition()),Toast.LENGTH_SHORT).show();
         //   Intent intent=new Intent(context,ItemInfo.class);
           // context.startActivity(intent);
        }
    }
}
</code>```

}

Any doubt just let me know. Hope it helps you.

EDIT- adding remaining xml files

recyclercontent.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff"
android:outlineProvider="bounds">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:translationZ="10dp"
    android:id="@+id/carview">
    <ImageView
        android:layout_width="150dp"
        android:layout_height="145dp"
        android:id="@+id/imageView2"
        android:layout_marginLeft="0dp" />
</android.support.v7.widget.CardView>
</code>```

swipelayout.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/imageView"
    android:layout_gravity="center_vertical" />
</code>```

Title: putting recyclerview in other Listview

Body:
This is the file i am inflating in other recyclerview and i have also attached another recyclerview in it, but i can't set it.

I have also searched some references but can't find the right one. Help me out here how to do it.

Thank you.

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_margin="10dp"
    android:elevation="3dp"
    app:cardBackgroundColor="#b7a2d6"
    app:cardCornerRadius="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/lesson_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="LessonName"
            android:textColor="#fff"
            android:textSize="25sp"
            android:textStyle="bold" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerViewChapters"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/lesson_name"
            android:padding="10dp" />
    </RelativeLayout>
</android.support.v7.widget.CardView>

SubjectActivity:

public class SubjectActivity extends AppCompatActivity {

    private RecyclerView lessonNamerecyclerView, recyclerViewChapters;

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

        lessonNamerecyclerView = (RecyclerView) findViewById(R.id.recyclerViewLesson);
        recyclerViewChapters = (RecyclerView) findViewById(R.id.recyclerViewChapters);

        lessonNamerecyclerView.setLayoutManager(new LinearLayoutManager(this));
        lessonNamerecyclerView.setAdapter(new LessonAdapter());

        recyclerViewChapters.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
        recyclerViewChapters.setAdapter(new DemoVideoAdapter());

    }

}

Body:
I have implemented something similar i made a main listview instead of recycle view and made horizontal recycleview as row of llistview. Adding some code snippets Hope it help.

Main Activity - only simple list view
 listview= (ListView) findViewById(R.id.listView);
    ListAdapter adapter=new ListAdapter(this);
    listview.setAdapter(adapter);

List Adapter
public class ListAdapter extends BaseAdapter {
private Context context;

private int lengt=4;
private String[] names={"Item 1","Item 2","Item 3 ","Item 4","Item 5"};
LayoutInflater layoutInflater;
RecyclerAdapter recyclerAdapter;
public ListAdapter(Context context){
    this.context=context;
    layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    recyclerAdapter=new RecyclerAdapter(context);
}

@Override
public int getCount() {
    return lengt;
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    View view1=layoutInflater.inflate(R.layout.recyclelayout,null,false);
    // here was text view
   // TextView tittle=(TextView)view1.findViewById(R.id.textView);
   // tittle.setText(names[i]);
   // TextView se=(TextView)view1.findViewById(R.id.textView2);
   // se.setText("See All >");
    RecyclerView recyclerView=(RecyclerView)view1.findViewById(R.id.recycler);
    recyclerView.setAdapter(recyclerAdapter);

    LinearLayoutManager linearLayoutManager=new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false);
    recyclerView.setLayoutManager(linearLayoutManager);
    return view1;
}

}

xml of row of listview that is recyclelayout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:clipToPadding="false">
<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:id="@+id/recycler">
</android.support.v7.widget.RecyclerView>

And the Recycleview adapter class is this.

class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerHolder> {
public int[] image={R.drawable.ic_close_24dp,R.drawable.ic_more_vert_24dp,R.drawable.ic_play_arrow_24dp,R.drawable.ic_skip_next_24dp};
private Context context;
public RecyclerAdapter(Context context){
    this.context=context;
}
@Override
public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclercontent,parent,false);
    RecyclerHolder vh=new RecyclerHolder(v);
    return vh;
}

@Override
public void onBindViewHolder(RecyclerHolder holder, int position) {
    holder.imageView.setImageResource(image[position]);
}

@Override
public int getItemCount() {
    return image.length;
}

public class RecyclerHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    public ImageView imageView;
    public CardView cardView;
    public RecyclerHolder(View itemView) {
        super(itemView);
        imageView=(ImageView)itemView.findViewById(R.id.imageView2);
        cardView=(CardView)itemView.findViewById(R.id.carview);
        imageView.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == imageView.getId()) {
            Toast.makeText(view.getContext(),"Item Pressed =" + String.valueOf(getAdapterPosition()),Toast.LENGTH_SHORT).show();
         //   Intent intent=new Intent(context,ItemInfo.class);
           // context.startActivity(intent);
        }
    }
}

}

Any doubt just let me know. Hope it helps you.

EDIT- adding remaining xml files

recyclercontent.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff"
android:outlineProvider="bounds">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp"
    android:translationZ="10dp"
    android:id="@+id/carview">
    <ImageView
        android:layout_width="150dp"
        android:layout_height="145dp"
        android:id="@+id/imageView2"
        android:layout_marginLeft="0dp" />
</android.support.v7.widget.CardView>

swipelayout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/imageView"
    android:layout_gravity="center_vertical" />


问:
git not adding existing folder
I started working on a project recently, then decided to push it up to github. So I did the following:

```<code>cd <root>
git init
git add -A
git commit -m 'message'
git remote add origin <ur>
git push -u origin master
</code>```

this, however, omitted an entire folder of my project. its basically a folder 1 level down from my root folder so:

```<code>root
 -folder //omitted
</code>```

I'm trying to do git add -A / git add * / git add . but every time I do git status it says there are changes but the folder is untracked.

I even tried to specifically add the folder git add folderName but git status is still showing it as untracked.

I also tried to navigate into the folder itself, and do a git add * and that added everything INSIDE of this folder, but I just cant seem to add the folder itself.

any idea what else I can do?

答:
A subfolder will not be added with git add . (or similar commands) if it contains a .git dir because it will be assumed to be a git submodule.

You can rm -rf .git in the subfolder if it's not supposed to be a submodule.

Title: git not adding existing folder

Body:
I started working on a project recently, then decided to push it up to github. So I did the following:

cd <root>
git init
git add -A
git commit -m 'message'
git remote add origin <ur>
git push -u origin master

this, however, omitted an entire folder of my project. its basically a folder 1 level down from my root folder so:

root
 -folder //omitted

I'm trying to do git add -A / git add * / git add . but every time I do git status it says there are changes but the folder is untracked.

I even tried to specifically add the folder git add folderName but git status is still showing it as untracked.

I also tried to navigate into the folder itself, and do a git add * and that added everything INSIDE of this folder, but I just cant seem to add the folder itself.

any idea what else I can do?


问:
How to set width AND pad integer witdth String Formatter in Java
Given I have the following integers:

```<code>1, 10, 100
</code>```

I want to pad them with zeroes to have exactly 3 digits:

```<code>001
010
100
</code>```

and I want to print them prefixed by 10 spaces:

```<code>      001 //assume 10 spaces from the beginning of the line
      010
      100
</code>```

I want to use Java formatter string to accomplish this but am only successful in accomplishing one of the above mention conditions but not both at once.

Below are 2 expressions that I created that accomplish each one of these conditions:

```<code>    @Test
    public void test1() {

        String[] langs = { "TEXTX", "TEXTXXX", "TEXTXX" };
        int[] nums = {1, 10, 100};

        for (int i = 0; i < 3; i++) {

            String s = langs[i];
            int n = nums[i];

            System.out.printf("%1$s%2$14s%3$03d\n", s, " ", n);
        }

    }
</code>```

According to documentation the formatter string has the below form:

```<code>%[argument_index$][flags][width][.precision]conversion
</code>```

but apparently the zero padding flag parameter cannot be followed by width parameter as it is being parsed as one number resulting in a "long width".

How can this be rewritten to accomplish the above mentioned conditions?

NOTE:

My only idea was to explicitly add a single space to the arguments and try to manipulate it as an argument. Something like this:

```<code>System.out.printf("%1$s%2$10s%3$03d\n", s, " ", n);
</code>```

EDIT:

My apologies, I just realized that I didn't fully described my question. These numbers need to follow certain other strings of different length, like this:

```<code>textX       001
textXXX     010
textXX      100
</code>```

So that the spacing is variable.

答:
If the two only criterias are the padding of 10 Spaces and zero-padding of the numbers:

```<code>final String str = String.format("%10s%03d", " ", 2);
</code>```

Edit after update from OP:

```<code> System.out.printf("%-10s%03d", "abc", 2);
</code>```

How it Works:

We need two arguments for Our pattern, one for the String of length 10, and one for the integer.

%10s is a pattern for a String of length 10. In order to left align it, we add the -: %-10s. The second argument is the integer of length 3 that we want to left pad With zero: %03d.

If we dont want to rearrange or reuse an argument for multiple format specifiers, just pass the arguments in the order specified in the pattern.

Body:
Given I have the following integers:

1, 10, 100

I want to pad them with zeroes to have exactly 3 digits:

001
010
100

and I want to print them prefixed by 10 spaces:

      001 //assume 10 spaces from the beginning of the line
      010
      100

I want to use Java formatter string to accomplish this but am only successful in accomplishing one of the above mention conditions but not both at once.

Below are 2 expressions that I created that accomplish each one of these conditions:

    @Test
    public void test1() {

        String[] langs = { "TEXTX", "TEXTXXX", "TEXTXX" };
        int[] nums = {1, 10, 100};

        for (int i = 0; i < 3; i++) {

            String s = langs[i];
            int n = nums[i];

            System.out.printf("%1$s%2$14s%3$03d\n", s, " ", n);
        }

    }

According to documentation the formatter string has the below form:

%[argument_index$][flags][width][.precision]conversion

but apparently the zero padding flag parameter cannot be followed by width parameter as it is being parsed as one number resulting in a "long width".

How can this be rewritten to accomplish the above mentioned conditions?

NOTE:

My only idea was to explicitly add a single space to the arguments and try to manipulate it as an argument. Something like this:

System.out.printf("%1$s%2$10s%3$03d\n", s, " ", n);

EDIT:

My apologies, I just realized that I didn't fully described my question. These numbers need to follow certain other strings of different length, like this:

textX       001
textXXX     010
textXX      100

So that the spacing is variable.

Body:
If the two only criterias are the padding of 10 Spaces and zero-padding of the numbers:

final String str = String.format("%10s%03d", " ", 2);

Edit after update from OP:

 System.out.printf("%-10s%03d", "abc", 2);

How it Works:

We need two arguments for Our pattern, one for the String of length 10, and one for the integer.

%10s is a pattern for a String of length 10. In order to left align it, we add the -: %-10s. The second argument is the integer of length 3 that we want to left pad With zero: %03d.

If we dont want to rearrange or reuse an argument for multiple format specifiers, just pass the arguments in the order specified in the pattern.


问:
How to send All objects of Mutable Array to Another Class?
I want to send Mutable Array with all its objects from my First Class to Second Class. I have no idea how can i do this please anybody tell me the way... </p>

答:
Try this:

```<code>yourSecondClass.mutableArray_asAMemberVariable = [[yourFirstClass mutableArray_asAMemberVariable] copy];
</code>```

This makes a copy out your firstClass mutable array and sends it to your second class.

Body:
Try this:

yourSecondClass.mutableArray_asAMemberVariable = [[yourFirstClass mutableArray_asAMemberVariable] copy];

This makes a copy out your firstClass mutable array and sends it to your second class.


问:
Using a JSON script in HTML and show data
Here is the Link to JSON.
http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json

This JSON file give data about weather

And I want to show this data, given by the above link into my HTML file. I am using JSON for the first time. So I need help linking this JSON file into my HTML document.

```<code><html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
</head>

<body>

<div class="wrapper">
<span id="temp"></span>
<span id="high"></span>
<span id="low"></span>
<span id="windspeed"></span>
<span id="description"></span>
<span id="city"></span>
<span id="iconorimage"></span>
<span id="time"></span>
<span id="any thing else"></span>
</div>
</body>
</html>
</code>```

I am ok, If I can show only temperature, city, weather icon [rain,sunny], a text description about weather, high/low, wind speed and time.

答:
Try this, It may help you

jsFiddle for the same
https://jsfiddle.net/sd0zc43j/3/

Using below ajax call

```<code>$.ajax({
  dataType: "json",
  url:"//api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json",
  success: function(data){
   $('#city').html("City : " + data["current_observation"]["display_location"]["city"]);
   $('#high').html("High Fahrenheit: " + data["forecast"]["simpleforecast"]["forecastday"][0]["high"]["fahrenheit"] + " & Celsius: " + data["forecast"]["simpleforecast"]["forecastday"][0]["high"]["celsius"]);
   $('#low').html("Low Fahrenheit: " + data["forecast"]["simpleforecast"]["forecastday"][0]["low"]["fahrenheit"] + " & Celsius: " + data["forecast"]["simpleforecast"]["forecastday"][0]["low"]["celsius"]);
   $('#temp').html("Tempearature : " + data["current_observation"]["temperature_string"]);
   $('#windspeed').html("Wind Speed : " + data["current_observation"]["wind_string"]);
   $('#description').html("Description : " + data["current_observation"]["icon"]);
   // $('#iconorimage').html("Icon URL : " + data["current_observation"]["icon_url"]);
   $('#img').attr("src",data["current_observation"]["icon_url"]);
  }
});
</code>```

Body:
Here is the Link to JSON.
http://api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json

This JSON file give data about weather

And I want to show this data, given by the above link into my HTML file. I am using JSON for the first time. So I need help linking this JSON file into my HTML document.

I am ok, If I can show only temperature, city, weather icon [rain,sunny], a text description about weather, high/low, wind speed and time.

Body:
Try this, It may help you

jsFiddle for the same
https://jsfiddle.net/sd0zc43j/3/

Using below ajax call

$.ajax({
  dataType: "json",
  url:"//api.wunderground.com/api/c3d8a6a640832fd0/conditions/forecast/alert/q/29.9205347,73.8706849.json",
  success: function(data){
   $('#city').html("City : " + data["current_observation"]["display_location"]["city"]);
   $('#high').html("High Fahrenheit: " + data["forecast"]["simpleforecast"]["forecastday"][0]["high"]["fahrenheit"] + " & Celsius: " + data["forecast"]["simpleforecast"]["forecastday"][0]["high"]["celsius"]);
   $('#low').html("Low Fahrenheit: " + data["forecast"]["simpleforecast"]["forecastday"][0]["low"]["fahrenheit"] + " & Celsius: " + data["forecast"]["simpleforecast"]["forecastday"][0]["low"]["celsius"]);
   $('#temp').html("Tempearature : " + data["current_observation"]["temperature_string"]);
   $('#windspeed').html("Wind Speed : " + data["current_observation"]["wind_string"]);
   $('#description').html("Description : " + data["current_observation"]["icon"]);
   // $('#iconorimage').html("Icon URL : " + data["current_observation"]["icon_url"]);
   $('#img').attr("src",data["current_observation"]["icon_url"]);
  }
});


问:
How to remove UIBarButtonItem tintColor animation on iOS?
I have a BarButtonItem animation here:

```<code>[UIView animateWithDuration:AnimDurationTintColorHint delay:0 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
    [view performSelector:@selector(setTintColor:) withObject:UIColor.blackColor];
} completion:^(BOOL finished) {
  ........
}];
</code>```

because UIBarButtonItem has no layer property, I can't use .layer removeAllAnimations to stop the endless animation assigned.

How to remove that?

答:
You have to take leftBarButtonItem or rightBarButtonItem and then set enabled property of UIBarButtonItem to NO.</p>

```<code>UIImage *img = [UIImage imageNamed:@"your image"];
    UIButton *btnMenu = [UIButton buttonWithType:UIButtonTypeCustom];
    btnMenu.frame = CGRectMake( 10, 0, img.size.width, img.size.height);
    [btnMenu addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
    [btnMenu setImage:img forState:UIControlStateNormal];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:btnMenu];
    self.navigationItem.leftBarButtonItem = backButton;
self.navigationItem.leftBarButtonItem.enabled = NO;
</code>```

Body:
I have a BarButtonItem animation here:

[UIView animateWithDuration:AnimDurationTintColorHint delay:0 options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse animations:^{
    [view performSelector:@selector(setTintColor:) withObject:UIColor.blackColor];
} completion:^(BOOL finished) {
  ........
}];

because UIBarButtonItem has no layer property, I can't use .layer removeAllAnimations to stop the endless animation assigned.

How to remove that?

Body:
You have to take leftBarButtonItem or rightBarButtonItem and then set enabled property of UIBarButtonItem to NO.

UIImage *img = [UIImage imageNamed:@"your image"];
    UIButton *btnMenu = [UIButton buttonWithType:UIButtonTypeCustom];
    btnMenu.frame = CGRectMake( 10, 0, img.size.width, img.size.height);
    [btnMenu addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
    [btnMenu setImage:img forState:UIControlStateNormal];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:btnMenu];
    self.navigationItem.leftBarButtonItem = backButton;
self.navigationItem.leftBarButtonItem.enabled = NO;


问:
Case insensitive regex with Postgres and JOOQ?
I currently use this code with JOOQ:

```<code>Condition condition = DSL.trueCondition();
if( isNotBlank(email) ){
  condition = condition.and(APP_USER.EMAIL.likeRegex(email));
}
</code>```

That ends up issuing Postgres specific SQL that does the regex match in the DB:

```<code>app_user.email ~ '{email regex}'
</code>```

Is it possible to get JOOQ to issue the case insensitive version: app_user.email ~* '{email regex}'?

My current workaround is to use this code:

```<code>if( isNotBlank(email) ){
  condition = condition.and(
    APP_USER.EMAIL.lower().likeRegex(email.toLowerCase()) );
}
</code>```

答:
If ever the jOOQ API is missing vendor-specific functionality, the answer is "plain SQL". In your case, simply write this:

PostgreSQL-specific solution

```<code>Condition condition = DSL.trueCondition();
if( isNotBlank(email) ){
  condition = condition.and("{0} ~* {1}", APP_USER.EMAIL, DSL.val(email));
}
</code>```

The method Condition.and(String, QueryPart...) is just convenience for creating an explicit plain SQL Condition through DSL.condition(String, QueryPart...):

```<code>Condition condition = DSL.trueCondition();
if( isNotBlank(email) ){
  condition = condition.and(DSL.condition("{0} ~* {1}", APP_USER.EMAIL, DSL.val(email)));
}
</code>```

Vendor-agnostic solution

If you want to be vendor-agnostic, you'd have to wrap the above code in your own utility and resort to using a CustomCondition

```<code>public static Condition caseInsensitiveLikeRegex(Field<String> field, String regex) {
    return new CustomCondition() {
        @Override
        public void accept(Context<?> ctx) {
            if (ctx.family() == POSTGRES)
                ctx.visit(DSL.condition("{0} ~* {1}", field, DSL.val(regex));
            else
                ctx.visit(field.lower().likeRegex(regex.toLowerCase()));
        }
    }
}
</code>```

The regex.toLowerCase() call is not 100% correct, of course, as it lower cases both the regex content, as well as the escaped patterns, such as \B for backslash, but you get the idea.

Body:
I currently use this code with JOOQ:

Condition condition = DSL.trueCondition();
if( isNotBlank(email) ){
  condition = condition.and(APP_USER.EMAIL.likeRegex(email));
}

That ends up issuing Postgres specific SQL that does the regex match in the DB:

app_user.email ~ '{email regex}'

Is it possible to get JOOQ to issue the case insensitive version: app_user.email ~* '{email regex}'?

My current workaround is to use this code:

if( isNotBlank(email) ){
  condition = condition.and(
    APP_USER.EMAIL.lower().likeRegex(email.toLowerCase()) );
}

Body:
If ever the jOOQ API is missing vendor-specific functionality, the answer is "plain SQL". In your case, simply write this:

PostgreSQL-specific solution

Condition condition = DSL.trueCondition();
if( isNotBlank(email) ){
  condition = condition.and("{0} ~* {1}", APP_USER.EMAIL, DSL.val(email));
}

The method Condition.and(String, QueryPart...) is just convenience for creating an explicit plain SQL Condition through DSL.condition(String, QueryPart...):

Condition condition = DSL.trueCondition();
if( isNotBlank(email) ){
  condition = condition.and(DSL.condition("{0} ~* {1}", APP_USER.EMAIL, DSL.val(email)));
}

Vendor-agnostic solution

If you want to be vendor-agnostic, you'd have to wrap the above code in your own utility and resort to using a CustomCondition

public static Condition caseInsensitiveLikeRegex(Field<String> field, String regex) {
    return new CustomCondition() {
        @Override
        public void accept(Context<?> ctx) {
            if (ctx.family() == POSTGRES)
                ctx.visit(DSL.condition("{0} ~* {1}", field, DSL.val(regex));
            else
                ctx.visit(field.lower().likeRegex(regex.toLowerCase()));
        }
    }
}

The regex.toLowerCase() call is not 100% correct, of course, as it lower cases both the regex content, as well as the escaped patterns, such as \B for backslash, but you get the idea.


问:
The animation scroll to top button does not work
a couple of days ago i started working with my companies website. I saw it was missing something so I decided to make a scroll to top button with animation. I am a noob in programming so i decided to look on the Internet. There I found this example. I literally copied the whole code but it does not work.

the button in the html:

```<code><a href="javascript:" id="return-to-top"><i class="icon-chevron-up"></i></a>
</code>```

and this is the jQuery:

```<code>$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {
        $('#return-to-top').fadeIn(200);
    } else {
        $('#return-to-top').fadeOut(200);
    }
});
$('#return-to-top').click(function() {
    $('body, html').animate({
        scrollTop : 0
    }, 500);
});
</code>```

I dont know what the problem is because it works on the codepen. Does anyone know how to fix this?

Thanks in advance

答:
Which browser are you using?

Anyway, $(window).scrollTop(0); seems to be supported by all browsers, but if you want to animate the scroll, $('html,body').animate({scrollTop:0},500);, like you're using, if you can share your HTML and CSS code, maybe the problem is in the z-index or try to put the width and the height of the ".icon-chevron-up" also to the "#return-to-top".

Everything seems to be working, try to use the console.log('some string here'); to see if the code is running.

Also, check if you added the jquery script:
script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>

Hope you solve it.

Body:
a couple of days ago i started working with my companies website. I saw it was missing something so I decided to make a scroll to top button with animation. I am a noob in programming so i decided to look on the Internet. There I found this example. I literally copied the whole code but it does not work.

the button in the html:

and this is the jQuery:

$(window).scroll(function() {
    if ($(this).scrollTop() >= 50) {
        $('#return-to-top').fadeIn(200);
    } else {
        $('#return-to-top').fadeOut(200);
    }
});
$('#return-to-top').click(function() {
    $('body, html').animate({
        scrollTop : 0
    }, 500);
});

I dont know what the problem is because it works on the codepen. Does anyone know how to fix this?

Thanks in advance


问:
How can I get react-i18next to work with storybook?
I have react-i18next working for the code that runs in the browser, however all our storybook examples are broken because we only test an individual component.

Can someone explain (with examples) how to get storybook that shows individual components working with react-i18next?

答:
Just added a storybook example to react-i18next examples: https://github.com/i18next/react-i18next/tree/master/example/storybook

did not run into any issue...could you please give us more detail on your configuration?


问:
Ruby: What is the easiest way to remove the first element from an array?
Lets say I have an array

```<code>[0, 132, 432, 342, 234]
</code>```

What is the easiest way to get rid of the first element? (0)

答:
You can use:

```<code>arr - [arr[0]]
</code>```

or

```<code>arr - [arr.shift]
</code>```

or simply

```<code>arr.shift(1)
</code>```

Body:
Lets say I have an array

[0, 132, 432, 342, 234]

What is the easiest way to get rid of the first element? (0)

Body:
You can use:

arr - [arr[0]]

or

arr - [arr.shift]

or simply

arr.shift(1)