问:
React-Redux Store is not properly changed by reducer
I'm struggling to learn React-Redux. I'm making a simple application that fetch data from Teleport API and show the list according to the user's input.

My issue is that even though action is dispatched in container component, state is not changed and the result does not show up.

This is a screenshot of console after dispatching action twice.

I suppose that there is an issue to store data properly. I appreciate if you can help me.

Here is my code.

/container/search.js

```<code>class Search extends Component{
 constructor(props){
    super(props);
    this.state = {
      city : ""
    }
   this.handleSubmit = this.handleSubmit.bind(this);
   this.handleChange = this.handleChange.bind(this);
   }

handleChange(event) {
    console.log(event.target.value)
    this.setState({
        city: event.target.value
    });
}

handleSubmit(event){
    event.preventDefault();
    console.log(this.state.city)
    this.props.addData(this.state.city);
    this.setState({
        city: ""
    });
}
render(){
    return(
        <div>
        <form onSubmit={this.handleSubmit}>
        <input type="text"
               placeholder="add city name"
               onChange={this.handleChange}
               value={this.state.city} />
        <button>Submit</button>
        </form>
        </div>
        )
}
}

function mapDispatchToProps(dispatch) {
return bindActionCreators({ addData }, dispatch);
}

export default connect(null, mapDispatchToProps)(Search);
</code>```

/actions/index.js

```<code>import axios from 'axios';

const ROOT_URL = "https://api.teleport.org/api/cities/?search";

const ADD_DATA = 'ADD_DATA';

export function addData(city){
    const url = `${ROOT_URL}=${city}`;
    const request = axios.get(url);
    return {
        type: ADD_DATA,
        payload: request
    };
 }
</code>```

/reducers/reducer_data.js

```<code>import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
switch(action.type) {
    case ADD_DATA:
        return [action.payload.data, ...state];
}
return state;
}
</code>```

/reducers/index.js

```<code>import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
    switch(action.type) {
        case ADD_DATA:
            return [action.payload.data, ...state];
}
return state;
}
</code>```

//EDIT
// index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import logger from 'redux-logger'

import reducers from './reducers';
import Search from './containers/search';

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, logger)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
    <Search />
    </Provider>
, document.querySelector('.container'));
</code>```

答:
Since axios.get(url) is asynchronous you need to wait for the request to succeed and then then dispatch an action. You could make use of middlewares such as redux-thunk while creating a store and then do the following

/actions/index.js

```<code>const ADD_DATA = 'ADD_DATA';

export function addData(city){

    return function(dispatch) {
         const url = `${ROOT_URL}=${city}`;
         axios.get(url)
               .then((res) => {
                    dispatch({
                       type: ADD_DATA,
                       payload: res.data
                    });
               });
    }

 }
</code>```

/reducers/index.js

```<code>import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
    switch(action.type) {
        case ADD_DATA:
            return [...state, action.payload];
}
return state;
}
</code>```

Body:
I'm struggling to learn React-Redux. I'm making a simple application that fetch data from Teleport API and show the list according to the user's input.

My issue is that even though action is dispatched in container component, state is not changed and the result does not show up.

This is a screenshot of console after dispatching action twice.

I suppose that there is an issue to store data properly. I appreciate if you can help me.

Here is my code.

/container/search.js

class Search extends Component{
 constructor(props){
    super(props);
    this.state = {
      city : ""
    }
   this.handleSubmit = this.handleSubmit.bind(this);
   this.handleChange = this.handleChange.bind(this);
   }

handleChange(event) {
    console.log(event.target.value)
    this.setState({
        city: event.target.value
    });
}

handleSubmit(event){
    event.preventDefault();
    console.log(this.state.city)
    this.props.addData(this.state.city);
    this.setState({
        city: ""
    });
}
render(){
    return(

        <form onSubmit={this.handleSubmit}>
        <input type="text"
               placeholder="add city name"
               onChange={this.handleChange}
               value={this.state.city} />
        <button>Submit</button>
        </form>

        )
}
}

function mapDispatchToProps(dispatch) {
return bindActionCreators({ addData }, dispatch);
}

export default connect(null, mapDispatchToProps)(Search);

/actions/index.js

import axios from 'axios';

const ROOT_URL = "https://api.teleport.org/api/cities/?search";

const ADD_DATA = 'ADD_DATA';

export function addData(city){
    const url = `${ROOT_URL}=${city}`;
    const request = axios.get(url);
    return {
        type: ADD_DATA,
        payload: request
    };
 }

/reducers/reducer_data.js

import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
switch(action.type) {
    case ADD_DATA:
        return [action.payload.data, ...state];
}
return state;
}

/reducers/index.js

import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
    switch(action.type) {
        case ADD_DATA:
            return [action.payload.data, ...state];
}
return state;
}

//EDIT
// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promiseMiddleware from 'redux-promise';
import logger from 'redux-logger'

import reducers from './reducers';
import Search from './containers/search';

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, logger)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
    <Search />
    </Provider>
, document.querySelector('.container'));

Body:
Since axios.get(url) is asynchronous you need to wait for the request to succeed and then then dispatch an action. You could make use of middlewares such as redux-thunk while creating a store and then do the following

/actions/index.js

const ADD_DATA = 'ADD_DATA';

export function addData(city){

    return function(dispatch) {
         const url = `${ROOT_URL}=${city}`;
         axios.get(url)
               .then((res) => {
                    dispatch({
                       type: ADD_DATA,
                       payload: res.data
                    });
               });
    }

 }

/reducers/index.js

import { ADD_DATA } from "../actions/index";

export default function( state=[], action) {
    switch(action.type) {
        case ADD_DATA:
            return [...state, action.payload];
}
return state;
}


来源: stackexchange

问:
I'm trying to convert a text file to dictionary or a list Python
I have the following text file datafile.txt

```<code>Pin AccountNumber   FirstName   LastName    AccountBalance      AccountType
2221    436115      Bob         Smith       100.00              Checking
</code>```

I need to load the text file and load it into a dictionary with the pin as the key. This is what I have so far and I do not understand how to proceed

```<code>bData = open('datafile.txt')

for line in bData:
    bInfo = line.split()
    print(bData)
</code>```

答:
first, skip the title line

```<code>next(bData)
</code>```

then build the dict in one line using dict comprehension and star unpacking (python 3):

```<code>d = {k:v for k,*v in (line.split() for line in bData)}
</code>```

python 2 compliant:

```<code>d = {s[0]:s[1:] for s in (line.split() for line in f)}
</code>```

result:

```<code>{'2221': ['436115', 'Bob', 'Smith', '100.00', 'Checking']}
</code>```

(you need to put more lines to get more keys of course)

ContentLicense: CC BY-SA 3.0

Body:
I have the following text file datafile.txt

Pin AccountNumber   FirstName   LastName    AccountBalance      AccountType
2221    436115      Bob         Smith       100.00              Checking

I need to load the text file and load it into a dictionary with the pin as the key. This is what I have so far and I do not understand how to proceed

bData = open('datafile.txt')

for line in bData:
    bInfo = line.split()
    print(bData)

Body:
first, skip the title line

next(bData)

then build the dict in one line using dict comprehension and star unpacking (python 3):

d = {k:v for k,*v in (line.split() for line in bData)}

python 2 compliant:

d = {s[0]:s[1:] for s in (line.split() for line in f)}

result:

{'2221': ['436115', 'Bob', 'Smith', '100.00', 'Checking']}

(you need to put more lines to get more keys of course)


问:
How to convert chr(0xdfff) to utf-8 bytes in Python 3 as in Python 2?
The code below explains my problem. It works as expected in Python 2.7, yet, all of the encode calls I've tried fail in Python 3.5 (see exception below)... does anyone on a way to circumvent this error and make it work in Python 3.5 as it did on Python 2.7?

```<code>import sys

if sys.version_info[0] <= 2:
    chr = unichr

out = chr(0xdfff)
print(repr(out)) # outputs '\udfff' both in Python 2 and 3
assert out.encode('utf-8').decode('utf-8') == out
assert out.encode('utf-8', errors='surrogateescape').decode('utf-8') == out
assert out.encode('utf-8', errors='strict').decode('utf-8') == out
</code>```

Error in Python 3.5:

```<code>Traceback (most recent call last):
  File "W:\rocky40\Projects\etk\coilib50\source\python\coilib50\io\xmlpickle\snippet.py", line 8, in <module>
    assert out.encode('utf-8').decode('utf-8') == out
UnicodeEncodeError: 'utf-8' codec can't encode character '\udfff' in position 0: surrogates not allowed
</code>```

Note that a different encoding wouldn't really suit it as I have files written this way to disk in Python 2 and I need to be able to load it back and dump it again on Python 3 so that Python 2 can read it again (so, the actual bytes written shouldn't really change).

答:
After searching a bit more I noticed that https://docs.python.org/3/library/codecs.html#codec-base-classes points to a surrogatepass which is specific to utf-X codecs, so, using surrogatepass instead of surrogateescape does seem to get the trick done and works properly on Python 3:

```<code>assert out.encode('utf-8', errors='surrogatepass'
    ).decode('utf-8', errors='surrogatepass') == out
