问:
Stretching element to contain all children
How is it possible in QML to automatically stretch element so that all its childs fit in it? And how to specify spacing? For example, I would like to have a rectangle around a text. The rectangle should have some internal spacing.

If I write the following then the rectangle has a size of 0,0.

```<code>Rectangle {
    color: "gray"
    anchors.centerIn: parent;

    Text {
        text: "Hello"
    }
}
</code>```

If I try to fix it by using the Column element, as suggested in How to make QML items to grow to fit contents?, then I get a column through the whole window/parent,

```<code>Column {
    anchors.centerIn: parent

    Rectangle {
        color: "gray"
        anchors.fill: parent
    }

    Text {
        anchors.centerIn: parent
        text: "Hello"
    }
}
</code>```

Edit:

I have also tried to use the Flow element instead of Column, but then I got a row through the whole window/parent.

答:
Setting the width and height manually works, but is a little ugly:

```<code>Rectangle {
    color: "gray"
    width: label.width+20
    height: label.height+20
    anchors.centerIn: parent

    Text {
        id: label
        anchors.centerIn: parent
        text: "Hello"
    }
}
</code>```

Body:
How is it possible in QML to automatically stretch element so that all its childs fit in it? And how to specify spacing? For example, I would like to have a rectangle around a text. The rectangle should have some internal spacing.

If I write the following then the rectangle has a size of 0,0.

Rectangle {
    color: "gray"
    anchors.centerIn: parent;

    Text {
        text: "Hello"
    }
}

If I try to fix it by using the Column element, as suggested in How to make QML items to grow to fit contents?, then I get a column through the whole window/parent,

Column {
    anchors.centerIn: parent

    Rectangle {
        color: "gray"
        anchors.fill: parent
    }

    Text {
        anchors.centerIn: parent
        text: "Hello"
    }
}

Edit:

I have also tried to use the Flow element instead of Column, but then I got a row through the whole window/parent.

Body:
Setting the width and height manually works, but is a little ugly:

Rectangle {
    color: "gray"
    width: label.width+20
    height: label.height+20
    anchors.centerIn: parent

    Text {
        id: label
        anchors.centerIn: parent
        text: "Hello"
    }
}


来源: stackexchange

问:
Detox tests: SyntaxError: Missing initializer in const declaration
I am pretty new to React Native and Detox and facing some issue debugging the root cause of this issue.

Basically for our test environment we first run our docker using
npm run e2e -- --docker start

e2e script is defined in package.json as
"e2e": "ts-node e2e/runner.ts",

The error that I get is:

@cb/mobile@0.0.1 e2e /Users/rishabhharit/Documents/GitHub/clearbook/packages/cb-mobile
ts-node e2e/runner.ts "--docker" "start"

/Users/rishabhharit/Documents/GitHub/clearbook/packages/cb-mobile/node_modules/react-native/Libraries/Utilities/warnOnce.js:15
const warnedKeys: {[string]: boolean} = {};
      ^^^^^^^^^^

SyntaxError: Missing initializer in const declaration
    at wrapSafe (internal/modules/cjs/loader.js:891:16)
    at Module._compile (internal/modules/cjs/loader.js:941:27)
    at Module._extensions..js (internal/modules/cjs/loader.js:1011:10)
    at Object.require.extensions.<computed> [as .js] (/Users/rishabhharit/Documents/GitHub/clearbook/packages/cb-mobile/node_modules/ts-node/src/index.ts:807:44)
    at Module.load (internal/modules/cjs/loader.js:822:32)
    at Function.Module._load (internal/modules/cjs/loader.js:730:14)
    at Module.require (internal/modules/cjs/loader.js:864:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/Users/rishabhharit/Documents/GitHub/clearbook/packages/cb-mobile/node_modules/react-native/Libraries/react-native/react-native-implementation.js:14:18)
    at Module._compile (internal/modules/cjs/loader.js:971:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @cb/mobile@0.0.1 e2e: `ts-node e2e/runner.ts "--docker" "start"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @cb/mobile@0.0.1 e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/rishabhharit/.npm/_logs/2020-05-07T08_58_41_483Z-debug.log

[2020-05-07T08_58_41_483Z-debug.log](https://github.com/wix/Detox/files/4591898/2020-05-07T08_58_41_483Z-debug.log)
```

runner.ts.zip

Now I am unsure where to look at. Will provide more info as per request.

答:
This answer helped me https://stackoverflow.com/a/57254546.
Just add this line to the e2e/config.json:

```<code>"preset": "react-native"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am pretty new to React Native and Detox and facing some issue debugging the root cause of this issue.

Basically for our test environment we first run our docker using
npm run e2e -- --docker start

e2e script is defined in package.json as
"e2e": "ts-node e2e/runner.ts",

The error that I get is:

@cb/mobile@0.0.1 e2e /Users/rishabhharit/Documents/GitHub/clearbook/packages/cb-mobile
ts-node e2e/runner.ts "--docker" "start"

/Users/rishabhharit/Documents/GitHub/clearbook/packages/cb-mobile/node_modules/react-native/Libraries/Utilities/warnOnce.js:15
const warnedKeys: {[string]: boolean} = {};
      ^^^^^^^^^^

SyntaxError: Missing initializer in const declaration
    at wrapSafe (internal/modules/cjs/loader.js:891:16)
    at Module._compile (internal/modules/cjs/loader.js:941:27)
    at Module._extensions..js (internal/modules/cjs/loader.js:1011:10)
    at Object.require.extensions.<computed> [as .js] (/Users/rishabhharit/Documents/GitHub/clearbook/packages/cb-mobile/node_modules/ts-node/src/index.ts:807:44)
    at Module.load (internal/modules/cjs/loader.js:822:32)
    at Function.Module._load (internal/modules/cjs/loader.js:730:14)
    at Module.require (internal/modules/cjs/loader.js:864:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/Users/rishabhharit/Documents/GitHub/clearbook/packages/cb-mobile/node_modules/react-native/Libraries/react-native/react-native-implementation.js:14:18)
    at Module._compile (internal/modules/cjs/loader.js:971:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @cb/mobile@0.0.1 e2e: `ts-node e2e/runner.ts "--docker" "start"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @cb/mobile@0.0.1 e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/rishabhharit/.npm/_logs/2020-05-07T08_58_41_483Z-debug.log

[2020-05-07T08_58_41_483Z-debug.log](https://github.com/wix/Detox/files/4591898/2020-05-07T08_58_41_483Z-debug.log)

runner.ts.zip

Now I am unsure where to look at. Will provide more info as per request.

Body:
This answer helped me https://stackoverflow.com/a/57254546.
Just add this line to the e2e/config.json:

"preset": "react-native"


问:
How dispaly an svg on the option of select with ReactJs?
I have a select flags which the options are the img (which src are svg)

My codeSandbox.

```<code>
Config.default = "fr";
Config.list = {
  de: {
    text: "Deutsch",
    icon: require("./images/de.svg")
  },
  en: {
    text: "English",
    icon: require("./images/eng.svg")
  },
  it: {
    text: "Italiano",
    icon: require("./images/italy.svg")
  }
};
class App extends Component {
  constructor() {
    super();

    this.state = {
      language: Config.default
    };
  }

  render() {
    return (
      <header className="d-flex align-items-end justify-content-end">
        <LanguageList Language={this.state.language} />
        <FormControl variant="outlined">
          <div className="wrap-select">
            <Select
              value={this.state.language}
              className="select-lang"
              onChange={e => this.setState({ language: e.target.value })}
              inputProps={{
                name: "locale"
              }}
            >
              <MenuItem value="en">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/eng.svg" />
                </div>
              </MenuItem>
              <MenuItem value="it">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/italy.svg" alt="it" />
                </div>
              </MenuItem>
              <MenuItem value="de">
                <div className="wrap-content-lang">
                  <img width="20" src="./images/de.svg" />
                </div>
              </MenuItem>
            </Select>
          </div>
        </FormControl>
      </header>
    );
  }
}
</code>```

When I run it, I get:

The pictures are not displayed, How can I display it ?

答:
With create react app, to display svg, you can use import to display images.

import ItalySVG from './images/italy.svg'
```

<p>Or - you can require it.</p>

<pre class="lang-js prettyprint-override"><code><img src={require("./images/italy.svg")}/>
</code>```

However, You will still have issue with codesandbox to import svgs because of the open issue

If you are working in codesandbox, then for now you can use images instead. It works. See working demo

Body:
I have a select flags which the options are the img (which src are svg)

My codeSandbox.

Config.default = "fr";
Config.list = {
  de: {
    text: "Deutsch",
    icon: require("./images/de.svg")
  },
  en: {
    text: "English",
    icon: require("./images/eng.svg")
  },
  it: {
    text: "Italiano",
    icon: require("./images/italy.svg")
  }
};
class App extends Component {
  constructor() {
    super();

    this.state = {
      language: Config.default
    };
  }

  render() {
    return (

        <LanguageList Language={this.state.language} />
        <FormControl variant="outlined">

            <Select
              value={this.state.language}
              className="select-lang"
              onChange={e => this.setState({ language: e.target.value })}
              inputProps={{
                name: "locale"
              }}
            >
              <MenuItem value="en">

              </MenuItem>
              <MenuItem value="it">

              </MenuItem>
              <MenuItem value="de">

              </MenuItem>
            </Select>

        </FormControl>

    );
  }
}

When I run it, I get:

The pictures are not displayed, How can I display it ?

Body:
With create react app, to display svg, you can use import to display images.

import ItalySVG from './images/italy.svg'

Or - you can require it.

<img src={require("./images/italy.svg")}/>

However, You will still have issue with codesandbox to import svgs because of the open issue

If you are working in codesandbox, then for now you can use images instead. It works. See working demo


问:
 Sprite Issue
I have the following code

```<code><ul id ="menu">
    <%foreach (var pckg in Model)
    { %>

        <li style = "text-align:center;width:60px;" class = "top-<%=pckg.Controller.ToLower() %>">
            li-text
        </li>

    <%} %>

</ul>
</code>```

and following is the sprite CSS

```<code>.top-pkg1{ background-position: -184px 0; width: 36px; height: 36px; }
.top-pkg2{ background-position: -270px 0; width: 36px; height: 36px; }
.top-pkg3{ background-position: -356px 0; width: 36px; height: 36px; }
.top-pkg4{ background-position: -517px 0; width: 36px; height: 36px; }
.top-pkg5{ background-position: -603px 0; width: 36px; height: 31px; }
.top-pkg5{ background-position: -689px 0; width: 36px; height: 36px; }
.top-pkg6{ background-position: -775px 0; width: 36px; height: 36px; }
.top-pkg7{ background-position: -861px 0; width: 36px; height: 36px; }
</code>```

and here is the container css

```<code> #menu li
    {
         display:block;
         background: url(/Content/images/TopMenu/topmenu.png) no-repeat top left;

    }
    #menu li a
    {
        margin-top:35px;
        text-align:center;
    }
</code>```

But when i ran this code i get the first image of the sprite partially shown on all li tags Couldn't figure out the problem. I created the css from Here
Fiddle link is
http://jsfiddle.net/tassadaque/LnGqX/1/

答:
First, run:

```<code><ul id ="menu">
    <%foreach (var pckg in Model)
    { %>

        <li style = "text-align:center;width:60px;">
            top-<%=pckg.Controller.ToLower() %>
        </li>

    <%} %>

</ul>
</code>```

To see if you get top-pkg1, top-pkg2, etc.
It seems to me that you have the same class in all li's.

ContentLicense: CC BY-SA 3.0

Title: <ul> Sprite Issue

Body:
I have the following code

    <%foreach (var pckg in Model)
    { %>

        <li style = "text-align:center;width:60px;" class = "top-<%=pckg.Controller.ToLower() %>">
            li-text

    <%} %>

and following is the sprite CSS

.top-pkg1{ background-position: -184px 0; width: 36px; height: 36px; }
.top-pkg2{ background-position: -270px 0; width: 36px; height: 36px; }
.top-pkg3{ background-position: -356px 0; width: 36px; height: 36px; }
.top-pkg4{ background-position: -517px 0; width: 36px; height: 36px; }
.top-pkg5{ background-position: -603px 0; width: 36px; height: 31px; }
.top-pkg5{ background-position: -689px 0; width: 36px; height: 36px; }
.top-pkg6{ background-position: -775px 0; width: 36px; height: 36px; }
.top-pkg7{ background-position: -861px 0; width: 36px; height: 36px; }

and here is the container css

 #menu li
    {
         display:block;
         background: url(/Content/images/TopMenu/topmenu.png) no-repeat top left;

    }
    #menu li a
    {
        margin-top:35px;
        text-align:center;
    }

But when i ran this code i get the first image of the sprite partially shown on all li tags Couldn't figure out the problem. I created the css from Here
Fiddle link is
http://jsfiddle.net/tassadaque/LnGqX/1/

Body:
First, run:

<ul id ="menu">
    <%foreach (var pckg in Model)
    { %>

        <li style = "text-align:center;width:60px;">
            top-<%=pckg.Controller.ToLower() %>
        </li>

    <%} %>

</ul>

To see if you get top-pkg1, top-pkg2, etc.
It seems to me that you have the same class in all li's.


问:
C# Calendar Server Control
I am totally new to C# and coding. I'm working on a challenge in a course I'm taking which in part needs to satisfy the following business rule:

Business Rule 1: Initialize the calendar controls. Make sure the end of the previous assignment date is set to today.  Make sure the start date of the new assignment is set for an additional 14 days from today.  Make sure the end date of the new assignment is set for an additional 21 days from today.

When I initially set these dates the selected date was correct, but since it is late in the month, I would have to click to the next month to see the selected date:

```<code> protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                previousCalendar.SelectedDate = DateTime.Now.Date;
                newCalendar.SelectedDate = DateTime.Now.Date.AddDays(14);
                endCalendar.SelectedDate = DateTime.Now.Date.AddDays(21);
            }
</code>```

so I added the following 2 lines of code (of course within the curly brackets) to show the selected date:

```<code>            newCalendar.VisibleDate = newCalendar.SelectedDate;
            endCalendar.VisibleDate = endCalendar.SelectedDate;
</code>```

This seems a little cumbersome, is there a way to consolidate these last two lines?

Again, I'm a total noob so I'm sure the answer will be obvious to everyone else here.

答:
```<code>newCalendar.VisibleDate = newCalendar.SelectedDate = DateTime.Now.Date.AddDays(14);
endCalendar.VisibleDate = endCalendar.SelectedDate = DateTime.Now.Date.AddDays(21);
</code>```

<p>If this is what you mean, then yes. You can set the same value to 2 different properties in the same line of code. Sometimes keeping your steps as separate lines is better because it can make your code more readable for someone else who isn't familiar with it, but in this case, I think combining like above is reasonable. </p>

Title: C# Calendar Server Control

Body:
I am totally new to C# and coding. I'm working on a challenge in a course I'm taking which in part needs to satisfy the following business rule:

Business Rule 1: Initialize the calendar controls. Make sure the end of the previous assignment date is set to today.  Make sure the start date of the new assignment is set for an additional 14 days from today.  Make sure the end date of the new assignment is set for an additional 21 days from today.

When I initially set these dates the selected date was correct, but since it is late in the month, I would have to click to the next month to see the selected date:

 protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                previousCalendar.SelectedDate = DateTime.Now.Date;
                newCalendar.SelectedDate = DateTime.Now.Date.AddDays(14);
                endCalendar.SelectedDate = DateTime.Now.Date.AddDays(21);
            }

so I added the following 2 lines of code (of course within the curly brackets) to show the selected date:

            newCalendar.VisibleDate = newCalendar.SelectedDate;
            endCalendar.VisibleDate = endCalendar.SelectedDate;

This seems a little cumbersome, is there a way to consolidate these last two lines?

Again, I'm a total noob so I'm sure the answer will be obvious to everyone else here.

Body:
newCalendar.VisibleDate = newCalendar.SelectedDate = DateTime.Now.Date.AddDays(14);
endCalendar.VisibleDate = endCalendar.SelectedDate = DateTime.Now.Date.AddDays(21);

If this is what you mean, then yes. You can set the same value to 2 different properties in the same line of code. Sometimes keeping your steps as separate lines is better because it can make your code more readable for someone else who isn't familiar with it, but in this case, I think combining like above is reasonable.


问:
Clear Cache in Android Application programmatically
what is the correct way to clear cache in android Application programmatically. I already using following code but its not look work for me

```<code>@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}
</code>```

答:
This code will remove your whole cache of the application, You can check on app setting and open the app info and check the size of cache. Once you will use this code your cache size will be 0KB . So it and enjoy the clean cache. </p>

```<code> if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
                    .clearApplicationUserData();
            return;
        }
</code>```

Body:
what is the correct way to clear cache in android Application programmatically. I already using following code but its not look work for me

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

Body:
This code will remove your whole cache of the application, You can check on app setting and open the app info and check the size of cache. Once you will use this code your cache size will be 0KB . So it and enjoy the clean cache.

 if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
                    .clearApplicationUserData();
            return;
        }