</code>```

Body:
The code below explains my problem. It works as expected in Python 2.7, yet, all of the encode calls I've tried fail in Python 3.5 (see exception below)... does anyone on a way to circumvent this error and make it work in Python 3.5 as it did on Python 2.7?

import sys

if sys.version_info[0] <= 2:
    chr = unichr

out = chr(0xdfff)
print(repr(out)) # outputs '\udfff' both in Python 2 and 3
assert out.encode('utf-8').decode('utf-8') == out
assert out.encode('utf-8', errors='surrogateescape').decode('utf-8') == out
assert out.encode('utf-8', errors='strict').decode('utf-8') == out

Error in Python 3.5:

Traceback (most recent call last):
  File "W:\rocky40\Projects\etk\coilib50\source\python\coilib50\io\xmlpickle\snippet.py", line 8, in <module>
    assert out.encode('utf-8').decode('utf-8') == out
UnicodeEncodeError: 'utf-8' codec can't encode character '\udfff' in position 0: surrogates not allowed

Note that a different encoding wouldn't really suit it as I have files written this way to disk in Python 2 and I need to be able to load it back and dump it again on Python 3 so that Python 2 can read it again (so, the actual bytes written shouldn't really change).

Body:
After searching a bit more I noticed that https://docs.python.org/3/library/codecs.html#codec-base-classes points to a surrogatepass which is specific to utf-X codecs, so, using surrogatepass instead of surrogateescape does seem to get the trick done and works properly on Python 3:

assert out.encode('utf-8', errors='surrogatepass'
    ).decode('utf-8', errors='surrogatepass') == out


问:
Capture user behavior in chat bot using microsoft bot framework
I want to capture the user behavior in my chatbot after each response given by bot. it basically a feedback, like/dislike button in Facebook.

Is it possible in MS bot framework?

答:
You can implement feedback yes no button or like button using rich card or hero card.

Many messaging channels provide the ability to attach richer objects. The Bot Framework has the ability to render rich cards as attachments. There are several types of cards supported: Hero Card, Thumbnail Card, Receipt Card, Sign-In Card, Animation Card, Video Card and Audio Card. Once the desired Card type is selected, it is mapped into an Attachment data structure. Check out the key code located in the CardsDialog class where the message.Attachments property of the message activity is populated with a card attachment.

```<code>public async Task DisplaySelectedCard(IDialogContext context, IAwaitable<string> result)
{
    var selectedCard = await result;

    var message = context.MakeMessage();

    var attachment = GetSelectedCard(selectedCard);
    message.Attachments.Add(attachment);

    await context.PostAsync(message);

    context.Wait(this.MessageReceivedAsync);
}
</code>```

Hero Card

The Hero card is a multipurpose card; it primarily hosts a single large image, a button, and a "tap action", along with text content to display on the card. Check out the GetHeroCard method in the CardsDialog class for a Hero Card sample.

```<code>private static Attachment GetHeroCard()
{
    var heroCard = new HeroCard
    {
        Title = "BotFramework Hero Card",
        Subtitle = "Your bots — wherever your users are talking",
        Text = "Build and connect intelligent bots to interact with your users naturally wherever they are, from text/sms to Skype, Slack, Office 365 mail and other popular services.",
        Images = new List<CardImage> { new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg") },
        Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Get Started", value: "https://learn.microsoft.com/bot-framework") }
    };

    return heroCard.ToAttachment();
}
</code>```

i have create a sample. Sharing image with you. On click of Yes it will show a card to give rating as well.

Body:
You can implement feedback yes no button or like button using rich card or hero card.

Many messaging channels provide the ability to attach richer objects. The Bot Framework has the ability to render rich cards as attachments. There are several types of cards supported: Hero Card, Thumbnail Card, Receipt Card, Sign-In Card, Animation Card, Video Card and Audio Card. Once the desired Card type is selected, it is mapped into an Attachment data structure. Check out the key code located in the CardsDialog class where the message.Attachments property of the message activity is populated with a card attachment.

public async Task DisplaySelectedCard(IDialogContext context, IAwaitable<string> result)
{
    var selectedCard = await result;

    var message = context.MakeMessage();

    var attachment = GetSelectedCard(selectedCard);
    message.Attachments.Add(attachment);

    await context.PostAsync(message);

    context.Wait(this.MessageReceivedAsync);
}

Hero Card

The Hero card is a multipurpose card; it primarily hosts a single large image, a button, and a "tap action", along with text content to display on the card. Check out the GetHeroCard method in the CardsDialog class for a Hero Card sample.

private static Attachment GetHeroCard()
{
    var heroCard = new HeroCard
    {
        Title = "BotFramework Hero Card",
        Subtitle = "Your bots — wherever your users are talking",
        Text = "Build and connect intelligent bots to interact with your users naturally wherever they are, from text/sms to Skype, Slack, Office 365 mail and other popular services.",
        Images = new List<CardImage> { new CardImage("https://sec.ch9.ms/ch9/7ff5/e07cfef0-aa3b-40bb-9baa-7c9ef8ff7ff5/buildreactionbotframework_960.jpg") },
        Buttons = new List<CardAction> { new CardAction(ActionTypes.OpenUrl, "Get Started", value: "https://learn.microsoft.com/bot-framework") }
    };

    return heroCard.ToAttachment();
}

i have create a sample. Sharing image with you. On click of Yes it will show a card to give rating as well.


问:
How to get all users that the logged in user is not friends with in MySQL?
I am fully able to get all of the logged in users current friends, which I do with this query here -

```<code>SELECT users.*
FROM users
LEFT JOIN friends
ON users.id = friends.friend_id
WHERE friends.user_id = $user_logged_in_id
</code>```

But I want to do the opposite, and I can't figure it out.

I am trying to do friends logic.

I need to get all the users who the currently logged in user is not already friends with

I have a users table and a friends table to act as a many to many relationship between users and their friends. The keys in the friends table are user_id friend_id.

To illustrate that someone is friends with another user I put (say the logged in user id is 3, and friends user id is 6) user_id = 3 and friend_id = 6 as one row, and then put another row with the id's flipped to illustrate the friendship the other way, user_id = 6 and friend_id = 3.

users table

```<code>|---------------------|------------------|
|          id         |     username     |
|---------------------|------------------|
|          1          |     sonja12      |
|---------------------|------------------|
|          2          |     dorris32     |
|---------------------|------------------|
|          3          |     billy32      |
|---------------------|------------------|
|          4          |     micha97      |
|---------------------|------------------|
|          5          |     travis841    |
|---------------------|------------------|
|          6          |     johnny28     |
|---------------------|------------------|
</code>```

friends table

```<code>|---------------------|------------------|------------------|
|          id         |     user_id      |     friend_id    |
|---------------------|------------------|------------------|
|          1          |        3         |         6        |
|---------------------|------------------|------------------|
|          2          |        6         |         3        |
|---------------------|------------------|------------------|
</code>```

EDIT:

I think I have narrowed down my question a bit to be more concise.

I want to get all users from the users table where their id does not appear as a friend id beside the user_id of the current logged in user in the friends table.

答:
For bigger Datasets I would use a NOT EXISTS subquery query:

```<code>select u.*
from users u
where u.id <> $user_logged_in_id
  and not exists (
    select *
    from friends f
    where f.user_id = $user_logged_in_id
      and f.friend_id = u.id
)
</code>```

or a LEFT (ANTI) JOIN:

```<code>select u.*
from users u
left join friends f
  on  f.user_id = $user_logged_in_id
  and f.friend_id = u.id
where u.id <> $user_logged_in_id
  and f.friend_id is null
</code>```

I think the execution plan for both queries should be almost the same.

Demos: http://rextester.com/KUOZ9198

Body:
I am fully able to get all of the logged in users current friends, which I do with this query here -

SELECT users.*
FROM users
LEFT JOIN friends
ON users.id = friends.friend_id
WHERE friends.user_id = $user_logged_in_id

But I want to do the opposite, and I can't figure it out.

I am trying to do friends logic.

I need to get all the users who the currently logged in user is not already friends with

I have a users table and a friends table to act as a many to many relationship between users and their friends. The keys in the friends table are user_id friend_id.

To illustrate that someone is friends with another user I put (say the logged in user id is 3, and friends user id is 6) user_id = 3 and friend_id = 6 as one row, and then put another row with the id's flipped to illustrate the friendship the other way, user_id = 6 and friend_id = 3.

users table

|---------------------|------------------|
|          id         |     username     |
|---------------------|------------------|
|          1          |     sonja12      |
|---------------------|------------------|
|          2          |     dorris32     |
|---------------------|------------------|
|          3          |     billy32      |
|---------------------|------------------|
|          4          |     micha97      |
|---------------------|------------------|
|          5          |     travis841    |
|---------------------|------------------|
|          6          |     johnny28     |
|---------------------|------------------|

friends table

|---------------------|------------------|------------------|
|          id         |     user_id      |     friend_id    |
|---------------------|------------------|------------------|
|          1          |        3         |         6        |
|---------------------|------------------|------------------|
|          2          |        6         |         3        |
|---------------------|------------------|------------------|

EDIT:

I think I have narrowed down my question a bit to be more concise.

I want to get all users from the users table where their id does not appear as a friend id beside the user_id of the current logged in user in the friends table.

Body:
For bigger Datasets I would use a NOT EXISTS subquery query:

select u.*
from users u
where u.id <> $user_logged_in_id
  and not exists (
    select *
    from friends f
    where f.user_id = $user_logged_in_id
      and f.friend_id = u.id
)

or a LEFT (ANTI) JOIN:

select u.*
from users u
left join friends f
  on  f.user_id = $user_logged_in_id
  and f.friend_id = u.id
where u.id <> $user_logged_in_id
  and f.friend_id is null

I think the execution plan for both queries should be almost the same.

Demos: http://rextester.com/KUOZ9198


问:
How to Disable the word suggestion strip in keyboard in ionic app
I want to disable the word suggestion (the line above the keyboard with thus this thos thi thik tha) in my ionic app
I have tried autocomplete="off",autocaptiliaze ="off" and all those properties but they are not working

i want a keyboard without word suggestion strip .. the one like when it comes for password type...can anyone suggest anything that helps... and i want the solution for ionic cordova apps not the native android or ios

答:
You can disable suggestions on the Soft Keyboard by adding the following line in the xml Edittext.

```<code>android:inputType="textNoSuggestions"
</code>```

Happy coding!!

Body:
You can disable suggestions on the Soft Keyboard by adding the following line in the xml Edittext.

android:inputType="textNoSuggestions"

Happy coding!!


问:
MPAndroidChart Value formatter out of array range
I wanna format XAxis values from int to String (actually date) the problem is that formatter is not stopping when ArrayList size is reached and I get out of array range exception. What can I do about this ?

```<code>    barEntries=new ArrayList <> (  );
    XAxisLabels=new ArrayList <> (  );
    barEntries.add ( new BarEntry ( 0,0 ) );
    XAxisLabels.add ( "2017-10-29 09:26:07" );
    barEntries.add ( new BarEntry ( 1,400 ) );
    XAxisLabels.add ( "2017-10-28 19:04:22" );
    barEntries.add ( new BarEntry ( 2,200 ) );
    XAxisLabels.add ( "2017-10-28 19:05:12" );
    barEntries.add ( new BarEntry ( 3,300 ) );
    XAxisLabels.add ( "2017-10-29 09:26:07" );

            BarDataSet barDataSet = new BarDataSet ( barEntries, "DataSet" );
            barDataSet.setColors ( ColorTemplate.COLORFUL_COLORS );

            BarData barData = new BarData ( barDataSet );

            XAxis xAxis = barChart.getXAxis ( );
            xAxis.setPosition ( XAxis.XAxisPosition.BOTH_SIDED );
            xAxis.setValueFormatter ( new MyXAxisValueFormatter ( XAxisLabels ) );
            //xAxis.setGranularity ( 1 );
            xAxis.setCenterAxisLabels ( true );
            //xAxis.setAxisMinimum ( 1 );
            barChart.setData ( barData );
            barChart.notifyDataSetChanged ( );
            barChart.invalidate ( );
</code>```

My Formatter:

```<code>public class MyXAxisValueFormatter implements IAxisValueFormatter{
        int counter=0;
        private ArrayList <String> mValues = new ArrayList <> (  );
        public MyXAxisValueFormatter(ArrayList<String> values)
        {
            this.mValues=values;
        }
        @Override
        public String getFormattedValue ( float value, AxisBase axis ) {
            String x;
            value=value+counter*0.3f;
            counter++;
            x= mValues.get ( (int)value);
            return x;
        }
}
</code>```

Application screenshot

答:
```<code>public class MyXAxisValueFormatter implements IAxisValueFormatter {
private List labels;

public MyXAxisValueFormatter(List<String> labels) {
    this.labels = labels;
}

@Override
public String getFormattedValue(float value, AxisBase axis) {
    try {
        int index = (int) value;
        return labels.get(index);
    } catch (Exception e) {
        return "";
    }
}
}
</code>```

Body:
I wanna format XAxis values from int to String (actually date) the problem is that formatter is not stopping when ArrayList size is reached and I get out of array range exception. What can I do about this ?

    barEntries=new ArrayList <> (  );
    XAxisLabels=new ArrayList <> (  );
    barEntries.add ( new BarEntry ( 0,0 ) );
    XAxisLabels.add ( "2017-10-29 09:26:07" );
    barEntries.add ( new BarEntry ( 1,400 ) );
    XAxisLabels.add ( "2017-10-28 19:04:22" );
    barEntries.add ( new BarEntry ( 2,200 ) );
    XAxisLabels.add ( "2017-10-28 19:05:12" );
    barEntries.add ( new BarEntry ( 3,300 ) );
    XAxisLabels.add ( "2017-10-29 09:26:07" );

            BarDataSet barDataSet = new BarDataSet ( barEntries, "DataSet" );
            barDataSet.setColors ( ColorTemplate.COLORFUL_COLORS );

            BarData barData = new BarData ( barDataSet );

            XAxis xAxis = barChart.getXAxis ( );
            xAxis.setPosition ( XAxis.XAxisPosition.BOTH_SIDED );
            xAxis.setValueFormatter ( new MyXAxisValueFormatter ( XAxisLabels ) );
            //xAxis.setGranularity ( 1 );
            xAxis.setCenterAxisLabels ( true );
            //xAxis.setAxisMinimum ( 1 );
            barChart.setData ( barData );
            barChart.notifyDataSetChanged ( );
            barChart.invalidate ( );

My Formatter:

public class MyXAxisValueFormatter implements IAxisValueFormatter{
        int counter=0;
        private ArrayList <String> mValues = new ArrayList <> (  );
        public MyXAxisValueFormatter(ArrayList<String> values)
        {
            this.mValues=values;
        }
        @Override
        public String getFormattedValue ( float value, AxisBase axis ) {
            String x;
            value=value+counter*0.3f;
            counter++;
            x= mValues.get ( (int)value);
            return x;
        }
}

Application screenshot


问:
How to save logs to file from "Debug" in my project
I use in my project Debug package https://www.npmjs.com/package/debug.
I set environment variable (variablename: DEBUG & value:*). After this i see in my console output logs from my app. I would like save all this logs to file. How i can make this?</p>

答: I would suggest that you try a well know library called Winston</p>


问:
why this code dont write movie data in binery file?
File movie5.dat is create on hard disk but no data is in the file! When I
    run code no error found and file have not binary data.</p>

```<code>import java.nio.file.*;
import java.io.*;

public class Main
{
    public static void main(String[] args)
    {
        DataOutputStream dos=DOS("e:\\movie5.dat");
        movies[] m=movieinfo();
        for (movies mm:m)
        {
            try {
                dos.writeUTF(mm.filmname);
                dos.writeInt(mm.year);
                dos.writeDouble(mm.price);
            }
            catch (IOException e6){System.out.println("I/O write Error."); }

        }
    }

     public static DataOutputStream DOS (String path)
     {
         DataOutputStream dos=null;
       try{
           File f1=new File(path);
           FileOutputStream f2=new FileOutputStream(f1,true);
           BufferedOutputStream f3=new BufferedOutputStream(f2);
           dos=new DataOutputStream(f3);
       }
       catch (FileNotFoundException e1)
       {
           System.out.println("file not found.");
           System.exit(0);
       }
       return dos;
   }

   public static movies[] movieinfo()
   {
       movies[] moviedata=new movies[3];
       moviedata[0]=new movies("Gladiator",2001,14.5);
       moviedata[1]=new movies("Matrix",2004,25.56);
       moviedata[2]=new movies("Spider Man",2017,32.32);
       return moviedata;
   }

   private static class  movies
   {
       String filmname;
       int year;
       double price;

       public movies(String filmname, int year, double price)
       {
           this.filmname=filmname;
           this.year=year;
           this.price=price;
       }
    }
}
</code>```

答: You never flush nor close your BufferedOutputStream. Your program ends before data is actually written to the disk.

Body:
File movie5.dat is create on hard disk but no data is in the file! When I
    run code no error found and file have not binary data.

import java.nio.file.*;
import java.io.*;

public class Main
{
    public static void main(String[] args)
    {
        DataOutputStream dos=DOS("e:\\movie5.dat");
        movies[] m=movieinfo();
        for (movies mm:m)
        {
            try {
                dos.writeUTF(mm.filmname);
                dos.writeInt(mm.year);
                dos.writeDouble(mm.price);
            }
            catch (IOException e6){System.out.println("I/O write Error."); }

        }
    }

     public static DataOutputStream DOS (String path)
     {
         DataOutputStream dos=null;
       try{
           File f1=new File(path);
           FileOutputStream f2=new FileOutputStream(f1,true);
           BufferedOutputStream f3=new BufferedOutputStream(f2);
           dos=new DataOutputStream(f3);
       }
       catch (FileNotFoundException e1)
       {
           System.out.println("file not found.");
           System.exit(0);
       }
       return dos;
   }

   public static movies[] movieinfo()
   {
       movies[] moviedata=new movies[3];
       moviedata[0]=new movies("Gladiator",2001,14.5);
       moviedata[1]=new movies("Matrix",2004,25.56);
       moviedata[2]=new movies("Spider Man",2017,32.32);
       return moviedata;
   }

   private static class  movies
   {
       String filmname;
       int year;
       double price;

       public movies(String filmname, int year, double price)
       {
           this.filmname=filmname;
           this.year=year;
           this.price=price;
       }
    }
}


问:
replace capture match with capture group in bash GNU sed
I've looked around to find a solution to my problem in other posts listed bellow, but it looks my regex is quit different and need special care:
How to output only captured groups with sed
Replace one capture group with another with GNU sed (macOS) 4.4
sed replace line with capture groups

I'm trying to replace a regex match group in big JSON file,
My file has mongoDB exported objects, and I'm trying to replace the objectId with the string:

```<code>{"_id":{"$oid":"56cad2ce0481320c111d2313"},"recordId":{"$oid":"56cad2ce0481320c111d2313"}}
</code>```

So the output in the original file should look like this:
    {"_id":"56cad2ce0481320c111d2313","recordId":"56cad2ce0481320c111d2313"}

That's the command I run in the shell:

```<code>sed -i 's/(?:{"\$oid":)("\w+")}/\$1/g' data.json
</code>```

I get no error, but the file remains the same.
What exactly am I doing wrong?

答:
Finally I've managed to make it work, the way regex works in bash is different then in regexr.com tester tool.

```<code>echo '{"$oid":"56cad2ce0481320c111d2313"}' | sed 's/{"$oid":\("\w*"\)}/\1/g'
</code>```

gives the correct output:

```<code>"56cad2ce0481320c111d2313"
</code>```

I found it even better to read from stdin and output to file, instead of writing first to JSON file, then read, replace and write again.

Since I use mongoexport to export collection, replace the objectId and write the output to JSON file, my final solution looks like this:

```<code>mongoexport --host localhost --db myDB --collection my_collection | sed 's/{"$oid":\\("\\w*"\\)}/\\1/g' >> data.json
</code>```

Body:
I've looked around to find a solution to my problem in other posts listed bellow, but it looks my regex is quit different and need special care:
How to output only captured groups with sed
Replace one capture group with another with GNU sed (macOS) 4.4
sed replace line with capture groups

I'm trying to replace a regex match group in big JSON file,
My file has mongoDB exported objects, and I'm trying to replace the objectId with the string:

{"_id":{"$oid":"56cad2ce0481320c111d2313"},"recordId":{"$oid":"56cad2ce0481320c111d2313"}}

So the output in the original file should look like this:
    {"_id":"56cad2ce0481320c111d2313","recordId":"56cad2ce0481320c111d2313"}

That's the command I run in the shell:

sed -i 's/(?:{"\$oid":)("\w+")}/\$1/g' data.json

I get no error, but the file remains the same.
What exactly am I doing wrong?

Body:
Finally I've managed to make it work, the way regex works in bash is different then in regexr.com tester tool.

echo '{"$oid":"56cad2ce0481320c111d2313"}' | sed 's/{"$oid":\("\w*"\)}/\1/g'

gives the correct output:

"56cad2ce0481320c111d2313"

I found it even better to read from stdin and output to file, instead of writing first to JSON file, then read, replace and write again.

Since I use mongoexport to export collection, replace the objectId and write the output to JSON file, my final solution looks like this:

mongoexport --host localhost --db myDB --collection my_collection | sed 's/{"$oid":\\("\\w*"\\)}/\\1/g' >> data.json


问:
Removing trailing slash on custom urls with .htaccess (not wordpress)
I'm new to learning HTACCESS and I'm trying my best to work on a websites URLs to make them more "seo friendly" and load properly. I've tried searching all over for what I need to point me in the right direction, but everything seems to be for "wordpress" and this is a custom built site.

Here is my issue. This site had a previous developer, the thing was a mess, and I've spent countless hours cleaning up the site, and he built the sites to show urls like this. "www.sitename.com/about-us.php"

I'm familiar enough with htaccess to know how to remove the trailing extension for .php, even showing trailing variables properly that doesn't require the trailing slash at the end like: "sitename.com/about-us?contact=true"

I was able to get the blog view page to load with a url like this: "sitename.com/posts/post-name-here/". This one though does require the trailing slash.

What I'm trying to accomplish is making the url string to work properly with trailing variables for a few pages like, register, apply, etc. So those urls would be something like this. "sitename.com/auth/apply" or "sitename.com/auth/register"

My issue is that the urls have to have a trailing slash at the end or it doesn't load.

Plus adding a trailing variables only works when formatted like this: "sitename.com/auth/apply/?application=submitted"

I'd prefer it look more like this. "sitename.com/auth/apply?application=submitted", without the trailing slash. But I can't find how to accomplish this.

Here is my .htaccess snippet.

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^posts\/(.*)/$ /view-post.php?post=$1 [QSA,NC,L]
RewriteRule ^auth\/(.*)/$ /auth-action.php?action=$1 [QSA,NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

Can someone help me, or point me in the right direction?

答:
Try using the following in your .htaccess. This will remove the trailing slash from your URLs.

```<code>RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=302,L]
</code>```

Make sure you clear your cache before testing this. You'll notice that I've set R=302 instead of 301. This makes it a temporary redirect for testing purposes. If you're happy with the redirect then change it to 301 to make it permanent.

Body:
I'm new to learning HTACCESS and I'm trying my best to work on a websites URLs to make them more "seo friendly" and load properly. I've tried searching all over for what I need to point me in the right direction, but everything seems to be for "wordpress" and this is a custom built site.

Here is my issue. This site had a previous developer, the thing was a mess, and I've spent countless hours cleaning up the site, and he built the sites to show urls like this. "www.sitename.com/about-us.php"

I'm familiar enough with htaccess to know how to remove the trailing extension for .php, even showing trailing variables properly that doesn't require the trailing slash at the end like: "sitename.com/about-us?contact=true"

I was able to get the blog view page to load with a url like this: "sitename.com/posts/post-name-here/". This one though does require the trailing slash.

What I'm trying to accomplish is making the url string to work properly with trailing variables for a few pages like, register, apply, etc. So those urls would be something like this. "sitename.com/auth/apply" or "sitename.com/auth/register"

My issue is that the urls have to have a trailing slash at the end or it doesn't load.

Plus adding a trailing variables only works when formatted like this: "sitename.com/auth/apply/?application=submitted"

I'd prefer it look more like this. "sitename.com/auth/apply?application=submitted", without the trailing slash. But I can't find how to accomplish this.

Here is my .htaccess snippet.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^posts\/(.*)/$ /view-post.php?post=$1 [QSA,NC,L]
RewriteRule ^auth\/(.*)/$ /auth-action.php?action=$1 [QSA,NC,L]
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Can someone help me, or point me in the right direction?

Body:
Try using the following in your .htaccess. This will remove the trailing slash from your URLs.

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=302,L]

Make sure you clear your cache before testing this. You'll notice that I've set R=302 instead of 301. This makes it a temporary redirect for testing purposes. If you're happy with the redirect then change it to 301 to make it permanent.


问:
array_merge in php on a single mutlidimensional array
I got an array here which differs in just one field[4].

Somehow my brains says use 'array_merge' but there is no usable result for me.

Can you please have a look?

```<code>Array
(
    [0] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 4,5
        )

    [1] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 6,7
        )
)
</code>```

Below is what I think should be the output.

```<code>Array
(
    [0] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 4,5,6,7
           )

)
</code>```

答:
You can not merge value by key because it could be anything, still you can merge array recursively by using array_merge_recursive function.

```<code>$ar1 = array(12, 'someclass','1,2,3,4,5,6,7','4,5');
$ar2 = array(12, 'someclass','1,2,3,4,5,6,7','6,7');
$result = array_unique(array_merge_recursive($ar1, $ar2));
print_r($result);
</code>```

Body:
I got an array here which differs in just one field[4].

Somehow my brains says use 'array_merge' but there is no usable result for me.

Can you please have a look?

Array
(
    [0] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 4,5
        )

    [1] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 6,7
        )
)

Below is what I think should be the output.

Array
(
    [0] => Array
        (
            [0] => 12
            [1] => someCssClass
            [2] => AnyText
            [3] => 1,2,3,4,5,6,7
            [4] => 4,5,6,7
           )

)

Body:
You can not merge value by key because it could be anything, still you can merge array recursively by using array_merge_recursive function.

$ar1 = array(12, 'someclass','1,2,3,4,5,6,7','4,5');
$ar2 = array(12, 'someclass','1,2,3,4,5,6,7','6,7');
$result = array_unique(array_merge_recursive($ar1, $ar2));
print_r($result);


问:
How to speed up my code? Python
I need my code to work faster, this one I currently have sometimes even takes up to 5 seconds to print an answer.

```<code>import math