问:
How to get command line arguments from position 1
Is there a way to get command line arguments in C# from args[1] and forward, excluding args[0]?

I've tried with this:

```<code>short argslenght = (short) args.Length;
string[] pargs = { "" };
for(int i = 1; i <= args.Length; i++)
{
    pargs[i-1] = args[i];
}
</code>```

But gives me this error:

```<code>System.IndexOutOfRangeException
</code>```

Thanks for your time.

答:
You are getting that error because you are trying to read a value from the array of index which exceeds the limit of the array length. It is happening for the last value. If there are 5 arguments, you can read the last one by args[4] but in your loop, you are trying to read it by args[5] which is causing the error.

You need to use Length -1 in your For loop, like this way:

```<code>for(int i = 1; i <= args.Length - 1; i++)
</code>```

Or remove the = from the condition:

```<code>for(int i = 1; i < args.Length; i++)
</code>```

Body:
Is there a way to get command line arguments in C# from args[1] and forward, excluding args[0]?

I've tried with this:

short argslenght = (short) args.Length;
string[] pargs = { "" };
for(int i = 1; i <= args.Length; i++)
{
    pargs[i-1] = args[i];
}

But gives me this error:

System.IndexOutOfRangeException

Thanks for your time.

Body:
You are getting that error because you are trying to read a value from the array of index which exceeds the limit of the array length. It is happening for the last value. If there are 5 arguments, you can read the last one by args[4] but in your loop, you are trying to read it by args[5] which is causing the error.

You need to use Length -1 in your For loop, like this way:

for(int i = 1; i <= args.Length - 1; i++)

Or remove the = from the condition:

for(int i = 1; i < args.Length; i++)


问:
Efficient way to count unique pairs in int array
This is my first post, hope it complies with posting guidelines of the site.
First of all a generic thanks to all the community: reading you from some months and learned a lot :o)

Premise: I'm a first years student of IT.

Here's the question: I'm looking for an efficient way to count the number of unique pairs (numbers that appear exactly twice) in a given positive int array (that's all I know), e.g. if:

```<code>int[] arr = {1,4,7,1,5,7,4,1,5};
</code>```

the number of unique pairs in arr is 3 (4,5,7).

I have some difficulties in... evaluating the efficiency of my proposals let's say.

Here's the first code I did:

```<code>int numCouples( int[] v ) {
int res = 0;
int count = 0;
for (int i = 0 ; i < v.length; i++){
    count = 0;
    for (int j = 0; j < v.length; j++){
        if (i != j && v[i] == v[j]){
            count++;
        }
    }
    if (count == 1){
        res++;
    }
}
return res/2;
}
</code>```

This shoudn't be good cause it checks the whole given array as many times as the number of elements in the given array... correct me if I'm wrong.

This is my second code:

```<code>int numCouples( int[] v) {
int n = 0;
int res = 0;
for (int i = 0; i < v.length; i++){
    if (v[i] > n){
        n = v[i];
    }
}
int[] a = new int [n];
for (int i = 0; i < v.length; i++){
    a[v[i]-1]++;
}
for (int i = 0; i < a.length; i++){
    if (a[i] == 2){
        res++;
    }
}
return res;
}
</code>```

I guess this should be better than the first one since it checks only 2 times the given array and 1 time the n array, when n is the max value of the given array. May be not so good if n is quite big I guess...

Well, 2 questions:

am I understanding good how to "measure" the efficiency of the code?

there's a better way to count the number of unique pairs in a given array?

EDIT:
Damn I've just posted and I'm already swamped by answers! Thanks! I'll study each one with care, for the time being I say I don't get those involving HashMap: out of my knowledge yet (hence thanks again for the insight:o) )