n, k = [int(x) for x in input().split()]
myList = [int(i) for i in input().split()]
range_is = math.factorial(n) / (math.factorial(3) * math.factorial(n-3))
range_is = int(range_is)

answer_list = []
q = 0
w = 1
e = 2

for l in range(range_is):
    o = myList[q]+myList[w]+myList[e]
    answer_list.append(o)
    if e == n-1 and w == n-2  and q != n-3:
        q = q+1
        w = q+1
        e = w+1

    elif e == n-1 and w != n-2:
        w = w+1
        e = w+1

    elif e != n:
        e = e+1

answer_list.sort()
print(answer_list[k-1])
</code>```

How can I make it run faster? And what is the problem in this code, so I can avoid this problem in the future?

答:
What should be written in your question

To summarize:

You have a list of n integers.

You want to calculate every combination of p integers.

You want to calculate the sum of every combination.

You want to sort those sums.

You want the k-th sum.

Code with itertools.combinations

With this description, the code becomes straightforward:

```<code>from itertools import combinations

n = 5
p = 3
k = 4

integers = range(1, n + 1)
triples = combinations(integers, p)
# [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
triple_sums = [sum(t) for t in triples]
# [6, 7, 8, 8, 9, 10, 9, 10, 11, 12]
triple_sums.sort()
# [6, 7, 8, 8, 9, 9, 10, 10, 11, 12]
print(triple_sums[k - 1])
# 8
</code>```

Using itertools.combinations might speed your code up, especially since you don't need to calculate math.factorial(n) for large n.

Most of all, this code is much more concise and shows your intent much better.

Performance

It's unfortunate that triple_sums isn't sorted even if integers are sorted. Every combination needs to be calculated, and the whole list has to be sorted. There might be an alternative way to produce the combinations with which triple_sums would be sorted directly but I cannot think of any.

If your list has 7000 integers, there will be 57142169000 triples. Using itertools won't help much for performance. You'd need to provide more information about the list and k.

Title: How to speed up my code? Python

Body:
I need my code to work faster, this one I currently have sometimes even takes up to 5 seconds to print an answer.

import math

n, k = [int(x) for x in input().split()]
myList = [int(i) for i in input().split()]
range_is = math.factorial(n) / (math.factorial(3) * math.factorial(n-3))
range_is = int(range_is)

answer_list = []
q = 0
w = 1
e = 2

for l in range(range_is):
    o = myList[q]+myList[w]+myList[e]
    answer_list.append(o)
    if e == n-1 and w == n-2  and q != n-3:
        q = q+1
        w = q+1
        e = w+1

    elif e == n-1 and w != n-2:
        w = w+1
        e = w+1

    elif e != n:
        e = e+1

answer_list.sort()
print(answer_list[k-1])

How can I make it run faster? And what is the problem in this code, so I can avoid this problem in the future?

Body:
What should be written in your question

To summarize:

You have a list of n integers.

You want to calculate every combination of p integers.

You want to calculate the sum of every combination.

You want to sort those sums.

You want the k-th sum.

Code with itertools.combinations

With this description, the code becomes straightforward:

from itertools import combinations

n = 5
p = 3
k = 4

integers = range(1, n + 1)
triples = combinations(integers, p)
# [(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
triple_sums = [sum(t) for t in triples]
# [6, 7, 8, 8, 9, 10, 9, 10, 11, 12]
triple_sums.sort()
# [6, 7, 8, 8, 9, 9, 10, 10, 11, 12]
print(triple_sums[k - 1])
# 8

Using itertools.combinations might speed your code up, especially since you don't need to calculate math.factorial(n) for large n.

Most of all, this code is much more concise and shows your intent much better.

Performance

It's unfortunate that triple_sums isn't sorted even if integers are sorted. Every combination needs to be calculated, and the whole list has to be sorted. There might be an alternative way to produce the combinations with which triple_sums would be sorted directly but I cannot think of any.

If your list has 7000 integers, there will be 57142169000 triples. Using itertools won't help much for performance. You'd need to provide more information about the list and k.


问:
Delphi - Open project programmatically in IDE
I would open .dproj files programmatically with embarcadero studio.
I know the path to dproj file and path to bds.exe, how can i do it?</p>

答:
You can open a delphi project from a cmd with the command:
"C:\DelphiInstallation\bin\bds.exe" -pDelphi "C:\Source\YourProjectFile.dproj"

From within Delphi you can use this code:

```<code> ShellExecute(Application.Handle,
  'open',
  PChar('"C:\DelphiInstallation\bin\bds.exe"'),
  PChar('-pDelphi "C:\Source\YourProjectFile.dproj"'),
  nil,
  SW_SHOWNORMAL)