答:
A Java8 parallel streamy version which uses a ConcurrentHashMap </p>

```<code>int[] arr = {1,4,7,1,5,7,4,1,5};
Map<Integer,Long> map=Arrays.stream(arr).parallel().boxed().collect(Collectors.groupingBy(Function.identity(),
        ConcurrentHashMap::new,Collectors.counting()));
map.values().removeIf(v->v!=2);
System.out.println(map.keySet().size());
</code>```

Body:
This is my first post, hope it complies with posting guidelines of the site.
First of all a generic thanks to all the community: reading you from some months and learned a lot :o)

Premise: I'm a first years student of IT.

Here's the question: I'm looking for an efficient way to count the number of unique pairs (numbers that appear exactly twice) in a given positive int array (that's all I know), e.g. if:

int[] arr = {1,4,7,1,5,7,4,1,5};

the number of unique pairs in arr is 3 (4,5,7).

I have some difficulties in... evaluating the efficiency of my proposals let's say.

Here's the first code I did:

int numCouples( int[] v ) {
int res = 0;
int count = 0;
for (int i = 0 ; i < v.length; i++){
    count = 0;
    for (int j = 0; j < v.length; j++){
        if (i != j && v[i] == v[j]){
            count++;
        }
    }
    if (count == 1){
        res++;
    }
}
return res/2;
}

This shoudn't be good cause it checks the whole given array as many times as the number of elements in the given array... correct me if I'm wrong.

This is my second code:

int numCouples( int[] v) {
int n = 0;
int res = 0;
for (int i = 0; i < v.length; i++){
    if (v[i] > n){
        n = v[i];
    }
}
int[] a = new int [n];
for (int i = 0; i < v.length; i++){
    a[v[i]-1]++;
}
for (int i = 0; i < a.length; i++){
    if (a[i] == 2){
        res++;
    }
}
return res;
}

I guess this should be better than the first one since it checks only 2 times the given array and 1 time the n array, when n is the max value of the given array. May be not so good if n is quite big I guess...

Well, 2 questions:

am I understanding good how to "measure" the efficiency of the code?

there's a better way to count the number of unique pairs in a given array?

EDIT:
Damn I've just posted and I'm already swamped by answers! Thanks! I'll study each one with care, for the time being I say I don't get those involving HashMap: out of my knowledge yet (hence thanks again for the insight:o) )

Body:
A Java8 parallel streamy version which uses a ConcurrentHashMap

int[] arr = {1,4,7,1,5,7,4,1,5};
Map<Integer,Long> map=Arrays.stream(arr).parallel().boxed().collect(Collectors.groupingBy(Function.identity(),
        ConcurrentHashMap::new,Collectors.counting()));
map.values().removeIf(v->v!=2);
System.out.println(map.keySet().size());


问:
Way to get number of digits in an int?
Is there a neater way for getting the number of digits in an int than this method?</p>
```<code>int numDigits = String.valueOf(1000).length();
</code>```

答:
no String API, no utils, no type conversion, just pure java iteration ->

```<code>public static int getNumberOfDigits(int input) {
    int numOfDigits = 1;
    int base = 1;
    while (input >= base * 10) {
        base = base * 10;
        numOfDigits++;
    }
    return numOfDigits;
 }
</code>```

You can go long for bigger values if you please.

Title: Way to get number of digits in an int?

Body:
Is there a neater way for getting the number of digits in an int than this method?

int numDigits = String.valueOf(1000).length();

Body:
no String API, no utils, no type conversion, just pure java iteration ->

public static int getNumberOfDigits(int input) {
    int numOfDigits = 1;
    int base = 1;
    while (input >= base * 10) {
        base = base * 10;
        numOfDigits++;
    }
    return numOfDigits;
 }

You can go long for bigger values if you please.


问:
Why at the time of invocation of browser 'java.lang.NullPointerException' is occurring in maven project and how to fix this?
I am making a maven project and at the time of opening the chrome browser is shows
 java.lang.NullPointerException exeption, i am unable to find what is missing here and why browser is not opening.

my base class is like this

```<code>
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterMethod;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;

import pages.LandingPage;
import pages.LoginPage;
import utils.ExtentReportManager;
import utils.DateUtils;

public class Base {
 public WebDriver driver;
 public Properties prop;
 public ExtentReports report = ExtentReportManager.getReportInstance();
 public ExtentTest logger;

 public void invokeBrowser(String browsername) {
     try {
         if (browsername.equalsIgnoreCase("Chrome")) {
             System.setProperty("webdriver.chrome.driver",
                     System.getProperty("user.dir") + "\\src\\resourc\\driver\\chromedriver.exe");
             driver = new ChromeDriver();//This is line 39 in Base
         } else if (browsername.equalsIgnoreCase("Firefox")) {
             System.setProperty("webdriver.gecko.driver",
                     System.getProperty("user.dir") + "\\src\\resourc\\driver\\geckodriver.exe");
             driver = new FirefoxDriver();
         } else {
             System.setProperty("webdriver.IEDriverServer.driver",
                     System.getProperty("user.dir") + "\\src\\resourc\\driver\\IEDriverServer.exe");
             driver = new InternetExplorerDriver();
         }
     } catch (Exception e) {
           e.printStackTrace();
     }
     driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);//**This is line 53**
     driver.manage().window().maximize();
     driver.manage().timeouts().pageLoadTimeout(180, TimeUnit.SECONDS);

         prop = new Properties();

         try {
             FileInputStream file = new FileInputStream(
                     System.getProperty("user.dir") + "\\src\\resourc\\ObjectRepository\\projectConfig.properties");
             prop.load(file);
         } catch (Exception e) {
             e.printStackTrace();
         }

     }

 public LandingPage OpenApplication(String websiteURLKey ) {
     driver.get(prop.getProperty(websiteURLKey));
     return PageFactory.initElements(driver, LandingPage.class);
 }

 public void closebrowser() {
     driver.close();
 }

 @AfterMethod
 public void reportFlush() {
     report.flush();
 }

 /****************** Capture Screen Shot ***********************/
 public void takeScreenShotOnFailure() {
     TakesScreenshot takeScreenShot = (TakesScreenshot) driver;
     File sourceFile = takeScreenShot.getScreenshotAs(OutputType.FILE);

     File destFile = new File(System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");
     try {
         FileUtils.copyFile(sourceFile, destFile);
//          logger.addScreenCaptureFromPath(
//                  System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");

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

 }

}
</code>```

and my test class is like this from where i am running all the files for project one by one

```<code>package test;

import org.apache.http.client.utils.DateUtils;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;

import base.Base;
import pages.DisplayDetails;
import pages.HomePage;
import pages.LandingPage;
import pages.LoginPage;
import pages.UpcomingBikesPage;
import utils.ExtentReportManager;

public class ProjectTest extends Base{
    LandingPage landingpage;
    LoginPage loginpage;
    HomePage homepage;
    UpcomingBikesPage upcomingbikespage;
    DisplayDetails displaydetails;

    @Test
    public void openBrowser() throws Exception {

        logger = report.createTest("Zigwheels Website Automation");
        Base base = new Base();
        logger.log(Status.INFO, "Initializing the Browser");
        base.invokeBrowser("chrome");//**This is line 32 in test file**
        logger.log(Status.INFO, "Opening the Website");
        landingpage = base.OpenApplication("websiteURL");
        logger.log(Status.INFO, " Login initated Successfully");
        loginpage = landingpage.initiatelogin();
        logger.log(Status.INFO, "Entered Credentials Successfully");

        homepage = loginpage.login();
        logger.log(Status.INFO, "Login Successfull");

        upcomingbikespage = homepage.home();
        logger.log(Status.INFO, "Got Upcoming Honda Bikes Successfully");
        displaydetails=upcomingbikespage.hondamanufacturer();

        displaydetails.finaly();

        //logger.addScreenCaptureFromPath(System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");

    }

}
</code>```

And in the console Error is as follows--

```<code>[RemoteTestNG] detected TestNG version 6.14.3
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 36324
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
FAILED: openBrowser
java.lang.NullPointerException
    at base.Base.invokeBrowser(Base.java:53)
    at test.ProjectTest.openBrowser(ProjectTest.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
</code>```

Line 53 is Shown through comment that is implicit wait line
Line 32 in test is also shown through comment that is base.invokeBrowser("chrome"); line.

```<code>org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 80
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'PRANJAL', ip: '192.168.225.26', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_241'
Driver info: driver.version: ChromeDriver
remote stacktrace: Backtrace:
    Ordinal0 [0x00F80C83+1707139]
    Ordinal0 [0x00EE68F1+1075441]
    Ordinal0 [0x00E5DFC9+516041]
    Ordinal0 [0x00DF0554+66900]
    Ordinal0 [0x00DECCE2+52450]
    Ordinal0 [0x00E0BFD7+180183]
    Ordinal0 [0x00E0BDDD+179677]
    Ordinal0 [0x00E09D4B+171339]
    Ordinal0 [0x00DF1D4A+73034]
    Ordinal0 [0x00DF2DC0+77248]
    Ordinal0 [0x00DF2D59+77145]
    Ordinal0 [0x00EFBB67+1162087]
    GetHandleVerifier [0x0101A966+508998]
    GetHandleVerifier [0x0101A6A4+508292]
    GetHandleVerifier [0x0102F7B7+594583]
    GetHandleVerifier [0x0101B1D6+511158]
    Ordinal0 [0x00EF402C+1130540]
    Ordinal0 [0x00EFD4CB+1168587]
    Ordinal0 [0x00EFD633+1168947]
    Ordinal0 [0x00F15B35+1268533]
    BaseThreadInitThunk [0x75F9343D+18]
    RtlInitializeExceptionChain [0x77209812+99]
    RtlInitializeExceptionChain [0x772097E5+54]

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$errorHandler$0(W3CHandshakeResponse.java:62)
    at org.openqa.selenium.remote.HandshakeResponse.lambda$getResponseFunction$0(HandshakeResponse.java:30)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:126)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
</code>```

答:
I've built your code. It works fine; it runs passed that line.

I've used my own chromedriver absolute path.

Might be a typo somewhere for your path. I suggest using pwd in a terminal/powershell in that chromedriver directory.

If not, it's potentially a missing selenium library. Have you downloaded selenium libraries and manually imported them?

if (browsername.equalsIgnoreCase("Chrome")) {
                System.setProperty("webdriver.chrome.driver",
                        "/Users/user/Documents/qac-cv-management-system/AutomatedTestReact/chromedriver");
                driver = new ChromeDriver();//This is line 39 in
}
```

Body:
I am making a maven project and at the time of opening the chrome browser is shows
 java.lang.NullPointerException exeption, i am unable to find what is missing here and why browser is not opening.

my base class is like this

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterMethod;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;

import pages.LandingPage;
import pages.LoginPage;
import utils.ExtentReportManager;
import utils.DateUtils;

public class Base {
 public WebDriver driver;
 public Properties prop;
 public ExtentReports report = ExtentReportManager.getReportInstance();
 public ExtentTest logger;

 public void invokeBrowser(String browsername) {
     try {
         if (browsername.equalsIgnoreCase("Chrome")) {
             System.setProperty("webdriver.chrome.driver",
                     System.getProperty("user.dir") + "\\src\\resourc\\driver\\chromedriver.exe");
             driver = new ChromeDriver();//This is line 39 in Base
         } else if (browsername.equalsIgnoreCase("Firefox")) {
             System.setProperty("webdriver.gecko.driver",
                     System.getProperty("user.dir") + "\\src\\resourc\\driver\\geckodriver.exe");
             driver = new FirefoxDriver();
         } else {
             System.setProperty("webdriver.IEDriverServer.driver",
                     System.getProperty("user.dir") + "\\src\\resourc\\driver\\IEDriverServer.exe");
             driver = new InternetExplorerDriver();
         }
     } catch (Exception e) {
           e.printStackTrace();
     }
     driver.manage().timeouts().implicitlyWait(180, TimeUnit.SECONDS);//**This is line 53**
     driver.manage().window().maximize();
     driver.manage().timeouts().pageLoadTimeout(180, TimeUnit.SECONDS);

         prop = new Properties();

         try {
             FileInputStream file = new FileInputStream(
                     System.getProperty("user.dir") + "\\src\\resourc\\ObjectRepository\\projectConfig.properties");
             prop.load(file);
         } catch (Exception e) {
             e.printStackTrace();
         }

     }

 public LandingPage OpenApplication(String websiteURLKey ) {
     driver.get(prop.getProperty(websiteURLKey));
     return PageFactory.initElements(driver, LandingPage.class);
 }

 public void closebrowser() {
     driver.close();
 }

 @AfterMethod
 public void reportFlush() {
     report.flush();
 }

 /****************** Capture Screen Shot ***********************/
 public void takeScreenShotOnFailure() {
     TakesScreenshot takeScreenShot = (TakesScreenshot) driver;
     File sourceFile = takeScreenShot.getScreenshotAs(OutputType.FILE);

     File destFile = new File(System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");
     try {
         FileUtils.copyFile(sourceFile, destFile);
//          logger.addScreenCaptureFromPath(
//                  System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");

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

 }

}

and my test class is like this from where i am running all the files for project one by one

package test;

import org.apache.http.client.utils.DateUtils;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;

import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;

import base.Base;
import pages.DisplayDetails;
import pages.HomePage;
import pages.LandingPage;
import pages.LoginPage;
import pages.UpcomingBikesPage;
import utils.ExtentReportManager;

public class ProjectTest extends Base{
    LandingPage landingpage;
    LoginPage loginpage;
    HomePage homepage;
    UpcomingBikesPage upcomingbikespage;
    DisplayDetails displaydetails;

    @Test
    public void openBrowser() throws Exception {

        logger = report.createTest("Zigwheels Website Automation");
        Base base = new Base();
        logger.log(Status.INFO, "Initializing the Browser");
        base.invokeBrowser("chrome");//**This is line 32 in test file**
        logger.log(Status.INFO, "Opening the Website");
        landingpage = base.OpenApplication("websiteURL");
        logger.log(Status.INFO, " Login initated Successfully");
        loginpage = landingpage.initiatelogin();
        logger.log(Status.INFO, "Entered Credentials Successfully");

        homepage = loginpage.login();
        logger.log(Status.INFO, "Login Successfull");

        upcomingbikespage = homepage.home();
        logger.log(Status.INFO, "Got Upcoming Honda Bikes Successfully");
        displaydetails=upcomingbikespage.hondamanufacturer();

        displaydetails.finaly();

        //logger.addScreenCaptureFromPath(System.getProperty("user.dir") + "/ScreenShots/" + DateUtils.getTimeStamp() + ".png");

    }

}

And in the console Error is as follows--

[RemoteTestNG] detected TestNG version 6.14.3
Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 36324
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
FAILED: openBrowser
java.lang.NullPointerException
    at base.Base.invokeBrowser(Base.java:53)
    at test.ProjectTest.openBrowser(ProjectTest.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
    at org.testng.TestNG.runSuites(TestNG.java:1049)
    at org.testng.TestNG.run(TestNG.java:1017)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

Line 53 is Shown through comment that is implicit wait line
Line 32 in test is also shown through comment that is base.invokeBrowser("chrome"); line.

org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 80
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'PRANJAL', ip: '192.168.225.26', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_241'
Driver info: driver.version: ChromeDriver
remote stacktrace: Backtrace:
    Ordinal0 [0x00F80C83+1707139]
    Ordinal0 [0x00EE68F1+1075441]
    Ordinal0 [0x00E5DFC9+516041]
    Ordinal0 [0x00DF0554+66900]
    Ordinal0 [0x00DECCE2+52450]
    Ordinal0 [0x00E0BFD7+180183]
    Ordinal0 [0x00E0BDDD+179677]
    Ordinal0 [0x00E09D4B+171339]
    Ordinal0 [0x00DF1D4A+73034]
    Ordinal0 [0x00DF2DC0+77248]
    Ordinal0 [0x00DF2D59+77145]
    Ordinal0 [0x00EFBB67+1162087]
    GetHandleVerifier [0x0101A966+508998]
    GetHandleVerifier [0x0101A6A4+508292]
    GetHandleVerifier [0x0102F7B7+594583]
    GetHandleVerifier [0x0101B1D6+511158]
    Ordinal0 [0x00EF402C+1130540]
    Ordinal0 [0x00EFD4CB+1168587]
    Ordinal0 [0x00EFD633+1168947]
    Ordinal0 [0x00F15B35+1268533]
    BaseThreadInitThunk [0x75F9343D+18]
    RtlInitializeExceptionChain [0x77209812+99]
    RtlInitializeExceptionChain [0x772097E5+54]

    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$errorHandler$0(W3CHandshakeResponse.java:62)
    at org.openqa.selenium.remote.HandshakeResponse.lambda$getResponseFunction$0(HandshakeResponse.java:30)
    at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:126)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)


问:
Handle French Characters in Java
I Have a Page where I search for a term and it is displaying perfect. Whatever character type it is.

Now when I have few checkboxes in JSP and I check it and submit. In these checkboxes I have one box name like ABC Farmacéutica Corporation.

When I click on submit button, I am calling a function and will set all parameters to a form and will submit that form. (I tested putting alert for the special character display before submit and it is displaying good).

Now, coming to the Java end, I use Springs Frame work. When I print the term in controller, then it is displayed like ABC FarmacÃ©utica Corporation.

Please help...
Thanks in advance.

EDIT :

Please try this sample Example

```<code>import java.net.*;
class sample{
    public static void main(String[] args){
        try{
            String aaa = "ABC Farmacéutica Corporation";
            String bbb = "ABC FarmacÃ©utica Corporation";

            aaa = URLEncoder.encode(aaa, "UTF-8");
            bbb = URLDecoder.decode(bbb, "UTF-8");

            System.out.println("aaa   "+aaa);
            System.out.println("bbb   "+bbb);

        }catch(Exception e){
            System.out.println(e);
        }
    }
}
</code>```

I am getting output as,

```<code>aaa   PiSA+Farmac%C3%A9utica+Mexicana+Corporativo
bbb   PiSA Farmac├⌐utica Mexicana Corporativo
</code>```

Try to print the string aaa as it is.

答:
I suspect the problem is with character encoding on the page. Make sure the page you submit from and the one you display to use the same character set and make sure that you set it explicitely.
for instance if your server runs on Linux the default encoding will be UTF-8 but if you view the page on Windows it will assume (if no encoding is specified) it to be ISO-8859-1.
Also when you are receiving the submitted text on your server side, the server will assume the default character set when building the string -- whereas your user might have used a differrent encoding if you didn't specify one.</p>

Title: Handle French Characters in Java

Body:
I Have a Page where I search for a term and it is displaying perfect. Whatever character type it is.

Now when I have few checkboxes in JSP and I check it and submit. In these checkboxes I have one box name like ABC Farmacéutica Corporation.

When I click on submit button, I am calling a function and will set all parameters to a form and will submit that form. (I tested putting alert for the special character display before submit and it is displaying good).

Now, coming to the Java end, I use Springs Frame work. When I print the term in controller, then it is displayed like ABC FarmacÃ©utica Corporation.

Please help...
Thanks in advance.

EDIT :

Please try this sample Example

import java.net.*;
class sample{
    public static void main(String[] args){
        try{
            String aaa = "ABC Farmacéutica Corporation";
            String bbb = "ABC FarmacÃ©utica Corporation";

            aaa = URLEncoder.encode(aaa, "UTF-8");
            bbb = URLDecoder.decode(bbb, "UTF-8");

            System.out.println("aaa   "+aaa);
            System.out.println("bbb   "+bbb);

        }catch(Exception e){
            System.out.println(e);
        }
    }
}

I am getting output as,

aaa   PiSA+Farmac%C3%A9utica+Mexicana+Corporativo
bbb   PiSA Farmac├⌐utica Mexicana Corporativo

Try to print the string aaa as it is.


问:
Corda3, field level access restrictions for an output state of a transaction across multiple parties
I have 5 nodes each representing partyA, partyB, partyC, partyD, partyE.
I need to make a transaction with need as described below...

only 'write user' from partyA should be able to 'create' or initiate flow with a state which has 20 fields, with parties as partyA,B,  C,D,E.

any other user (including 'read user' from partyA) should be able to only view output state details (but do not have ability to modify/consume it).

partyA, partyB should get to see all 20 fields.

partyC, partyD should see only 15 of those 20 fields.

partyE should see only 10 of 20 fields.

Can some one suggest best approach to achieve field level read write access control for output states in corda3.x please.

Thanks in advance.

答:
I am afraid there is no privacy control down to a field level of states.

For your example, the best is to create 3 kinds of states to share with those parties, say a FullState, HalvedState, QuarteredState.

In your contracts, you can make sure the initiator/initial signer of the transaction is partyA's identity. Because only the initiator is able to make changes which matches your #1 requirement.

Then implement 2 flows that will be triggered after the FullState is created/modified and clone it to a HalvedState and share with the corresponding nodes.


问:
Observable<string[]> in ngIf directive
I have a method that returns roles of a user like:

```<code>  getUserRoles() : Observable<string[]> {
    return this.getToken().pipe(
      map(token => {
        let payload = decode(token);
        return payload["roles"];
      })
    )
  }