</code>```

Body:
You can open a delphi project from a cmd with the command:
"C:\DelphiInstallation\bin\bds.exe" -pDelphi "C:\Source\YourProjectFile.dproj"

From within Delphi you can use this code:

 ShellExecute(Application.Handle,
  'open',
  PChar('"C:\DelphiInstallation\bin\bds.exe"'),
  PChar('-pDelphi "C:\Source\YourProjectFile.dproj"'),
  nil,
  SW_SHOWNORMAL)


问:
Gulp Uglify problems with $super global in Prototype
I'm trying to use gulp-uglify to compress and uglify all JS files recursively in my directory:

```<code>var gulp = require('gulp');
var uglify = require('gulp-uglify');

gulp.task('compress', function () {
    return gulp.src('js/**/*.js')
        .pipe(uglify({ mangle: {reserved: '$super'}}))
        .pipe(gulp.dest('js_dist'));
});

gulp.task('default', ['compress']);
</code>```

This works okay, but I noticed javascript errors throughout my website. This is because in the Prototype file I can see just one occurrence of $super in quotes on line 138 still remains, but the other 12 occurrences of it have been uglified. I thought that the reserved section would reserve this global, but it doesn't appear to be working. Any ideas?

答:
Weirdly enough, formatting the code like this solved my problem:</p>

```<code>var gulp = require('gulp');
var uglify = require('gulp-uglify');