</code>```

I'm trying to use this in an anchor to hide/show the item based on a role like:

```<code><a *ngIf="(authService.getUserRoles | async).includes('admin')" routerLink="/admin" clrDropdownItem>Admin</a>
</code>```

However, I get the compiler error:

```<code>ERROR in src/app/components/profile/profile.component.html:15:18 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '() => Observable<string[]>' is not assignable to parameter of type 'Promise<unknown>'.
      Type '() => Observable<string[]>' is missing the following properties from type 'Promise<unknown>': then, catch, [Symbol.toStringTag], finally

15       <a *ngIf="(authService.getUserRoles | async).includes('admin')" routerLink="/admin" clrDropdownItem>Admin</a>
                    ~~~~~~~~~~~~~~~~~~~~~~~~~

  src/app/components/profile/profile.component.ts:7:16
    7   templateUrl: './profile.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component ProfileComponent.
</code>```

Can't quite figure out what I'm doing wrong. I'm using Angular 9.

答:
Your approach won't work...

Even if you change your code to this: authService.getUserRoles() | async
Your code won't work because this function would run every time your view is checked and
you will not benefit from the async pipe, the opposite.

It would be better

1) Subscribe to your data in the initilazition of the component (remember to unsubscribe before you destroy the component).

2) Create new pipe to handle that logic.

3) Use guards.

4) Make the function synchronous:

```<code>.ts
    isInRole(role: string): boolean {
        const token = this.getToken();
        const payload = decode(token);
        return payload && payload["roles"] && payload["roles"].includes(role);
    }

.html

     <a *ngIf="isInRole('admin')" routerLink="/admin" clrDropdownItem>Admin</a>
</code>```

Title: Observable<string[]> in ngIf directive

Body:
I have a method that returns roles of a user like:

  getUserRoles() : Observable<string[]> {
    return this.getToken().pipe(
      map(token => {
        let payload = decode(token);
        return payload["roles"];
      })
    )
  }

I'm trying to use this in an anchor to hide/show the item based on a role like:

Admin

However, I get the compiler error:

ERROR in src/app/components/profile/profile.component.html:15:18 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '() => Observable<string[]>' is not assignable to parameter of type 'Promise<unknown>'.
      Type '() => Observable<string[]>' is missing the following properties from type 'Promise<unknown>': then, catch, [Symbol.toStringTag], finally

15       Admin
                    ~~~~~~~~~~~~~~~~~~~~~~~~~

  src/app/components/profile/profile.component.ts:7:16
    7   templateUrl: './profile.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component ProfileComponent.

Can't quite figure out what I'm doing wrong. I'm using Angular 9.

Body:
Your approach won't work...

Even if you change your code to this: authService.getUserRoles() | async
Your code won't work because this function would run every time your view is checked and
you will not benefit from the async pipe, the opposite.

It would be better

1) Subscribe to your data in the initilazition of the component (remember to unsubscribe before you destroy the component).

2) Create new pipe to handle that logic.

3) Use guards.

4) Make the function synchronous:

.ts
    isInRole(role: string): boolean {
        const token = this.getToken();
        const payload = decode(token);
        return payload && payload["roles"] && payload["roles"].includes(role);
    }

.html

     <a *ngIf="isInRole('admin')" routerLink="/admin" clrDropdownItem>Admin</a>


问:
Composer : Why some of my packages got automatically removed on installing a new package
My composer status while installing the new package

I tried installing stripe package on yii2 via composer. It got installed successfully but also removed some of the packages automatically. I didn't edit composer.json or lock file, I just execute the composer require command to install the package. Why the composer removed those packages and how can I recover them back? Is there any way to prevent it in future?
Thanks!

答:
Say your project A requires dependency B.

Version 1.1.x of dependency B requires package C.

Now if you update to version 1.2.x of dependency B which does NOT depend on package C anymore composer will automatically detect the orphaned dependency and therefore remove package C.

If you still want package C to be available to your application after the update you need to explicitly require it - making it an explicit dependency instead of an implicit one (installed as a dependency of another package).

composer automatically updates the other dependencies of your project (respecting the existing version constraints your composer.json) if you invoke composer require.

To prevent automatic dependency updates use:

```<code>composer require --no-update <package>
</code>```

Body:
Say your project A requires dependency B.

Version 1.1.x of dependency B requires package C.

Now if you update to version 1.2.x of dependency B which does NOT depend on package C anymore composer will automatically detect the orphaned dependency and therefore remove package C.

If you still want package C to be available to your application after the update you need to explicitly require it - making it an explicit dependency instead of an implicit one (installed as a dependency of another package).

composer automatically updates the other dependencies of your project (respecting the existing version constraints your composer.json) if you invoke composer require.

To prevent automatic dependency updates use:

composer require --no-update <package>


问:
Enable PHP logging in Azure App Service (WebApp)
This has been asked a handful of times, but in 2020 the accepted solution doesn't appear to work. I have uploaded my PHP files to /site/wwwroot and inside the same wwwroot created a php.ini file with only one line entry:

```<code>display_errors=On
</code>```

I also created an App Setting for my WebApp, as below - Key name PHP_INI_SCAN_DIR and value as shown below:

The website has been restarted. Still no PHP errors displaying. I get a blank page.

答:
I think it's necessary for you to enable error logging here:

Then you can go to kudu, a new folder should be found in kudu, this folder holds the error message.

Body:
This has been asked a handful of times, but in 2020 the accepted solution doesn't appear to work. I have uploaded my PHP files to /site/wwwroot and inside the same wwwroot created a php.ini file with only one line entry:

display_errors=On

I also created an App Setting for my WebApp, as below - Key name PHP_INI_SCAN_DIR and value as shown below:

The website has been restarted. Still no PHP errors displaying. I get a blank page.


问:
Office Automation - Create msg file
I'm trying to create an Outlook Message File (.msg) file using Python, specifically from Flask.

Here's what I have:

```<code>import win32com.client
def html2msg():
    com_object = win32com.client.Dispatch('Outlook.Application')
    com_file = com_object.CreateItem(0)
    com_file.Subject = 'Subject'
    com_file.HTMLBody = '<html><head></head><body><p>Test Email</p></body></html>'
    com_file.SaveAs('new.msg')
    com_file.Close(0)
</code>```

This works fine when run as a user in Windows, or instigated from within flask when the flask app is run manually as a user...

The issue comes when it is run behind IIS with wfastcgi: I get this non-specific error:

```<code>File "<COMObject Outlook.Application>", line 2, in CreateItem
pywintypes.com_error: (-2147467260, 'Operation aborted', None, None)
</code>```

I previously had similar(ish) issues with Word, which were caused because the com object was being run under the system profile, and were solved by creating a folder as per: https://theether.net/kb/100120?id=100120

Has anyone managed to accomplish something similar?

答:
The issue comes when it is run behind IIS with wfastcgi: I get this non-specific error:

The Considerations for server-side Automation of Office article states the following for the error you've got:

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.

As a workaround, you need to use a low-level API on which Outlook is based on - Extended MAPI or just any wrapper around that API such as Redemption.

If you deal with Exchange server profiles only, consider using EWS, see Start using web services in Exchange for more information.

Title: Office Automation - Create msg file

Body:
I'm trying to create an Outlook Message File (.msg) file using Python, specifically from Flask.

Here's what I have:

import win32com.client
def html2msg():
    com_object = win32com.client.Dispatch('Outlook.Application')
    com_file = com_object.CreateItem(0)
    com_file.Subject = 'Subject'
    com_file.HTMLBody = '
Test Email
'
    com_file.SaveAs('new.msg')
    com_file.Close(0)

This works fine when run as a user in Windows, or instigated from within flask when the flask app is run manually as a user...

The issue comes when it is run behind IIS with wfastcgi: I get this non-specific error:

File "<COMObject Outlook.Application>", line 2, in CreateItem
pywintypes.com_error: (-2147467260, 'Operation aborted', None, None)

I previously had similar(ish) issues with Word, which were caused because the com object was being run under the system profile, and were solved by creating a folder as per: https://theether.net/kb/100120?id=100120

Has anyone managed to accomplish something similar?


问:
sort Array by another Array like GroupBy NodeJs
Hello I have two array and I want to sort them another array but i want to sort like group by.

```<code>var a = [1,2,3,2,1,3,3,2,1]
var b = [b,b,b,c,c,c,d,d,d]
</code>```

The result I want like;

```<code>var a =[3,2,1,3,2,1,3,2,1]
var b =[b,b,b,c,c,c,d,d,d]
</code>```

答:
Assuming you're trying to sort groups based on the associated letters of each number, you could group each number first by its associated letter from b by using a Map with .reduce(), then sort each group so it's in descending order with .sort(). Once each group is sorted, you can flatten your array of groups using .concat() like so:

const a = [1,2,3,2,1,3,3,2,1];
const b = ['b','b','b','c','c','c','d','d','d'];

const sortedGroups = [].concat(...Array.from(a.reduce((map, val, i) =>
  map.set(b[i], (map.get(b[i]) || []).concat(val)),
  new Map
).values(), grouped => grouped.sort((a, b) => b-a)));

console.log(sortedGroups);```