gulp.task('compress', function () {
    return gulp.src('js/**/*.js')
        .pipe(uglify({
            'mangle': {
                reserved: ['$super']
            }
        }))
        .pipe(gulp.dest('js_dist'));
});

gulp.task('default', ['compress']);
</code>```

Body:
I'm trying to use gulp-uglify to compress and uglify all JS files recursively in my directory:

var gulp = require('gulp');
var uglify = require('gulp-uglify');

gulp.task('compress', function () {
    return gulp.src('js/**/*.js')
        .pipe(uglify({ mangle: {reserved: '$super'}}))
        .pipe(gulp.dest('js_dist'));
});

gulp.task('default', ['compress']);

This works okay, but I noticed javascript errors throughout my website. This is because in the Prototype file I can see just one occurrence of $super in quotes on line 138 still remains, but the other 12 occurrences of it have been uglified. I thought that the reserved section would reserve this global, but it doesn't appear to be working. Any ideas?

Body:
Weirdly enough, formatting the code like this solved my problem:

var gulp = require('gulp');
var uglify = require('gulp-uglify');

gulp.task('compress', function () {
    return gulp.src('js/**/*.js')
        .pipe(uglify({
            'mangle': {
                reserved: ['$super']
            }
        }))
        .pipe(gulp.dest('js_dist'));
});

gulp.task('default', ['compress']);


问:
Excel countif based on subsets
I am trying to count the number of companies we support based on their NAICS code (industry classification code). When a company signs up they provide either their 3,4,5 or 6-digit NAICS code.

For example, let's say I have three companies who joined. One of them provides its six-digit NAICS code 311811 (retail bakeries); another also provides its six-digit code 311812 (Commercial Bakeries); and the last one chooses only to provider its three-digit code 311 (food manufacturing).

In my spreadsheet the list of all the companies who join is in Sheet "RawData" and the NAICS code in Column J. The list of all NAICS codes is on Sheet "List" of my workbook, which is where I would like to return the result of total companies within a NAICS code.

A simple sumif function =COUNTIF(RawData!J:J,List!A1) returns only the count of organizations that joined based on an exact match of the code. In other words I get this:

```<code>Code   Count
311    1
3118   0
31181  0
311811 1
311812 1
</code>```

What I really want to get get is

```<code>Code   Count
311    3
3118   2
31181  2
311811 1
311812 1
</code>```

In the latter table the two companies that selected 311811 and 311812 should be counted in the count for the 311 code and the 3118 and 31181 codes.

答:
Try the following array formula in cell B2 to get the count of 311 if 311 is in cell A2:

```<code>=SUM(IF(ISERROR(SEARCH(A2,J:J)),0,1))
</code>```

Note, that the above is an array formula and needs to be entered as such using Ctrl+Shift+Enter (instead of just pressing Enter). You will see that Excel recoginzes the formula as an array formula by automatically adding curved brackets around the formula like so (do NOT manually enter these curved brackets):

```<code>{=SUM(IF(ISERROR(SEARCH(A2,J:J)),0,1))}
</code>```

Of course the above can be expanded upon by dragging the formula down and adding in column A3 the value 3118 in cell A4 the value 31181 and so on.

Title: Excel countif based on subsets

Body:
I am trying to count the number of companies we support based on their NAICS code (industry classification code). When a company signs up they provide either their 3,4,5 or 6-digit NAICS code.

For example, let's say I have three companies who joined. One of them provides its six-digit NAICS code 311811 (retail bakeries); another also provides its six-digit code 311812 (Commercial Bakeries); and the last one chooses only to provider its three-digit code 311 (food manufacturing).

In my spreadsheet the list of all the companies who join is in Sheet "RawData" and the NAICS code in Column J. The list of all NAICS codes is on Sheet "List" of my workbook, which is where I would like to return the result of total companies within a NAICS code.

A simple sumif function =COUNTIF(RawData!J:J,List!A1) returns only the count of organizations that joined based on an exact match of the code. In other words I get this:

Code   Count
311    1
3118   0
31181  0
311811 1
311812 1

What I really want to get get is

Code   Count
311    3
3118   2
31181  2
311811 1
311812 1

In the latter table the two companies that selected 311811 and 311812 should be counted in the count for the 311 code and the 3118 and 31181 codes.

Body:
Try the following array formula in cell B2 to get the count of 311 if 311 is in cell A2:

=SUM(IF(ISERROR(SEARCH(A2,J:J)),0,1))

Note, that the above is an array formula and needs to be entered as such using Ctrl+Shift+Enter (instead of just pressing Enter). You will see that Excel recoginzes the formula as an array formula by automatically adding curved brackets around the formula like so (do NOT manually enter these curved brackets):

{=SUM(IF(ISERROR(SEARCH(A2,J:J)),0,1))}

Of course the above can be expanded upon by dragging the formula down and adding in column A3 the value 3118 in cell A4 the value 31181 and so on.


问:
How to have different gradle.properties files for release/debug builds?
We need to have gradle.properties files with different configs for release and debug builds, because some of the features we use are experimental and they break some things. Is that possible?

Example of our gradle.properties file

```<code>org.gradle.daemon=true
org.gradle.jvmargs=-Xmx1500m -XX:MaxPermSize=512m
org.gradle.parallel=true
kotlin.incremental=true
android.enableD8=true
</code>```

答:
```<code>buildTypes {
    release {
        shrinkResources true
        minifyEnabled true
        debuggable false
        signingConfig signingConfigs.releaseConfig
    }
    debug1 {
        debuggable true
        signingConfig signingConfigs.debug
    }
    debug2 {
        debuggable true
        signingConfig signingConfigs.debug
    }
}
</code>```

You came different build variants like above and on Android studios select the build variants option(usually in the bottom left corner). select which variant you want to build the apk and run the app.

Body:
We need to have gradle.properties files with different configs for release and debug builds, because some of the features we use are experimental and they break some things. Is that possible?

Example of our gradle.properties file

org.gradle.daemon=true
org.gradle.jvmargs=-Xmx1500m -XX:MaxPermSize=512m
org.gradle.parallel=true
kotlin.incremental=true
android.enableD8=true

Body:
buildTypes {
    release {
        shrinkResources true
        minifyEnabled true
        debuggable false
        signingConfig signingConfigs.releaseConfig
    }
    debug1 {
        debuggable true
        signingConfig signingConfigs.debug
    }
    debug2 {
        debuggable true
        signingConfig signingConfigs.debug
    }
}

You came different build variants like above and on Android studios select the build variants option(usually in the bottom left corner). select which variant you want to build the apk and run the app.


问:
ASCII files, how to deal with separator in quoted string?
I have an ASCII file (csv, for instance) that uses , as separator, however this char is also present in quoted strings:

```<code>3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3
</code>```

To avoid such ambiguity I want to replace the , separator by the ; one. How to do that with command line? (under linux).

UPDATE/extra question:

There are at least two options using sed or awk.

My extra question is which one is the fastest? (this can be important for big csv files).

答:
I think your requirement is the perfect use case for using FPAT in GNU Awk,

Normally, when using FS, gawk defines the fields as the parts of the record that occur in between each field separator. In other words, FS defines what a field is not, instead of what a field is. However, there are times when you really want to define the fields by what they are, and not by what they are not.

The most notorious such case is so-called comma-separated values (CSV) data.  If commas only separated the data, there wouldn’t be an issue. The problem comes when one of the fields contains an embedded comma. In such cases, most programs embed the field in double quotes.

In the case of CSV data as presented here, each field is either “anything that is not a comma,” or “a double quote, anything that is not a double quote, and a closing double quote.” If written as a regular expression constant (see Regexp), we would have ([^,]+)|([[:space:]]*\"[^\"]+\"). Writing this as a string requires us to escape the double quotes, leading to:

```<code>FPAT = "([^,]+)|([[:space:]]*\"[^\"]+\")"
</code>```

Using that on your file to output de-limit file on ; character do

```<code>awk -v OFS=';' 'BEGIN{FPAT = "([^,]+)|([[:space:]]*\"[^\"]+\")"}{$1=$1}1' file
</code>```

Also you could speed-things up by playing with the locale set in your system. Forcing the locale settings to C will let you match the characters to the ASCII data set alone and not UTF-8, pass it locally to the command as

```<code>LC_ALL=C awk -v OFS=';' 'BEGIN{FPAT = "([^,]+)|([[:space:]]*\"[^\"]+\")"}{$1=$1}1' file
</code>```

Since FPAT involves using standard regex parsers, it could perform slower than the ones involving non-regex substitutions.

Body:
I have an ASCII file (csv, for instance) that uses , as separator, however this char is also present in quoted strings:

3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3

To avoid such ambiguity I want to replace the , separator by the ; one. How to do that with command line? (under linux).

UPDATE/extra question:

There are at least two options using sed or awk.

My extra question is which one is the fastest? (this can be important for big csv files).

Body:
I think your requirement is the perfect use case for using FPAT in GNU Awk,

Normally, when using FS, gawk defines the fields as the parts of the record that occur in between each field separator. In other words, FS defines what a field is not, instead of what a field is. However, there are times when you really want to define the fields by what they are, and not by what they are not.

The most notorious such case is so-called comma-separated values (CSV) data.  If commas only separated the data, there wouldn’t be an issue. The problem comes when one of the fields contains an embedded comma. In such cases, most programs embed the field in double quotes.

In the case of CSV data as presented here, each field is either “anything that is not a comma,” or “a double quote, anything that is not a double quote, and a closing double quote.” If written as a regular expression constant (see Regexp), we would have ([^,]+)|([[:space:]]*\"[^\"]+\"). Writing this as a string requires us to escape the double quotes, leading to:

FPAT = "([^,]+)|([[:space:]]*\"[^\"]+\")"

Using that on your file to output de-limit file on ; character do

awk -v OFS=';' 'BEGIN{FPAT = "([^,]+)|([[:space:]]*\"[^\"]+\")"}{$1=$1}1' file

Also you could speed-things up by playing with the locale set in your system. Forcing the locale settings to C will let you match the characters to the ASCII data set alone and not UTF-8, pass it locally to the command as

LC_ALL=C awk -v OFS=';' 'BEGIN{FPAT = "([^,]+)|([[:space:]]*\"[^\"]+\")"}{$1=$1}1' file

Since FPAT involves using standard regex parsers, it could perform slower than the ones involving non-regex substitutions.


问:
MPAndroidChart fading lines on line chart (step) when last two entries are close
I have a simple line chart class that extends com.github.mikephil.charting.charts.LineChart with x-axis recording time (0-24) and Y-axis values from 1-4.

The first entry in the dataset will always have an x-value of 0 (carry over from previous day). When my last two entries are close together on the x-axis ( less than 1), the line on the graph fades near points and step. I have tried this on two devices, it is faulting on one (android api 17) and not the other (andorid api 18).

This issue disappears when the gap between the last two values increases or when I zoom in on the graph ~ (x100).

Dataset is configured as follows:

```<code>dataSet.setColor(-16222537);
dataSet.setDrawCircles(false);
dataSet.setDrawValues(false);
dataSet.setMode(LineDataSet.Mode.STEPPED);
dataSet.setDrawHighlightIndicators(false);
dataSet.setLineWidth(3);
</code>```

The set of values I am plotting are

(0, 1.0)

(9.58333, 4.0)

(9.73042, 4.0)

Screenshot of chart with fading lines:

答:
chart.setHardwareAccelerationEnabled(false);

This should to the trick.

I've also noticed this on my Android 4.1 device.
Higher versions do not seem to have this issue, although I'm not sure from which version on.

Body:
I have a simple line chart class that extends com.github.mikephil.charting.charts.LineChart with x-axis recording time (0-24) and Y-axis values from 1-4.

The first entry in the dataset will always have an x-value of 0 (carry over from previous day). When my last two entries are close together on the x-axis ( less than 1), the line on the graph fades near points and step. I have tried this on two devices, it is faulting on one (android api 17) and not the other (andorid api 18).

This issue disappears when the gap between the last two values increases or when I zoom in on the graph ~ (x100).

Dataset is configured as follows:

dataSet.setColor(-16222537);
dataSet.setDrawCircles(false);
dataSet.setDrawValues(false);
dataSet.setMode(LineDataSet.Mode.STEPPED);
dataSet.setDrawHighlightIndicators(false);
dataSet.setLineWidth(3);

The set of values I am plotting are

(0, 1.0)

(9.58333, 4.0)

(9.73042, 4.0)

Screenshot of chart with fading lines:


问:
Docker - Which environment is actually running on Windows 7?
I’m new to docker, started to learn about it but I’m a little confused.

I need to run app on windows environment.

I have Windows 7 – native Docker is only for Windows 10, so I need to download the Docker toolbox for Windows 7.

The toolbox is actually using a Linux VM to run it.

So, in this state I will actually create a container with windows environment or Linux environment?

Is the Docker for windows 10 also uses Linux?

Thanks

答:
Containers are not VMs, they rely on the host OS and this means you can't run directly:

a windows container on linux

a linux container on windows

without using some kind of virtualization that will provide the layer needed for each case. For example, Docker toolbox for Windows makes use of Oracle VM VirtualBox, in order to run linux containers.

more about Windows containers:

Windows Container Types

Windows Containers include two different container types, or runtimes.

Windows Server Containers – provide application isolation through process and namespace isolation technology. A Windows Server Container shares a kernel with the container host and all containers running on the host. These containers do not provide a hostile security boundary and should not be used to isolate untrusted code. Because of the shared kernel space, these containers require the same kernel version and configuration.

Hyper-V Isolation – expands on the isolation provided by Windows Server Containers by running each container in a highly optimized virtual machine. In this configuration, the kernel of the container host is not shared with other containers on the same host. These containers are designed for hostile multitenant hosting with the same security assurances of a virtual machine. Since these containers do not share the kernel with the host or other containers on the host, they can run kernels with different versions and configurations (with in supported versions) - for example all Windows containers on Windows 10 use Hyper-V isolation to utilize the Windows Server kernel version and configuration.

Running a container on Windows with or without Hyper-V Isolation is a runtime decision. You may elect to create the container with Hyper-V isolation initially and later at runtime choose to run it instead as a Windows Server container.

Further reading:

Linux machine with docker deploy windows container

Can Windows Containers be hosted on linux?

Can I run windows containers using docker-toolbox on windows 7?


问:
Join arrays expression in ECMAScript 2016
I am new to JavaScript. I need to write simple script which should join several arrays into one. I found this example:

```<code>var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);
</code>```

But I have more than two arrays.
Is it possible to concat several arrays in one expression?

答:
```<code>var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];
var arr3 = ['g', 'h', 'i'];
var arr4 = ['j', 'k', 'l'];