Body:
Hello I have two array and I want to sort them another array but i want to sort like group by.

var a = [1,2,3,2,1,3,3,2,1]
var b = [b,b,b,c,c,c,d,d,d]

The result I want like;

var a =[3,2,1,3,2,1,3,2,1]
var b =[b,b,b,c,c,c,d,d,d]


问:
Socket IO Rooms: Get list of clients in specific room
I'm trying to display a list of clients in a specific room. I just want to show their username, and not their socket id.

This where I'm at:

```<code>socket.set('nickname', "Earl");
socket.join('chatroom1');
console.log('User joined chat room 1);

var roster = io.sockets.clients('chatroom1');
for ( i in roster )
{
   console.log('Username: ' + roster[i]);
}
</code>```

Haven't had any luck getting it to list Socket IDs or anything. Would like it to return the nicknames however.

答:
socket.io ^ 2.0

```<code>function getRoomClients(room) {
  return new Promise((resolve, reject) => {
    io.of('/').in(room).clients((error, clients) => {
      resolve(clients);
    });
  });
}

...
const clients = await getRoomClients('hello-world');
console.log(clients);
</code>```

Output

```<code>[ '9L47TWua75nkL_0qAAAA',
'tVDBzLjhPRNdgkZdAAAB',
'fHjm2kxKWjh0wUAKAAAC' ]
</code>```

Body:
I'm trying to display a list of clients in a specific room. I just want to show their username, and not their socket id.

This where I'm at:

socket.set('nickname', "Earl");
socket.join('chatroom1');
console.log('User joined chat room 1);

var roster = io.sockets.clients('chatroom1');
for ( i in roster )
{
   console.log('Username: ' + roster[i]);
}

Haven't had any luck getting it to list Socket IDs or anything. Would like it to return the nicknames however.

Body:
socket.io ^ 2.0

function getRoomClients(room) {
  return new Promise((resolve, reject) => {
    io.of('/').in(room).clients((error, clients) => {
      resolve(clients);
    });
  });
}

...
const clients = await getRoomClients('hello-world');
console.log(clients);

Output

[ '9L47TWua75nkL_0qAAAA',
'tVDBzLjhPRNdgkZdAAAB',
'fHjm2kxKWjh0wUAKAAAC' ]


问:
How to find all enhancements in SAP system?
I need to prepare a document which includes all enhancements implemented in the SAP system of the company, what are all steps that I have to go through?</p>

答:
Another more comprehensive way to find all the enhancements is to (re)use the best practices.

A wonderful tool called ABAP Exit Ray Eye was developed yet in 2009 and though it is a bit forgotten now, it is still does the job.

Having different criteria

it can show you currently implemented enhancements in a very nifty and user-friendly way:

The source code of this tool can be grabbed in archive from Github repo and is installable by SAPLink.


问:
Jenkins Pipeline - emailext Does not Resolve env Variable in Template
In my jenkinsfile I defined an environment variable:

env.PACKAGES = htmlPackageList

I tried accessing it from the template with ${PACKAGES} and ${env.PACKAGES}, but both times I just receive the email with a plain string.

template.html:

```<code><pre style='line-height: 10px; color: green; font-size: 20px; white-space: pre; margin: 1em 0; display: block;'>$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS.<br/> ```

Check console Build URL to view full results.

Change list:

    ${CHANGES, showPaths=true, format="
%a: %r %p

 — “%m”
", pathFormat="

%p"}

--

Published Packages:

${PACKAGES}
```

<p>The email is invoked by:</p>

```success {
    script{
        emailext body: ('${FILE,path="Jenkins/Templates/template.html"}'),
        to: "${env.EmailTo}",
        subject: '[Jenkins] [$PROJECT_NAME] - [Build # $BUILD_NUMBER] - [$BUILD_STATUS]',
        mimeType: 'text/html'
     }
}
```

答:
The below declaration in template(groovy) can fetch all the env variables from pipeline

```<code><% def envEnviron = it.getAction("org.jenkinsci.plugins.workflow.cps.EnvActionImpl").getEnvironment()
    println(envEnviron)
%\>
</code>```

The below also can be used to get only the overridden variables in pipeline

```<code><% def envOveriddenEnviron = it.getAction("org.jenkinsci.plugins.workflow.cps.EnvActionImpl").getOverriddenEnvironment()
    println(envOveriddenEnviron)
%\>
</code>```

Body:
In my jenkinsfile I defined an environment variable:

env.PACKAGES = htmlPackageList

I tried accessing it from the template with ${PACKAGES} and ${env.PACKAGES}, but both times I just receive the email with a plain string.

template.html:

$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS.

Check console Build URL to view full results.

Change list:

    ${CHANGES, showPaths=true, format="
%a: %r %p

 — “%m”
", pathFormat="

%p"}

--

Published Packages:

${PACKAGES}

The email is invoked by:

success {
    script{
        emailext body: ('${FILE,path="Jenkins/Templates/template.html"}'),
        to: "${env.EmailTo}",
        subject: '[Jenkins] [$PROJECT_NAME] - [Build # $BUILD_NUMBER] - [$BUILD_STATUS]',
        mimeType: 'text/html'
     }
}

Body:
The below declaration in template(groovy) can fetch all the env variables from pipeline

<% def envEnviron = it.getAction("org.jenkinsci.plugins.workflow.cps.EnvActionImpl").getEnvironment()
    println(envEnviron)
%\>

The below also can be used to get only the overridden variables in pipeline

<% def envOveriddenEnviron = it.getAction("org.jenkinsci.plugins.workflow.cps.EnvActionImpl").getOverriddenEnvironment()
    println(envOveriddenEnviron)
%\>


问:
I need to calculate the number of holidays, falling on working days only, between two dates
I have a table, called Holidays, which lists all the dates classed as a holiday:

```<code>Date
01/01/2020
10/04/2020
13/04/2020
</code>```

I have a table called employees, which shows an employee's working days, in a 7 digit syntax, where 0 is a working day and 1 is not a working day. It goes from Monday to Sunday. So '0000011' would mean that person works on Monday to Friday, and does not work on Saturday/Sunday.

```<code>Code     WorkingDays
A1       0000011
B1       1000111
</code>```

I have a table of date ranges as such:

```<code>From         To          Employee
01/01/2020   31/05/2020  A1
01/01/2020   31/05/2020  B1
</code>```

What I would like to return is:

```<code>From         To          Employee    Holidays
01/01/2020   31/05/2020  A1          3
01/01/2020   31/05/2020  B1          0
</code>```

Employee A1 - there are 3 Holidays which fall between those two dates and are also working days
Employee B1 - there are no Holidays which fall between those two dates and are also working days

I need something similar to the NETWORKDAYS.INTL function, but instead of calculating working days I need it to calculate holidays somehow. Is this possible?

答:
Use NETWORKDAYS.INTL twice, one with just the weekends and the other that include the holidays and subtract the later from the prior:

```<code>=NETWORKDAYS.INTL(D2,E2,C2)-NETWORKDAYS.INTL(D2,E2,C2,$A$2:$A$4)
</code>```

Body:
I have a table, called Holidays, which lists all the dates classed as a holiday:

Date
01/01/2020
10/04/2020
13/04/2020

I have a table called employees, which shows an employee's working days, in a 7 digit syntax, where 0 is a working day and 1 is not a working day. It goes from Monday to Sunday. So '0000011' would mean that person works on Monday to Friday, and does not work on Saturday/Sunday.

Code     WorkingDays
A1       0000011
B1       1000111

I have a table of date ranges as such:

From         To          Employee
01/01/2020   31/05/2020  A1
01/01/2020   31/05/2020  B1

What I would like to return is:

From         To          Employee    Holidays
01/01/2020   31/05/2020  A1          3
01/01/2020   31/05/2020  B1          0

Employee A1 - there are 3 Holidays which fall between those two dates and are also working days
Employee B1 - there are no Holidays which fall between those two dates and are also working days

I need something similar to the NETWORKDAYS.INTL function, but instead of calculating working days I need it to calculate holidays somehow. Is this possible?

Body:
Use NETWORKDAYS.INTL twice, one with just the weekends and the other that include the holidays and subtract the later from the prior:

=NETWORKDAYS.INTL(D2,E2,C2)-NETWORKDAYS.INTL(D2,E2,C2,$A$2:$A$4)


问:
Dask dataframe read parquet format fails from http
I have been dealing with this problem for a week.
I use the command

```<code>from dask import dataframe as ddf
ddf.read_parquet("http://IP:port/webhdfs/v1/user/...")
</code>```

I got invalid parquet magic.
However ddf.read_parquet is Ok with "webhdfs://"

I would like the ddf.read_parquet works for http because I want to use it in dask-ssh cluster for workers without hdfs access.

答:
Although the comments already partly answer this question, I thought I would add some information as an answer

HTTP(S) is supported by dask (actually fsspec) as a backend filesystem; but to get partitioning within a file, you need to get the size of that file, and to resolve globs, you need to be able to get a list of links, neither of which are necessarily provided by any given server

webHDFS (or indeed httpFS) don't work like HTTP downloads, you need to use a specific API to open a file and fetch a final URL on a cluster member to that file; so the two methods are not interchangeable

webHDFS is normally intended for use outside of the hadoop cluster; within the cluster, you would probably use plain HDFS ("hdfs://"). However, kerberos-secured webHDFS can be tricky to work with, depending on how the security was set up.

Body:
I have been dealing with this problem for a week.
I use the command

from dask import dataframe as ddf
ddf.read_parquet("http://IP:port/webhdfs/v1/user/...")

I got invalid parquet magic.
However ddf.read_parquet is Ok with "webhdfs://"

I would like the ddf.read_parquet works for http because I want to use it in dask-ssh cluster for workers without hdfs access.


问:
Django: changing image size and upload to S3
I have inherited a Django Project and we have moved images to S3

One of the models is a typical user profile

```<code>class Profile(UUIDBase):

    first_name = models.CharField(_("First Name"), max_length=20)
    last_name = models.CharField(_("Last Name"), max_length=20, null=True)
    profile_image = models.ImageField(
        _("Profile Image"),
        upload_to=profile_image_name,
         max_length=254,
        blank=True,
        null=True
    )
    profile_image_thumb = models.ImageField(
        _("Profile Image Thumbnail"),
        upload_to=profile_image_name,
        max_length=254,
        blank=True,
       null=True
    )
    ... other fields
</code>```

Where profile_image_name is a function:

```<code>def profile_image_name(instance, filename):
    if filename:
        target_dir = 'uploads/profile_img/'
        _, ext = filename.rsplit('.', 1)
        filename = str(instance.uid) + '.' + ext
        return '/'.join([target_dir, filename])
</code>```

I have a bit of code that worked:

```<code>@shared_task
def resize_image(image_path, dim_x, append_str='_resized', **kwargs):
    '''
    resize any image_obj while maintaining aspect ratio
    '''
    orig = storage.open(image_path, 'r')
    im = Image.open(orig, mode='r')
    new_y = (float(dim_x) * float(im.height)) / float(im.width)
    new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS)
    img_path, img_name = path.split(image_path)
    file_name, img_ext = img_name.rsplit('.', 1)
    new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext)
    try:
        new_f = storage.open(new_img_path, 'w')
    except IOError as e:
        logger.critical("Caught IOError in {}, {}".format(__file__, e))
        ravenclient.captureException()
        return None
    try:
        new_im.save(new_f)
    except IOError as e:
        logger.critical("Caught IOError in {}, {}".format(__file__, e))
        ravenclient.captureException()
       return None
    except Exception as e:
       logger.critical("Caught unhandled exception in {}. {}".format(
        __file__, e)
       )
       ravenclient.captureException()
       return None
    im.close()
    new_im.close()
    new_f.close()
    return new_img_path