var arr5 = Array.prototype.concat.apply(arr1, [arr2, arr3, arr4]);
console.log(arr5);
</code>```

By this means you can concat n number of arrays. Just add more arrays after arr4.

If you have array of arrays, Something like this,

```<code> var arr1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]
</code>```

You can use spread,

```<code>var arr2 = Array.prototype.concat(...arr1);
console.log(arr2);
</code>```

Body:
I am new to JavaScript. I need to write simple script which should join several arrays into one. I found this example:

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];

var arr3 = arr1.concat(arr2);

But I have more than two arrays.
Is it possible to concat several arrays in one expression?

Body:
var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', 'f'];
var arr3 = ['g', 'h', 'i'];
var arr4 = ['j', 'k', 'l'];

var arr5 = Array.prototype.concat.apply(arr1, [arr2, arr3, arr4]);
console.log(arr5);

By this means you can concat n number of arrays. Just add more arrays after arr4.

If you have array of arrays, Something like this,

 var arr1 = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']]

You can use spread,

var arr2 = Array.prototype.concat(...arr1);
console.log(arr2);


问:
Webpack writes the absolute path info in bundle when Babel-loader is used
Here is a piece of my webpack config file:
`

// webpack.config.js
  entry: path.resolve(__dirname, 'src/app.js'),
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist/js/'),
    library: 'app',
    publicPath: '/js/',
    pathinfo: NODE_ENV === 'development',
  },
  //...
    module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel',
          },
          {
            loader: 'eslint',
          },
        ],
      },
      //...
    ],
  },

 // .babelrc
 {
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": [
            "last 1 Chrome versions",
            "last 1 Firefox versions",
            "last 1 Edge versions",
            "last 1 iOS versions"
          ]
        },
        "modules": false
      }
    ]
  ],
  "plugins": [
    ["istanbul", {
      "exclude": [
        "./test/unit/**/*.js"
      ]
    }]
  ]
}```

The Problem: I get the full local path to my js file like this:
path: '/Users/username/MyProjects/projectname/src/view/dialog/Messages.js.
Which don't like to have in my production bundle.

I get this only using babel-loader for js files.

I use "webpack": "3.8.1".

Please help!

答:
The problem resolved.
The reason was Istanbul Babel plugin.
The solution is to use 'test' variable and use Istanbul in test mode only:

```<code>// .babelrc
</code>```

{
  "presets": [
    [
     // ...
  ],
  "env": {
    "test": {
      "plugins": [
        ["istanbul", {
          "exclude": [
            "./test/unit/**/*.js"
          ]
        }]
      ]
    }
  }
}```