</code>```

Which is called from a post_save signal handler :

```<code>@receiver(post_save, sender=Profile, dispatch_uid='resize_profile_image')
def resize_profile_image(sender, instance=None, created=False, **kwargs):
    if created:
        if instance.profile_image:
            width, height = image_dimensions(instance.profile_image.name)
            print(width, height)
            if width > MAX_WIDTH:
                result = resize_image.delay(instance.profile_image.name, MAX_WIDTH)
                instance.profile_image.name = result.get()
            if width > THUMB_WIDTH:
                result = resize_image.delay(
                    instance.profile_image.name,
                    THUMB_WIDTH,
                    append_str='_thumb'
                )
                instance.profile_image_thumb.name = result.get()
            try:
                instance.save()
            except Exception as e:
                log.critical("Unhandled exception in {}, {}".format(__name__, e))
                ravenclient.captureException()
</code>```

The intent is to take uploaded images and resize them 1) to the max width that a mobile device can display and 2) to a 50 pixel thumbnail for use in the mobile app.

When I look on S3, I do not see my resized images or thumbnails. Yet the unit tests (which are thorough) don't give any errors.

When I get the image dimensions:

```<code>def image_dimensions(image_path):
    f = storage.open(image_path, 'r')
    im = Image.open(f, 'r')
    height = im.height
    width = im.width
    im.close()
    f.close()
    return (width, height)
</code>```

There is no problem accessing the object's ImageField.  I get no error when I use default_storage to open the instance's profile_image. The PIL method

new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS)  does return a new instance of class 'PIL.Image.Image'.

In fact (pardon my verbosity)

This does not raise an error:

```<code>>>> u = User(email="root@groupon.com", password="sdfbskjfskjfskjdf")
>>> u.save()
>>> p = Profile(user=u, profile_image=create_image_file())
>>> p.save()
>>> from django.core.files.storage import default_storage as storage
>>> orig = storage.open(p.profile_image.name, 'r')
>>> orig
<S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19.jpg>
>>> im = Image.open(orig, mode='r')
>>> im
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=5000x5000 at 0x10B8F1FD0>
>>> im.__class__
<class 'PIL.JpegImagePlugin.JpegImageFile'>
>>> dim_x = 500
>>> new_y = (float(dim_x) * float(im.height)) / float(im.width)
>>> new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS)
>>> new_im.__class__
<class 'PIL.Image.Image'>
>>> img_path, img_name = path.split(p.profile_image.name)
>>> file_name, img_ext = img_name.rsplit('.', 1)
>>> append_str='_resized'
>>> new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext)
>>> new_f = storage.open(new_img_path, 'w')
>>> new_f
<S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19_resized.jpg>
>>> new_im.save(new_f)  #### This does NOT create an S3 file!!!!
>>> im.close()
>>> new_im.close()
>>> new_f.close()
</code>```

>>> p.save() uploads the new profile image to S3.  I was expecting >>> new_im.save(new_f) to write the Image file to S3.  But it does not.

Any insight or help is greatly appreciated and thank you for taking the time to look at this problem.

Edit ...

My settings:

```<code>AWS_STORAGE_BUCKET_NAME = 'testthis'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'
</code>```

Where custom_storage.py is

```<code>from django.conf import settings
from storages.backends.s3boto import S3BotoStorage

class MediaStorage(S3BotoStorage):
    location = settings.MEDIAFILES_LOCATION
    bucket_name = settings.AWS_STORAGE_BUCKET_NAME
</code>```

答:
I think the whole setup is crazy. I'd strongly suggest you look into using a library like django-versatileimagefield. The implementation would look like this:

```<code>from versatileimagefield.fields import VersatileImageField
from versatileimagefield.image_warmer import VersatileImageFieldWarmer

class Profile(UUIDBase):
    first_name = models.CharField(_("First Name"), max_length=20)
    last_name = models.CharField(_("Last Name"), max_length=20, null=True)
    image = VersatileImageFied(upload_to='uploads/profile_img/', blank=True, null=True)

@receiver(models.signals.post_save, sender=Profile)
def warm_profile_image(sender, instance, **kwargs):
    if instance.image:
        VersatileImageFieldWarmer(instance_or_queryset=instance, rendition_key_set='profile_image', image_attr='image', verbose=True).warm()
</code>```

And in your settings:

```<code>VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = {
    'profile_image': [
        ('cropped', 'crop__400x400'),
        ('thumbnail', 'thumbnail__20x20')
    ]
}
</code>```

The Profile warmer creates representations saved to S3 no problem. You can access either the full image as profile.image or the different versions as profile.image.cropped and profile.image.thumbnail. The library even allows you to set up a point of interest so the cropping happens around a specific center point in the image.

Serializers if using DRF:

```<code>from versatileimagefield.serializers import VersatileImageFieldSerializer

class ProfileSerializer(serializers.ModelSerializer):
    image = VersatileImageFieldSerializer(
        sizes=[
            ('cropped', 'crop__400x400'),
            ('thumbnail', 'thumbnail__20x20')
        ],
        required=False
    )
    ... other fields and the Meta class