Body:
Here is a piece of my webpack config file:
`

// webpack.config.js
  entry: path.resolve(__dirname, 'src/app.js'),
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist/js/'),
    library: 'app',
    publicPath: '/js/',
    pathinfo: NODE_ENV === 'development',
  },
  //...
    module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: [
          {
            loader: 'babel',
          },
          {
            loader: 'eslint',
          },
        ],
      },
      //...
    ],
  },

 // .babelrc
 {
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": [
            "last 1 Chrome versions",
            "last 1 Firefox versions",
            "last 1 Edge versions",
            "last 1 iOS versions"
          ]
        },
        "modules": false
      }
    ]
  ],
  "plugins": [
    ["istanbul", {
      "exclude": [
        "./test/unit/**/*.js"
      ]
    }]
  ]
}

The Problem: I get the full local path to my js file like this:
path: '/Users/username/MyProjects/projectname/src/view/dialog/Messages.js.
Which don't like to have in my production bundle.

I get this only using babel-loader for js files.

I use "webpack": "3.8.1".

Please help!

Body:
The problem resolved.
The reason was Istanbul Babel plugin.
The solution is to use 'test' variable and use Istanbul in test mode only:

// .babelrc

{
  "presets": [
    [
     // ...
  ],
  "env": {
    "test": {
      "plugins": [
        ["istanbul", {
          "exclude": [
            "./test/unit/**/*.js"
          ]
        }]
      ]
    }
  }
}


问:
Redirection issue with wordpress blog directory URL's
My blog is hosted at blog.example.com. I have a reverse proxy set up on my primary site such that request to www.example.com/blog will be served from blog.example.com.

request https://www.example.com/blog/wp-login.php is working properly, but all the wp-admin and wp-content URL are getting redirected without "blog" in the URL.

Example:

Requests to https://www.example.com/blog/wp-admin/plugins.php redirects to https://www.example.com/wp-admin/plugins.php.

Kindly guide me in resolving the issue.

.htaccess

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>
</code>```

答:
Open phpmyadmin

Check wp_options table

update option_name

```<code>siteurl => https://www.example.com/blog/

home =>  https://www.example.com/blog/
</code>```

Body:
My blog is hosted at blog.example.com. I have a reverse proxy set up on my primary site such that request to www.example.com/blog will be served from blog.example.com.

request https://www.example.com/blog/wp-login.php is working properly, but all the wp-admin and wp-content URL are getting redirected without "blog" in the URL.

Example:

Requests to https://www.example.com/blog/wp-admin/plugins.php redirects to https://www.example.com/wp-admin/plugins.php.

Kindly guide me in resolving the issue.

.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog/index.php [L]
</IfModule>

Body:
Open phpmyadmin

Check wp_options table

update option_name

siteurl => https://www.example.com/blog/

home =>  https://www.example.com/blog/


问:
Checking for HTTPS Website Response Code
to begin with - I am new at this page, just created my account because I couldn't handle the problem I am up to.

I am trying to get a response code from the website - what actually interest me is if the page I am checking exists so I am looking for 404 error. I did it like this:

```<code>public static void main(String[] args) throws IOException {
    URL url = new URL("https://bittrex.com/dffdgdfgdfgdfgfdgdf");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    int responseCode = con.getResponseCode();
    System.out.println(responseCode);

}
</code>```

The URL does not exists but it keeps giving me 403 (Forbidden Access) or 503 (Service Unavailable) response code yet the site is obviously 404ed. I read somewhere that its because of HTTPS protocole and setRequestProperty to pretend being a browser would help but it didn't.

Is there anyway I could fix this so that the site returns 404 error to me? I appreciate help in advance!

答:
It depends on website response. Hit your link https://bittrex.com/dffdgdfgdfgdfgfdgdf in any browser, it will give you 404. That is the reason you are getting 404.

Below Code give you 200 response code :

```<code>URL url = new URL("https://google.com");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    int responseCode = con.getResponseCode();
    System.out.println(responseCode);
</code>```

Body:
to begin with - I am new at this page, just created my account because I couldn't handle the problem I am up to.

I am trying to get a response code from the website - what actually interest me is if the page I am checking exists so I am looking for 404 error. I did it like this:

public static void main(String[] args) throws IOException {
    URL url = new URL("https://bittrex.com/dffdgdfgdfgdfgfdgdf");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    int responseCode = con.getResponseCode();
    System.out.println(responseCode);

}

The URL does not exists but it keeps giving me 403 (Forbidden Access) or 503 (Service Unavailable) response code yet the site is obviously 404ed. I read somewhere that its because of HTTPS protocole and setRequestProperty to pretend being a browser would help but it didn't.

Is there anyway I could fix this so that the site returns 404 error to me? I appreciate help in advance!

Body:
It depends on website response. Hit your link https://bittrex.com/dffdgdfgdfgdfgfdgdf in any browser, it will give you 404. That is the reason you are getting 404.

Below Code give you 200 response code :

URL url = new URL("https://google.com");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
    int responseCode = con.getResponseCode();
    System.out.println(responseCode);


问:
Python slicing - Skips certain number of rows
I currently have 500 rows of data. I want to use the first fifty rows, then skip 50 rows and so on. How do I go on about doing this?</p>

答:
The slice notation is list[start:end], in your case you can use a xrange with a step of 100 (50*2) and then take only the 50 first rows to do your task :

```<code>rows = [x for x in xrange(0, 500)]

for x in xrange(0, len(rows), 100):
    print repr(rows[x:x+50]) # Do stuff here (iterate again if necessary)
</code>```

out

```<code>[0, 1, 2, 3, ... 48, 49]
[100, 101, 102, 103, ... 148, 149] ...
</code>```

Body:
The slice notation is list[start:end], in your case you can use a xrange with a step of 100 (50*2) and then take only the 50 first rows to do your task :

rows = [x for x in xrange(0, 500)]

for x in xrange(0, len(rows), 100):
    print repr(rows[x:x+50]) # Do stuff here (iterate again if necessary)

out

[0, 1, 2, 3, ... 48, 49]
[100, 101, 102, 103, ... 148, 149] ...


问:
Beego range in view templates
I have an integer having value 5 and i want to loop against it and populate a dropdown as following using range or for loop in html. can any one help me how to do that</p>

```<code><a class="dropdown-item" href="#">1</a>
<a class="dropdown-item" href="#">2</a>
<a class="dropdown-item" href="#">3</a>
<a class="dropdown-item" href="#">4</a>
<a class="dropdown-item" href="#">5</a>
</code>```

答:
You first need something you can range over, like an array, slice, map, or a channel.

For example in your Go code create a slice of ints ([]int) and assign it to the template data.

```<code>items := []int{1, 2, 3, 4, 5}
this.Data["items"] = items
</code>```

Now inside the template you can range over items like so:

```<code>{{range $val := .items}}
<a class="dropdown-item" href="#">{{$val}}</a>
{{end}}
</code>```

```<code>func numSequence(num int) []int {
    out := make([]int, num) // create slice of length equal to num

    for i := range out {
        out[i] = i + 1
    }
    return out
}

fmt.Println(numSequence(5))
// Output: [1, 2, 3, 4, 5]

fmt.Println(numSequence(7))
// Output: [1, 2, 3, 4, 5, 6, 7]
</code>```

Executable example on Go playgound.

Please note: since playground doesn't support importing of 3rd party packages the example executes the template using the html/template package instead of using the beego framework, but this is ok because beego uses html/template under the hood. Also the hyphen in the example template (-}}) gets rid of whitespace up to the next token, you don't have to use it if you don't want to.

Title: Beego range in view templates

Body:
I have an integer having value 5 and i want to loop against it and populate a dropdown as following using range or for loop in html. can any one help me how to do that

1
2
3
4
5

Body:
You first need something you can range over, like an array, slice, map, or a channel.

For example in your Go code create a slice of ints ([]int) and assign it to the template data.

items := []int{1, 2, 3, 4, 5}
this.Data["items"] = items

Now inside the template you can range over items like so:

{{range $val := .items}}
<a class="dropdown-item" href="#">{{$val}}</a>
{{end}}

func numSequence(num int) []int {
    out := make([]int, num) // create slice of length equal to num

    for i := range out {
        out[i] = i + 1
    }
    return out
}

fmt.Println(numSequence(5))
// Output: [1, 2, 3, 4, 5]

fmt.Println(numSequence(7))
// Output: [1, 2, 3, 4, 5, 6, 7]

Executable example on Go playgound.

Please note: since playground doesn't support importing of 3rd party packages the example executes the template using the html/template package instead of using the beego framework, but this is ok because beego uses html/template under the hood. Also the hyphen in the example template (-}}) gets rid of whitespace up to the next token, you don't have to use it if you don't want to.


问:
Check if two products are in same order in Woocommerce email notifications
I am trying to add additional text to email for completed order if order contains two specfic product IDs. Here is my code so far:

```<code>function advmi_check_order_product_id($order_id)
{
    $order = new WC_Order($order_id);
    $items = $order->get_items();
    foreach($items as $item) {
        $product_id = $item['product_id'];
        if (($product_id == 56943 && $product_id == 95956 && 'completed' == $order->status )) {
            echo '<p>Added Text for both products in the order</p><p>Text </p>';
        }
        elseif ($product_id == 56943 && 'completed' == $order->status) {
            echo '<p>Text for only 56943 </p><p>Text </p>';
}
        }
</code>```

I also need the order status to be completed.

I am stuck - Any help on this please?

I am using WC Version: 2.6.14

答:
This will add some text before the order table on completed order emails.  I looped through the order items and set flags based on if those items are included in the order.</p>

```<code>add_action( 'woocommerce_email_before_order_table', 'add_additonal_order_email_text', 10, 4 );
function add_additonal_order_email_text( $order, $sent_to_admin, $plain_text, $email ) {
    $product_id_1 = 56943;
    $product_id_2 = 95956;
    $product_1_exists = false;
    $product_2_exists = false;

    if ( ! $sent_to_admin && 'completed' == $order->get_status() ) {
        foreach( $order->get_items() as $order_item ) {
            $product_id = $order_item->get_product_id();

            if( $product_id == $product_id_1 )
                $product_1_exists = true;
            elseif( $product_id == $product_id_2 )
                $product_2_exists = true;
        }

        if ( $product_1_exists && $product_2_exists ) {
            echo '<p>Added Text for both products in the order</p><p>Text </p>';
        }
        elseif ( $product_1_exists && ! product_2_exists ) {
            echo '<p>Text for only 56943 </p><p>Text </p>';
        }
    }
}
</code>```

Body:
I am trying to add additional text to email for completed order if order contains two specfic product IDs. Here is my code so far:

function advmi_check_order_product_id($order_id)
{
    $order = new WC_Order($order_id);
    $items = $order->get_items();
    foreach($items as $item) {
        $product_id = $item['product_id'];
        if (($product_id == 56943 && $product_id == 95956 && 'completed' == $order->status )) {
            echo '
Added Text for both products in the order

Text
';
        }
        elseif ($product_id == 56943 && 'completed' == $order->status) {
            echo '
Text for only 56943

Text
';
}
        }

I also need the order status to be completed.

I am stuck - Any help on this please?

I am using WC Version: 2.6.14

Body:
This will add some text before the order table on completed order emails.  I looped through the order items and set flags based on if those items are included in the order.

add_action( 'woocommerce_email_before_order_table', 'add_additonal_order_email_text', 10, 4 );
function add_additonal_order_email_text( $order, $sent_to_admin, $plain_text, $email ) {
    $product_id_1 = 56943;
    $product_id_2 = 95956;
    $product_1_exists = false;
    $product_2_exists = false;

    if ( ! $sent_to_admin && 'completed' == $order->get_status() ) {
        foreach( $order->get_items() as $order_item ) {
            $product_id = $order_item->get_product_id();

            if( $product_id == $product_id_1 )
                $product_1_exists = true;
            elseif( $product_id == $product_id_2 )
                $product_2_exists = true;
        }

        if ( $product_1_exists && $product_2_exists ) {
            echo '<p>Added Text for both products in the order</p><p>Text </p>';
        }
        elseif ( $product_1_exists && ! product_2_exists ) {
            echo '<p>Text for only 56943 </p><p>Text </p>';
        }
    }
}


问:
spark application from kafka stream takes long time to produce recommendation
I am reading stream of data in my spark application from kafka stream. My requirement is to produce product recommendation for a user when he makes any request (search/browse etc.)

I already have a trained model containing score of users. I am using Java and org.apache.spark.mllib.recommendation.MatrixFactorizationModel model to read the model once at start of my spark application. Whenever there is any browsing event, I call recommendProducts(user_id, num_of_recommended_products) API to produce recommendation for a user from my already existing trained model.

This API is taking ~3-5 seconds for generating result per user which is very slow and hence my stream processing lags behind. Are there any ways in which I can optimise the time of this API? I am considering increasing stream duration from 15 seconds to 1 minute as an optimisation (not sure of its results now)

答:
Calling recommendProducts in real time, doesn't make much sense. Since ALS model can make predictions only for users, which has been seen in the training dataset, it is better to recommendProductsForUser once, store the output in a store which supports first lookups by key and fetch results from there, when needed.

If adding storage layer is not an option, you can also take output of recommendProductsForUser, partition by id, checkpoint and cache predictions, and then join with input stream by id.


问:
Can't we upload a mp3 file to Office 365 video channel/ Stream app?
I tired to upload an mp3 file in Office 365 video/stream but getting error message like file format is not supported.

But when checked the support file link - Audio codec supported contains .mp3 file for Office 365 video. Why it is not allowing me to upload an mp3 file?

答:
Audio codec is not the same thing as the file format. For example you can have a video file encoded with video codec H.264 and audio codec of MP3 with file format .mp4.
Microsoft Stream (aka Office 365 Video) only supports formats listed in Supported video file formats section. In fact mp3 is not a video file format.

The solution might be to change file extension from mp3 to mp4. Then you should be able to upload the file to Microsoft Stream service.

Here you can read more about the differences between codecs and formats.


问:
Python can't encode with surrogateescape
I have a problem with Unicode surrogates encoding in Python (3.4):

```<code>>>> b'\xCC'.decode('utf-16_be', 'surrogateescape').encode('utf-16_be', 'surrogateescape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'utf-16-be' codec can't encode character '\udccc' in position 0: surrogates not allowed
</code>```

If I'm not mistaken, according to Python documentation:

'surrogateescape': On decoding, replace byte with individual surrogate
  code ranging from U+DC80 to U+DCFF. This code will then be turned back
  into the same byte when the 'surrogateescape' error handler is used
  when encoding the data.

The code should just produce the source sequence (b'\xCC'). So why is the exception raised instead?

This is possibly related to my second question:

Changed in version 3.4: The utf-16* and utf-32* encoders no longer allow surrogate code points (U+D800–U+DFFF) to be encoded.

(From https://docs.python.org/3/library/codecs.html#standard-encodings)

From as far as I know, it's impossible to encode some code points to UTF-16 without surrogate pairs. So what's the reason behind this?

答:
If you use surrogatepass (instead of surrogateescape), things should work on Python 3.

See: https://docs.python.org/3/library/codecs.html#codec-base-classes (which says that surrogatepass allows encoding and decoding of surrogate codes (for utf related encoding).

Body:
I have a problem with Unicode surrogates encoding in Python (3.4):

>>> b'\xCC'.decode('utf-16_be', 'surrogateescape').encode('utf-16_be', 'surrogateescape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'utf-16-be' codec can't encode character '\udccc' in position 0: surrogates not allowed

If I'm not mistaken, according to Python documentation:

'surrogateescape': On decoding, replace byte with individual surrogate
  code ranging from U+DC80 to U+DCFF. This code will then be turned back
  into the same byte when the 'surrogateescape' error handler is used
  when encoding the data.

The code should just produce the source sequence (b'\xCC'). So why is the exception raised instead?

This is possibly related to my second question:

Changed in version 3.4: The utf-16* and utf-32* encoders no longer allow surrogate code points (U+D800–U+DFFF) to be encoded.

(From https://docs.python.org/3/library/codecs.html#standard-encodings)

From as far as I know, it's impossible to encode some code points to UTF-16 without surrogate pairs. So what's the reason behind this?


问:
How to set Recyclerview to show only 4 tiles
So, ive implemented a RecyclerView which has 15 items, now what I want to do is to restrict the RecyclerView to 4 items when I click a button and vice versa, i'm not sure how to do that, this is what I have done, any inputs would be helpful

```<code>floatingButton.Click += delegate {
            if (clicked)
            {
                Toast.MakeText(this, "Has been clicked before", ToastLength.Short).Show();
                recyclerview_layoutmanger = new GridLayoutManager(this,, 2);
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = false;
            }
            else {
                recyclerview_layoutmanger = new LinearLayoutManager(this, LinearLayoutManager.Vertical, false);
                Toast.MakeText(this, "Has not been clicked before", ToastLength.Short).Show();
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = true;
            }
        };
</code>```

Adapter Class

```<code>  public class RecyclerAdapter : RecyclerView.Adapter
    {
        public event EventHandler<int> ItemClick;

        private readonly List<MessageList> messages;

        public RecyclerAdapter(List<MessageList> messages)
        {
            this.messages = messages;
            NotifyDataSetChanged();
        }

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            var movieViewHolder = (MessageViewHolder)holder;
            movieViewHolder.messageView.Text = messages[position].Message;
            movieViewHolder.dateView.Text = messages[position].messageDate;
            // movieViewHolder.MovieImageView.SetImageResource(Resource.Drawable.starwarslogo);
        }

        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var layout = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.messages_list_layout, parent, false);

            return new MessageViewHolder(layout, OnItemClick);

        }

        public override int ItemCount
        {
            get { return messages.Count; }
        }

        void OnItemClick(int position)
        {
            if (ItemClick != null)
                ItemClick(this, position);
        }
    }

        /// <summary>
        /// Called after <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c>, <c><see cref="M:Android.App.Activity.OnRestart" /></c>, or
        /// <c><see cref="M:Android.App.Activity.OnPause" /></c>, for your activity to start interacting with the user.
        /// </summary>
        protected override void OnResume()
    {
        var toggle = new ActionBarDrawerToggle(this, this.DrawerLayout, this.AppToolbar, 0, 0);
        this.DrawerLayout.AddDrawerListener(toggle);
        toggle.SyncState();

        base.OnResume();
    }
</code>```

But this just changes the layout to a side by side kinda thing

答: Simple solution is to limit your arraylist to size 4 then inflate it in recycler view rather than doing changes in recycler view. </p>

Body:
So, ive implemented a RecyclerView which has 15 items, now what I want to do is to restrict the RecyclerView to 4 items when I click a button and vice versa, i'm not sure how to do that, this is what I have done, any inputs would be helpful

floatingButton.Click += delegate {
            if (clicked)
            {
                Toast.MakeText(this, "Has been clicked before", ToastLength.Short).Show();
                recyclerview_layoutmanger = new GridLayoutManager(this,, 2);
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = false;
            }
            else {
                recyclerview_layoutmanger = new LinearLayoutManager(this, LinearLayoutManager.Vertical, false);
                Toast.MakeText(this, "Has not been clicked before", ToastLength.Short).Show();
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = true;
            }
        };

Adapter Class

  public class RecyclerAdapter : RecyclerView.Adapter
    {
        public event EventHandler<int> ItemClick;

        private readonly List<MessageList> messages;

        public RecyclerAdapter(List<MessageList> messages)
        {
            this.messages = messages;
            NotifyDataSetChanged();
        }

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            var movieViewHolder = (MessageViewHolder)holder;
            movieViewHolder.messageView.Text = messages[position].Message;
            movieViewHolder.dateView.Text = messages[position].messageDate;
            // movieViewHolder.MovieImageView.SetImageResource(Resource.Drawable.starwarslogo);
        }

        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var layout = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.messages_list_layout, parent, false);

            return new MessageViewHolder(layout, OnItemClick);

        }

        public override int ItemCount
        {
            get { return messages.Count; }
        }

        void OnItemClick(int position)
        {
            if (ItemClick != null)
                ItemClick(this, position);
        }
    }

        ///
        /// Called after <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c>, <c><see cref="M:Android.App.Activity.OnRestart" /></c>, or
        /// <c><see cref="M:Android.App.Activity.OnPause" /></c>, for your activity to start interacting with the user.
        ///
        protected override void OnResume()
    {
        var toggle = new ActionBarDrawerToggle(this, this.DrawerLayout, this.AppToolbar, 0, 0);
        this.DrawerLayout.AddDrawerListener(toggle);
        toggle.SyncState();

        base.OnResume();
    }

But this just changes the layout to a side by side kinda thing