</code>```

Body:
I have inherited a Django Project and we have moved images to S3

One of the models is a typical user profile

class Profile(UUIDBase):

    first_name = models.CharField(_("First Name"), max_length=20)
    last_name = models.CharField(_("Last Name"), max_length=20, null=True)
    profile_image = models.ImageField(
        _("Profile Image"),
        upload_to=profile_image_name,
         max_length=254,
        blank=True,
        null=True
    )
    profile_image_thumb = models.ImageField(
        _("Profile Image Thumbnail"),
        upload_to=profile_image_name,
        max_length=254,
        blank=True,
       null=True
    )
    ... other fields

Where profile_image_name is a function:

def profile_image_name(instance, filename):
    if filename:
        target_dir = 'uploads/profile_img/'
        _, ext = filename.rsplit('.', 1)
        filename = str(instance.uid) + '.' + ext
        return '/'.join([target_dir, filename])

I have a bit of code that worked:

@shared_task
def resize_image(image_path, dim_x, append_str='_resized', **kwargs):
    '''
    resize any image_obj while maintaining aspect ratio
    '''
    orig = storage.open(image_path, 'r')
    im = Image.open(orig, mode='r')
    new_y = (float(dim_x) * float(im.height)) / float(im.width)
    new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS)
    img_path, img_name = path.split(image_path)
    file_name, img_ext = img_name.rsplit('.', 1)
    new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext)
    try:
        new_f = storage.open(new_img_path, 'w')
    except IOError as e:
        logger.critical("Caught IOError in {}, {}".format(__file__, e))
        ravenclient.captureException()
        return None
    try:
        new_im.save(new_f)
    except IOError as e:
        logger.critical("Caught IOError in {}, {}".format(__file__, e))
        ravenclient.captureException()
       return None
    except Exception as e:
       logger.critical("Caught unhandled exception in {}. {}".format(
        __file__, e)
       )
       ravenclient.captureException()
       return None
    im.close()
    new_im.close()
    new_f.close()
    return new_img_path

Which is called from a post_save signal handler :

@receiver(post_save, sender=Profile, dispatch_uid='resize_profile_image')
def resize_profile_image(sender, instance=None, created=False, **kwargs):
    if created:
        if instance.profile_image:
            width, height = image_dimensions(instance.profile_image.name)
            print(width, height)
            if width > MAX_WIDTH:
                result = resize_image.delay(instance.profile_image.name, MAX_WIDTH)
                instance.profile_image.name = result.get()
            if width > THUMB_WIDTH:
                result = resize_image.delay(
                    instance.profile_image.name,
                    THUMB_WIDTH,
                    append_str='_thumb'
                )
                instance.profile_image_thumb.name = result.get()
            try:
                instance.save()
            except Exception as e:
                log.critical("Unhandled exception in {}, {}".format(__name__, e))
                ravenclient.captureException()

The intent is to take uploaded images and resize them 1) to the max width that a mobile device can display and 2) to a 50 pixel thumbnail for use in the mobile app.

When I look on S3, I do not see my resized images or thumbnails. Yet the unit tests (which are thorough) don't give any errors.

When I get the image dimensions:

def image_dimensions(image_path):
    f = storage.open(image_path, 'r')
    im = Image.open(f, 'r')
    height = im.height
    width = im.width
    im.close()
    f.close()
    return (width, height)

There is no problem accessing the object's ImageField.  I get no error when I use default_storage to open the instance's profile_image. The PIL method

new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS)  does return a new instance of class 'PIL.Image.Image'.

In fact (pardon my verbosity)

This does not raise an error:

>>> u = User(email="root@groupon.com", password="sdfbskjfskjfskjdf")
>>> u.save()
>>> p = Profile(user=u, profile_image=create_image_file())
>>> p.save()
>>> from django.core.files.storage import default_storage as storage
>>> orig = storage.open(p.profile_image.name, 'r')
>>> orig
<S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19.jpg>
>>> im = Image.open(orig, mode='r')
>>> im
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=5000x5000 at 0x10B8F1FD0>
>>> im.__class__
<class 'PIL.JpegImagePlugin.JpegImageFile'>
>>> dim_x = 500
>>> new_y = (float(dim_x) * float(im.height)) / float(im.width)
>>> new_im = im.resize((dim_x, int(new_y)), Image.ANTIALIAS)
>>> new_im.__class__
<class 'PIL.Image.Image'>
>>> img_path, img_name = path.split(p.profile_image.name)
>>> file_name, img_ext = img_name.rsplit('.', 1)
>>> append_str='_resized'
>>> new_img_path = path.join(img_path, file_name + append_str + '.' + img_ext)
>>> new_f = storage.open(new_img_path, 'w')
>>> new_f
<S3BotoStorageFile: uploads/profile_img/b0fd4f00-cce6-4dd3-b514-4c46a801ab19_resized.jpg>
>>> new_im.save(new_f)  #### This does NOT create an S3 file!!!!
>>> im.close()
>>> new_im.close()
>>> new_f.close()

>>> p.save() uploads the new profile image to S3.  I was expecting >>> new_im.save(new_f) to write the Image file to S3.  But it does not.

Any insight or help is greatly appreciated and thank you for taking the time to look at this problem.

Edit ...

My settings:

AWS_STORAGE_BUCKET_NAME = 'testthis'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'

Where custom_storage.py is

from django.conf import settings
from storages.backends.s3boto import S3BotoStorage

class MediaStorage(S3BotoStorage):
    location = settings.MEDIAFILES_LOCATION
    bucket_name = settings.AWS_STORAGE_BUCKET_NAME

Body:
I think the whole setup is crazy. I'd strongly suggest you look into using a library like django-versatileimagefield. The implementation would look like this:

from versatileimagefield.fields import VersatileImageField
from versatileimagefield.image_warmer import VersatileImageFieldWarmer

class Profile(UUIDBase):
    first_name = models.CharField(_("First Name"), max_length=20)
    last_name = models.CharField(_("Last Name"), max_length=20, null=True)
    image = VersatileImageFied(upload_to='uploads/profile_img/', blank=True, null=True)

@receiver(models.signals.post_save, sender=Profile)
def warm_profile_image(sender, instance, **kwargs):
    if instance.image:
        VersatileImageFieldWarmer(instance_or_queryset=instance, rendition_key_set='profile_image', image_attr='image', verbose=True).warm()

And in your settings:

VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = {
    'profile_image': [
        ('cropped', 'crop__400x400'),
        ('thumbnail', 'thumbnail__20x20')
    ]
}

The Profile warmer creates representations saved to S3 no problem. You can access either the full image as profile.image or the different versions as profile.image.cropped and profile.image.thumbnail. The library even allows you to set up a point of interest so the cropping happens around a specific center point in the image.

Serializers if using DRF:

from versatileimagefield.serializers import VersatileImageFieldSerializer

class ProfileSerializer(serializers.ModelSerializer):
    image = VersatileImageFieldSerializer(
        sizes=[
            ('cropped', 'crop__400x400'),
            ('thumbnail', 'thumbnail__20x20')
        ],
        required=False
    )
    ... other fields and the Meta class


问:
Fast check of first inequality
I am looking for a function similar to match, but it should have an inequality as test and stop at the first occurrence.

```<code>a <- c(1,3,5,7,9,12)
b <- 6
# the output should be 4
# i tried this one:  match(min(a [b <= a ]),a ), but with much data it is slow
</code>```

答:
findInterval gives the index of b in a or the index of the largest value in a less than b if there is no match; therefore, use findInterval and then add 1 if it is not an exact match since you want the next rather than prior index.  a must be sorted in ascending order.

```<code>ix <- findInterval(b, a, all.inside = TRUE)
ix <- ix + (a[ix] < b)

ix
## [1] 4
</code>```

or possibly the first line is sufficient if you can change the requirements slightly.   There is some question regarding how edge cases are to be handled but I have added all.inside = TRUE to handle one such situation.

Title: Fast check of first inequality

Body:
I am looking for a function similar to match, but it should have an inequality as test and stop at the first occurrence.

a <- c(1,3,5,7,9,12)
b <- 6
# the output should be 4
# i tried this one:  match(min(a [b <= a ]),a ), but with much data it is slow

Body:
findInterval gives the index of b in a or the index of the largest value in a less than b if there is no match; therefore, use findInterval and then add 1 if it is not an exact match since you want the next rather than prior index.  a must be sorted in ascending order.

ix <- findInterval(b, a, all.inside = TRUE)
ix <- ix + (a[ix] < b)

ix
## [1] 4

or possibly the first line is sufficient if you can change the requirements slightly.   There is some question regarding how edge cases are to be handled but I have added all.inside = TRUE to handle one such situation.


问:
MongoDB Pagination with two values
Let's say my MongoDB records look like this:

{category: A , sub_category : 1}

{category: A , sub_category : 2}

{category: A , sub_category : 3}

{category: B , sub_category : 1}

{category: B , sub_category : 2}

{category: B , sub_category : 3}

{category: C , sub_category : 1}

{category: C , sub_category : 2}

{category: C , sub_category : 3}

I am trying to achieve pagination with these values. So, I created a compound index with both of these fields (both in ascending order).

Let's say my page limit is 2.

So my first query looks like this -> db.record.find().sort({category: 1, sub_category: 1}); -> And the first two records are returned.

My second query looks like this -> db.record.find({category : {$gte: A}, sub_category: {$gt : 2}}).sort({category: 1, sub_category: 1}).

I was expecting record 3 and 4 to return. But I got record 3 and record 6.

I understood that my way of querying is not right. I couldn't find another solution. Please help me with this issue.

P.S. I am not using skip and limit technique, because I am following bucket pattern.

答:
I followed the suggestions from Tom Slabbaert and Adnan Ahmed Ansari, and the solution worked.

I used this query:

```<code>db.record.find({ $or: [ { category : 'A' , sub_category: {$gt : 2}}, { category : {$gt: 'A'} } ] })
</code>```

Title: MongoDB Pagination with two values

Body:
I followed the suggestions from Tom Slabbaert and Adnan Ahmed Ansari, and the solution worked.

I used this query:

db.record.find({ $or: [ { category : 'A' , sub_category: {$gt : 2}}, { category : {$gt: 'A'} } ] })


问:
Reading file string into an array (In a pythonic way)
I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.

I have pretty much everything sorted up to convert the lines into arrays.

I basically do (pseudopython code)

```<code> line=file.readlines()
 line=line.split(' ') # Or whatever separator
 array=np.array(line)
 #And then iterate over every value casting them as floats
      newarray[i]=array.float(array[i])
</code>```

This works, buts seems a bit counterintuitive and antipythonic, I wanted to know if there is a better way to handle the inputs from a file to have at the end an array full of floats.

答:
Quick answer:

```<code>arrays = []
for line in open(your_file): # no need to use readlines if you don't want to store them
    # use a list comprehension to build your array on the fly
    new_array = np.array((array.float(i) for i in line.split(' ')))
    arrays.append(new_array)
</code>```

If you process often this kind of data, the csv module will help.

```<code>import csv

arrays = []
# declare the format of you csv file and Python will turn line into
# lists for you
parser = csv.reader(open(your_file), delimiter=' '))
for l in parser:
    arrays.append(np.array((array.float(i) for i in l)))
</code>```

If you feel wild, you can even make this completly declarative:

```<code>import csv

parser = csv.reader(open(your_file), delimiter=' '))
make_array = lambda row : np.array((array.float(i) for i in row))
arrays = [make_array(row) for row in parser]
</code>```

And if you realy want you colleagues to hate you, you can make a one liner (NOT PYTHONIC AT ALL :-):

```<code>arrays = [np.array((array.float(i) for i in r)) for r in csv.reader(open(your_file), delimiter=' '))]
</code>```

Stripping all the boiler plate and flexibility, you can end up with a clean and quite readable one liner. I wouldn't use it because I like the refatoring potential of using csv, but it can be good enought. It's a grey zone here, so I wouldn't say it's Pythonic, but it's definitly handy.

```<code>arrays = [np.array((array.float(i) for i in l.split())) for l in open(your_file))]
</code>```

Body:
I'm reading lines from a file to then work with them. Each line is composed solely by float numbers.

I have pretty much everything sorted up to convert the lines into arrays.

I basically do (pseudopython code)

 line=file.readlines()
 line=line.split(' ') # Or whatever separator
 array=np.array(line)
 #And then iterate over every value casting them as floats
      newarray[i]=array.float(array[i])

This works, buts seems a bit counterintuitive and antipythonic, I wanted to know if there is a better way to handle the inputs from a file to have at the end an array full of floats.

Body:
Quick answer:

arrays = []
for line in open(your_file): # no need to use readlines if you don't want to store them
    # use a list comprehension to build your array on the fly
    new_array = np.array((array.float(i) for i in line.split(' ')))
    arrays.append(new_array)

If you process often this kind of data, the csv module will help.

import csv

arrays = []
# declare the format of you csv file and Python will turn line into
# lists for you
parser = csv.reader(open(your_file), delimiter=' '))
for l in parser:
    arrays.append(np.array((array.float(i) for i in l)))

If you feel wild, you can even make this completly declarative:

import csv

parser = csv.reader(open(your_file), delimiter=' '))
make_array = lambda row : np.array((array.float(i) for i in row))
arrays = [make_array(row) for row in parser]

And if you realy want you colleagues to hate you, you can make a one liner (NOT PYTHONIC AT ALL :-):

arrays = [np.array((array.float(i) for i in r)) for r in csv.reader(open(your_file), delimiter=' '))]

Stripping all the boiler plate and flexibility, you can end up with a clean and quite readable one liner. I wouldn't use it because I like the refatoring potential of using csv, but it can be good enought. It's a grey zone here, so I wouldn't say it's Pythonic, but it's definitly handy.

arrays = [np.array((array.float(i) for i in l.split())) for l in open(your_file))]