问:
Want data added to the Query via Left Outer Joint to NOT repeat
I have a database structure (ER diagram below) that has three level of hierarchical data and the fourth level of optional data.

If I write a query to get de-normalized data of three levels - level 1 to level 3 with sample data across three tables shown as below:

When queried, this layout of the data is very straight forward and as expected as below:

Upon running the below query, I get the following output (And I have tried various combinations by clubbing the set of L1 to L4 and moving one L4 out as a another query and then joining the set L1 - L4 etc.) - again this is on the expected lines.

```<code>SELECT        [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId,
                         ManagementResponse.ManagementResponseTest
FROM            Category INNER JOIN
                         [Group] ON Category.GroupId = [Group].GroupId INNER JOIN
                         RLI ON Category.CategoryId = RLI.CategoryId LEFT OUTER JOIN
                         ManagementResponse ON RLI.RLIId = ManagementResponse.RLIId LEFT OUTER JOIN
                         Comment ON RLI.RLIId = Comment.RLIId
</code>```

However, I need data in the following format - and this is what I am unable to figure out how to get (I don't want the level 4 data to repeat as I add additional level 4 data via left outer joins):

答:
This query will give you the final output:

```<code>WITH CommentAndResponse AS (

SELECT Comment.CommentId,
         Comment.CommentText,
         ManagementResponse.ManagementResponseId,
         ManagementResponse.ManagementResponseTest,
    COALESCE(Comment.RLIId, ManagementResponse.RLIId) AS RLIId
 FROM (
    (SELECT Comment.CommentId,
            Comment.CommentText,
            Comment.RLIId,
            ROW_NUMBER() OVER (PARTITION BY Comment.RLIId ORDER BY Comment.CommentId) AS CommentRowNumber
    FROM Comment) AS Comment
    FULL JOIN
    (SELECT  ManagementResponse.ManagementResponseId,
            ManagementResponse.ManagementResponseTest,
            ManagementResponse.RLIId,
            ROW_NUMBER() OVER (PARTITION BY ManagementResponse.RLIId ORDER BY ManagementResponse.ManagementResponseId) AS ManagementResponseRowNumber
    FROM ManagementResponse) AS ManagementResponse
    ON Comment.CommentRowNumber = ManagementResponse.ManagementResponseRowNumber AND Comment.RLIId = ManagementResponse.RLIId )
    )

SELECT          [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, CommentAndResponse.CommentId, CommentAndResponse.CommentText, CommentAndResponse.ManagementResponseId, CommentAndResponse.ManagementResponseTest
FROM            [Category]
INNER JOIN      [Group] ON Category.GroupId = [Group].GroupId
INNER JOIN      [RLI] ON Category.CategoryId = RLI.CategoryId
LEFT OUTER JOIN [CommentAndResponse] ON RLI.RLIId = CommentAndResponse.RLIId
</code>```

Body:
I have a database structure (ER diagram below) that has three level of hierarchical data and the fourth level of optional data.

If I write a query to get de-normalized data of three levels - level 1 to level 3 with sample data across three tables shown as below:

When queried, this layout of the data is very straight forward and as expected as below:

Upon running the below query, I get the following output (And I have tried various combinations by clubbing the set of L1 to L4 and moving one L4 out as a another query and then joining the set L1 - L4 etc.) - again this is on the expected lines.

SELECT        [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId,
                         ManagementResponse.ManagementResponseTest
FROM            Category INNER JOIN
                         [Group] ON Category.GroupId = [Group].GroupId INNER JOIN
                         RLI ON Category.CategoryId = RLI.CategoryId LEFT OUTER JOIN
                         ManagementResponse ON RLI.RLIId = ManagementResponse.RLIId LEFT OUTER JOIN
                         Comment ON RLI.RLIId = Comment.RLIId

However, I need data in the following format - and this is what I am unable to figure out how to get (I don't want the level 4 data to repeat as I add additional level 4 data via left outer joins):

Body:
This query will give you the final output:

WITH CommentAndResponse AS (

SELECT Comment.CommentId,
         Comment.CommentText,
         ManagementResponse.ManagementResponseId,
         ManagementResponse.ManagementResponseTest,
    COALESCE(Comment.RLIId, ManagementResponse.RLIId) AS RLIId
 FROM (
    (SELECT Comment.CommentId,
            Comment.CommentText,
            Comment.RLIId,
            ROW_NUMBER() OVER (PARTITION BY Comment.RLIId ORDER BY Comment.CommentId) AS CommentRowNumber
    FROM Comment) AS Comment
    FULL JOIN
    (SELECT  ManagementResponse.ManagementResponseId,
            ManagementResponse.ManagementResponseTest,
            ManagementResponse.RLIId,
            ROW_NUMBER() OVER (PARTITION BY ManagementResponse.RLIId ORDER BY ManagementResponse.ManagementResponseId) AS ManagementResponseRowNumber
    FROM ManagementResponse) AS ManagementResponse
    ON Comment.CommentRowNumber = ManagementResponse.ManagementResponseRowNumber AND Comment.RLIId = ManagementResponse.RLIId )
    )

SELECT          [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, CommentAndResponse.CommentId, CommentAndResponse.CommentText, CommentAndResponse.ManagementResponseId, CommentAndResponse.ManagementResponseTest
FROM            [Category]
INNER JOIN      [Group] ON Category.GroupId = [Group].GroupId
INNER JOIN      [RLI] ON Category.CategoryId = RLI.CategoryId
LEFT OUTER JOIN [CommentAndResponse] ON RLI.RLIId = CommentAndResponse.RLIId


来源: stackexchange

问:
Edge 15 throws error when using 'for ... of' on a NodeList
When looking at the ECMAScript compatibility table, it says that Edge 15 and Edge 16 support for ... of loops.

However, when I run this code:

const list = document.querySelectorAll('[data-test]');
console.log(list);

for (const item of list) {
  console.log(item);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div></code>```

It works in Chrome and Firefox, but not in Edge. Instead it says:

Object doesn't support property or method 'Symbol.iterator'.

As I understand it, NodeList actually should support it, right?

Here's a fildde to try it yourself: Test it online

Can somebody explain the problem or the mistake here?

答:
Edge does support for... of.

It would seem that it doesn't support iterators on NodeLists. Not all array-like objects support iterators and I'm not sure whether there is any standard saying that NodeLists have to.

In any case, it's easy enough to get for ... of to work with them:

const list = document.querySelectorAll('[data-test]');

for (const item of Array.from(list)) {
 console.log(item);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-test>a</div>
<div data-test>b</div>
<div data-test>c</div>
<div data-test>d</div>
<div data-test>e</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
When looking at the ECMAScript compatibility table, it says that Edge 15 and Edge 16 support for ... of loops.

However, when I run this code:

const list = document.querySelectorAll('[data-test]');
console.log(list);

for (const item of list) {
  console.log(item);
}

It works in Chrome and Firefox, but not in Edge. Instead it says:

Object doesn't support property or method 'Symbol.iterator'.

As I understand it, NodeList actually should support it, right?

Here's a fildde to try it yourself: Test it online

Can somebody explain the problem or the mistake here?

Body:
Edge does support for... of.

It would seem that it doesn't support iterators on NodeLists. Not all array-like objects support iterators and I'm not sure whether there is any standard saying that NodeLists have to.

In any case, it's easy enough to get for ... of to work with them:

const list = document.querySelectorAll('[data-test]');

for (const item of Array.from(list)) {
 console.log(item);
}

<div data-test>a</div>
<div data-test>b</div>
<div data-test>c</div>
<div data-test>d</div>
<div data-test>e</div>

ContentLicense: CC BY-SA 3.0


问:
OpenSearch + PHP for INSPIRE ATOM : Why can I get the correct Content-Type?
I've been following the official Technical Guide for Download Services of INSPIRE to build an ATOM feed with OpenSearch: https://inspire.ec.europa.eu/documents/technical-guidance-implementation-inspire-download-services

I'm stuck at creating the PHP that performs the search.

According to the before mentioned guide, the OpenSearch description XML has to have these templates:

```<code><Url type="application/zip" rel="results" template="http://myWeb/atom/search.php?spatial_dataset_identifier_code={inspire_dls:spatial_dataset_identifier_code?}&spatial_dataset_identifier_namespace={inspire_dls:spatial_dataset_identifier_namespace?}&crs={inspire_dls:crs?}&language={language?}&q={searchTerms?}"/>

<Url type="application/atom+xml" rel="describedby" template="http://myWeb/atom/search.php?spatial_dataset_identifier_code={inspire_dls:spatial_dataset_identifier_code?}&spatial_dataset_identifier_namespace={inspire_dls:spatial_dataset_identifier_namespace?}&crs={inspire_dls:crs?}&language={language?}&q={searchTerms?}"/>
</code>```

The same guide has a PHP script to help the developer write the "search.php" file. That script starts like this:

```<code>$returnFile = false;
foreach (apache_request_headers() as $name => $value) {
   //echo("$name: $value\n");
   if ($name=="Accept" && $value=="application/zip"){
      $returnFile = true;
   }
}
</code>```

If $returnFile is true, a ZIP file must be returned. If it is false, an XML is returned (that is what the rest of the script does).

My problem is that the condition $name=="Accept" && $value=="application/zip" is never true, so the search always returns an XML.

How can $value be application/zip?

This is the Accept value that I get when accessing http://myWeb/atom/search.php:

```<code>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
</code>```

EDIT: The guide tells something more about this:

```<code>The example given in Annex A uses content negotiation to identify which
operation to perform. This means that even though the operation endpoint is
only one, i.e. http://myWeb/search.php, the client has to set the HTTP
―Accept‖ Header to the correct value in order to receive the expected
result.
</code>```

So, if I test my ATOM feed in the INSPIRE validator, the client is the INSPIRE validator (the one that sends the queries to search.php)... am I wrong?

答: I opened an issue with the developers of the validator and they confirmed that is not working as expected. The validator should add the 'Accept' header in the request, but it leaves it blank. They are working in a fix.</p>

Body:
I've been following the official Technical Guide for Download Services of INSPIRE to build an ATOM feed with OpenSearch: https://inspire.ec.europa.eu/documents/technical-guidance-implementation-inspire-download-services

I'm stuck at creating the PHP that performs the search.

According to the before mentioned guide, the OpenSearch description XML has to have these templates:

<Url type="application/zip" rel="results" template="http://myWeb/atom/search.php?spatial_dataset_identifier_code={inspire_dls:spatial_dataset_identifier_code?}&spatial_dataset_identifier_namespace={inspire_dls:spatial_dataset_identifier_namespace?}&crs={inspire_dls:crs?}&language={language?}&q={searchTerms?}"/>

<Url type="application/atom+xml" rel="describedby" template="http://myWeb/atom/search.php?spatial_dataset_identifier_code={inspire_dls:spatial_dataset_identifier_code?}&spatial_dataset_identifier_namespace={inspire_dls:spatial_dataset_identifier_namespace?}&crs={inspire_dls:crs?}&language={language?}&q={searchTerms?}"/>

The same guide has a PHP script to help the developer write the "search.php" file. That script starts like this:

$returnFile = false;
foreach (apache_request_headers() as $name => $value) {
   //echo("$name: $value\n");
   if ($name=="Accept" && $value=="application/zip"){
      $returnFile = true;
   }
}

If $returnFile is true, a ZIP file must be returned. If it is false, an XML is returned (that is what the rest of the script does).

My problem is that the condition $name=="Accept" && $value=="application/zip" is never true, so the search always returns an XML.

How can $value be application/zip?

This is the Accept value that I get when accessing http://myWeb/atom/search.php:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8

EDIT: The guide tells something more about this:

The example given in Annex A uses content negotiation to identify which
operation to perform. This means that even though the operation endpoint is
only one, i.e. http://myWeb/search.php, the client has to set the HTTP
―Accept‖ Header to the correct value in order to receive the expected
result.

So, if I test my ATOM feed in the INSPIRE validator, the client is the INSPIRE validator (the one that sends the queries to search.php)... am I wrong?


问:
jsPDF: How to use doc.text() to print strings in separate lines?
I have a loop that prints strings in a JSON object. </p>

```<code>for (var i in list){
    doc.text(list[i]['id'] + '  ' + list[i]['name'], 10 ,10)
}
</code>```

<p>In the pdf file, all strings overlapped in the first line. I tried adding '\n' but it didn't work. How do I use doc.text() to print strings in separate lines? </p>

答:
The function you're using takes the parameters (coordinates) x and y like so: doc.text(text, x, y, flags). So to print the strings in seperate lines, you should add something to the y-component of the coordinate each time the loop runs. Example:

```<code>for (var i in list){
    doc.text(list[i]['id'] + '  ' + list[i]['name'], 10, 10 + 10*i)
}
</code>```

Source: jsPDF.text

EDIT: As said in the comments, you could also just pass an array of the text you want to display like this:

```<code>var text = []
for (var i in list){
    text.push(list[i]['id'] + '  ' + list[i]['name'])
}
doc.text(text, 10, 10)
</code>```

Body:
I have a loop that prints strings in a JSON object.

for (var i in list){
    doc.text(list[i]['id'] + '  ' + list[i]['name'], 10 ,10)
}

In the pdf file, all strings overlapped in the first line. I tried adding '\n' but it didn't work. How do I use doc.text() to print strings in separate lines?

Body:
The function you're using takes the parameters (coordinates) x and y like so: doc.text(text, x, y, flags). So to print the strings in seperate lines, you should add something to the y-component of the coordinate each time the loop runs. Example:

for (var i in list){
    doc.text(list[i]['id'] + '  ' + list[i]['name'], 10, 10 + 10*i)
}

Source: jsPDF.text

EDIT: As said in the comments, you could also just pass an array of the text you want to display like this:

var text = []
for (var i in list){
    text.push(list[i]['id'] + '  ' + list[i]['name'])
}
doc.text(text, 10, 10)


问:
Partially flattening a JavaScript object
I have a JavaScript object that I receive from an API that I cannot modify. I would like to use this data within a tool, but the tool only accepts values stored on the root level of the object e.g. I cannot use dot notation to access the value of a key a level down.

Based on the example below, I'd like to be able to access shape.colour, but by referencing something like shape__colour instead, from a new JSON object.

Example starting object:

```<code>[{
  "id" : 12345,
  "size" : 40,
  "shape": {
     "colour" : 'yellow',
     "dimension" : '2D'
  }
},
{
  "id" : 12346,
  "size" : 50,
  "shape": {
     "colour" : 'blue',
     "dimension" : '3D'
  }
}]
</code>```

What I need it to look like:

```<code>[{
  "id" : 12345,
  "size" : 40,
  "shape__colour": 'yellow',
  "shape__dimension" : '2D;'
  }
},
{
  "id" : 12346,
  "size" : 50,
  "shape__colour": 'blue',
  "shape__dimension" : '3D'
  }
}]
</code>```

Other examples of object flattening functions that I've come across seem to produce a single level array (removing the objects altogether), whereas I need to keep the individual objects, but for the data inside them to be on one level.

Any help would be greatly appreciated!

答:
You can use map to return a new array with the flattened shape properties:

```<code>let result = arr.map(({id, size, shape}) => {
  return {
    id,
    size,
    shape_colour: shape.colour,
    shape_dimension: shape.dimension
  }
});
</code>```

Note: you can also destructure the shape object in the arguments list:

```<code>let result = arr.map(({
  id,
  size,
  shape: { colour: shape_colour, dimension: shape_dimension }
}) => {
  return {
    id,
    size,
    shape_colour,
    shape_dimension,
  }
});
</code>```

Body:
I have a JavaScript object that I receive from an API that I cannot modify. I would like to use this data within a tool, but the tool only accepts values stored on the root level of the object e.g. I cannot use dot notation to access the value of a key a level down.

Based on the example below, I'd like to be able to access shape.colour, but by referencing something like shape__colour instead, from a new JSON object.

Example starting object:

[{
  "id" : 12345,
  "size" : 40,
  "shape": {
     "colour" : 'yellow',
     "dimension" : '2D'
  }
},
{
  "id" : 12346,
  "size" : 50,
  "shape": {
     "colour" : 'blue',
     "dimension" : '3D'
  }
}]

What I need it to look like:

[{
  "id" : 12345,
  "size" : 40,
  "shape__colour": 'yellow',
  "shape__dimension" : '2D;'
  }
},
{
  "id" : 12346,
  "size" : 50,
  "shape__colour": 'blue',
  "shape__dimension" : '3D'
  }
}]

Other examples of object flattening functions that I've come across seem to produce a single level array (removing the objects altogether), whereas I need to keep the individual objects, but for the data inside them to be on one level.

Any help would be greatly appreciated!

Body:
You can use map to return a new array with the flattened shape properties:

let result = arr.map(({id, size, shape}) => {
  return {
    id,
    size,
    shape_colour: shape.colour,
    shape_dimension: shape.dimension
  }
});

Note: you can also destructure the shape object in the arguments list:

let result = arr.map(({
  id,
  size,
  shape: { colour: shape_colour, dimension: shape_dimension }
}) => {
  return {
    id,
    size,
    shape_colour,
    shape_dimension,
  }
});


问:
Visual Studio 2010 - Add New Connection (SQL) as a different Windows Authenticated user
Here is my situation.

Domain Name: myDomain
user:   bob

I want to create a connection to a SQL server in myDomain from VS Studio 2010 as a different Windows user (not SQL Authentication)

My SQL admins will only build a user id myDomain\AppUser

Is there a way to specify a different user/pwd as a Windows authenticated ?

TIA.

Ralph

答: The shellrunas tool from sysinternals (http://technet.microsoft.com/en-us/sysinternals/cc300361) works very well for this purpose.  You don't even need to be in the same domain as the target server.  Just pass in the credentials (i.e. username and password) and you should be good to go.</p>

ContentLicense: CC BY-SA 2.5


问:
Laravel 5.5 three table join
Edit: I am using API routes, so i have no views and such

I have a database like this

```<code>User:
   id
   name

card:
   id
   card_number
   user_id

swipe:
   id
   time
   card_number
</code>```

the relationships go as followed  user has one card one card has many swipe

the joins would be as such

```<code>user.id = card.user_id
card.card_number = swipe.card_number
</code>```

In Larvel i have 3 models.

```<code>user
card
swipe
</code>```

user Model

```<code>class user extends Model
{

    public function card()
    {
        return $this->hasOne('App\card','user_id','id');
    }

}
</code>```

in a controller if i do

```<code>$model = user::with('card')->get();
</code>```

i get the card data joined with the user data as expected.

```<code>class card extends Model
{

    public function person()
    {
       return $this->belongsTo('App\user');
    }

    public function swipe(){
        return $this->hasMany('App\swipe','card_number','card_number');
    }
}
</code>```

if i now do

$model = user::with('card.swipe')->get();

which i would expect to return all the users with their cards, and swipes associated to that card.

However what i get is

500 internal server error

What am i doing wrong here?

答:
You should be able to extract your data in your controller like this:

```<code>return user::with(['card' => function($query) {
   $query->with('swipe');
}])->get();
</code>```

Make sure your swipe model "belongsTo('App\card')".

Title: Laravel 5.5 three table join

Body:
Edit: I am using API routes, so i have no views and such

I have a database like this

User:
   id
   name

card:
   id
   card_number
   user_id

swipe:
   id
   time
   card_number

the relationships go as followed  user has one card one card has many swipe

the joins would be as such

user.id = card.user_id
card.card_number = swipe.card_number

In Larvel i have 3 models.

user
card
swipe

user Model

class user extends Model
{

    public function card()
    {
        return $this->hasOne('App\card','user_id','id');
    }

}

in a controller if i do

$model = user::with('card')->get();

i get the card data joined with the user data as expected.

class card extends Model
{

    public function person()
    {
       return $this->belongsTo('App\user');
    }

    public function swipe(){
        return $this->hasMany('App\swipe','card_number','card_number');
    }
}

if i now do

$model = user::with('card.swipe')->get();

which i would expect to return all the users with their cards, and swipes associated to that card.

However what i get is

500 internal server error

What am i doing wrong here?

Body:
You should be able to extract your data in your controller like this:

return user::with(['card' => function($query) {
   $query->with('swipe');
}])->get();

Make sure your swipe model "belongsTo('App\card')".


问:
Android Studio connecting to localhost in mobile
I just wanted to ask how to connect to the localhost when the app is installed in mobile? I tried installing the apk of the android app in my mobile phone instead of the emulator of android studio. My app has a login and register activity. In the emulator, I'm able to register and login while I cannot register and login using my phone. Thanks in advance for the answer!</p>

答:
There are a lot of answers exist, but in simple follow the steps below.

First try to connect both your pc and mobile devices in the same network.

Then find the ip of your pc (run ipconfig in command prompt if you are using a pc).

Place this ip as your base url in your app and use register/login  endpoints as per your need.

For eg: http://your.ip.here/register.php  like this > (http://192.168.0.2/register.php)

Now run the app, it'll connect to the above said ip.


问:
Create a python dictionary from a list
I'm trying to create a dictionary from a list in python. I'm creating  alist from a .txt fril in the same directory as the .py file. But I don't understand how I create a dictionary without manually assigning a key to every value?

```<code>l = open ("Luther_King.txt").read()
words = l.split( )
print (words)
</code>```

The print statement is just to check if it did in fact split the string into a list. Am I going to need to manually assign a key for every word or can I generate one somehow?

答:
I am going to take a wild guess- and suggest you use range of the size of your list to generate keys.Then zip them together,you'll have your dictionary!!

```<code>#Your original list
['Jack', 'Luther', 'Dima', 'Vijay']

#Generate another list,which will be your keys
key_list=range(1,5,1)

newdict = dict(zip(key_list, words))

#This is how new dict would look
{1: 'Jack', 2: 'Luther', 3: 'Dima', 4: 'Vijay'}
</code>```

Title: Create a python dictionary from a list

Body:
I'm trying to create a dictionary from a list in python. I'm creating  alist from a .txt fril in the same directory as the .py file. But I don't understand how I create a dictionary without manually assigning a key to every value?

l = open ("Luther_King.txt").read()
words = l.split( )
print (words)

The print statement is just to check if it did in fact split the string into a list. Am I going to need to manually assign a key for every word or can I generate one somehow?

Body:
I am going to take a wild guess- and suggest you use range of the size of your list to generate keys.Then zip them together,you'll have your dictionary!!

#Your original list
['Jack', 'Luther', 'Dima', 'Vijay']

#Generate another list,which will be your keys
key_list=range(1,5,1)

newdict = dict(zip(key_list, words))

#This is how new dict would look
{1: 'Jack', 2: 'Luther', 3: 'Dima', 4: 'Vijay'}


问:
Programmatically go back to the previous fragment in the backstack
Say I have an activity that has fragments added programmatically:

```<code>private void animateToFragment(Fragment newFragment, String tag) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container, newFragment, tag);
    ft.addToBackStack(null);
    ft.commit();
}
</code>```

What is the best way to return to the previous fragment that was visible?

I found Trigger back-button functionality on button click in Android but I'm thinking simulating a back key event isn't the right way to go about it (and I can't get it to work either):

```<code>dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
</code>```

Calling finish() just closes the activity which I'm not interested in.

Is there a better way to go about this?

答:
This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.

On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !

Inside activities on back pressed put this:

```<code>Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");

if (home instanceof FragmentDetailedPizza && home.isVisible()) {
    if (getFragmentManager().getBackStackEntryCount() != 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
} else {
    //Primary fragment
    moveTaskToBack(true);
}
</code>```

And launch the other fragment like this:

```<code>Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, someFragment, "DetailedPizza");
transaction.addToBackStack("DetailedPizza");
transaction.commit();
</code>```

Body:
Say I have an activity that has fragments added programmatically:

private void animateToFragment(Fragment newFragment, String tag) {
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container, newFragment, tag);
    ft.addToBackStack(null);
    ft.commit();
}

What is the best way to return to the previous fragment that was visible?

I found Trigger back-button functionality on button click in Android but I'm thinking simulating a back key event isn't the right way to go about it (and I can't get it to work either):

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));

Calling finish() just closes the activity which I'm not interested in.

Is there a better way to go about this?

Body:
This solution works perfectly for bottom bar based fragment navigation when you want to close the app when back pressed in primary fragment.

On the other hand when you are opening the secondary fragment (fragment in fragment) which is defined as "DetailedPizza" in my code it will return the previous state of primary fragment. Cheers !

Inside activities on back pressed put this:

Fragment home = getSupportFragmentManager().findFragmentByTag("DetailedPizza");

if (home instanceof FragmentDetailedPizza && home.isVisible()) {
    if (getFragmentManager().getBackStackEntryCount() != 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
} else {
    //Primary fragment
    moveTaskToBack(true);
}

And launch the other fragment like this:

Fragment someFragment = new FragmentDetailedPizza();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container_body, someFragment, "DetailedPizza");
transaction.addToBackStack("DetailedPizza");
transaction.commit();


问:
LINQ Query to search for users with partial name
I have this SQL query:

```<code>SELECT
    *
FROM
    employeeTable
WHERE
    (
    concat(first_name, ' ', last_name) like concat('%', replace(@MatchString, ' ', '%'), '%')
        or
    concat(last_name, ' ', first_name) like concat('%', replace(@MatchString, ' ', '%'), '%')
    )
</code>```

It works perfectly by searching both name and last name with partial values., by searching users with partial strings. So for example:

"ric jon" will find Rick Jones, Richard Jonesy, and Jonathan Prichter.

I have the following Linq Query, using Entity Framework:

```<code>from employee in context.Employee
                    where employee.first_name.Contains(matchString)
                    || employee.last_name.Contains(matchString)
                    select employee
</code>```

But the string "ric jon" does not find anything.

I can't seem to make that linq query work the same as the SQL query.

答:
That SQL wouldn't in fact find those records you sampled with the given "ric jon". What you are asking for is a special filter which IMHO requires a function that is not natively supported by the backend (you didn't specify your backend but anyway at least I don't know a backend that would support this natively). Something like this would work (note that you are getting the Employee records to local, this is not done at backend level):

```<code>Func<Employee, string[], bool> match = (emp, _parts) => {
     return
     ((emp.FirstName.IndexOf(_parts[0],StringComparison.CurrentCultureIgnoreCase  ) != -1) &&
     (_parts.Length == 1 || emp.LastName.IndexOf(_parts[1], StringComparison.CurrentCultureIgnoreCase) != -1)) ||
     ((_parts.Length == 1 || emp.FirstName.IndexOf(_parts[1], StringComparison.CurrentCultureIgnoreCase) != -1) &&
     (emp.LastName.IndexOf(_parts[0], StringComparison.CurrentCultureIgnoreCase) != -1));
};

string search = "ric jon";
var result = context.Employee.AsEnumerable()
              .Where(n => match(n, search.Split()));
</code>```

Update:

You can use this one which would be supported by many backends:

```<code>string search = "ric jon";
string[] parts = search.ToLowerInvariant().Split();
string p1 = parts.Length < 1 ? "" :parts[0];
string p2 = parts.Length < 2 ? "" :parts[1];

var result = context.Employee.Where(n =>
    ((n.FirstName.ToLowerInvariant().Contains(p1) &&
     n.LastName.ToLowerInvariant().Contains(p2))) ||
     ((n.FirstName.ToLowerInvariant().Contains(p2) &&
     n.LastName.ToLowerInvariant().Contains(p1))));
</code>```

Body:
I have this SQL query:

SELECT
    *
FROM
    employeeTable
WHERE
    (
    concat(first_name, ' ', last_name) like concat('%', replace(@MatchString, ' ', '%'), '%')
        or
    concat(last_name, ' ', first_name) like concat('%', replace(@MatchString, ' ', '%'), '%')
    )

It works perfectly by searching both name and last name with partial values., by searching users with partial strings. So for example:

"ric jon" will find Rick Jones, Richard Jonesy, and Jonathan Prichter.

I have the following Linq Query, using Entity Framework:

from employee in context.Employee
                    where employee.first_name.Contains(matchString)
                    || employee.last_name.Contains(matchString)
                    select employee

But the string "ric jon" does not find anything.

I can't seem to make that linq query work the same as the SQL query.

Body:
That SQL wouldn't in fact find those records you sampled with the given "ric jon". What you are asking for is a special filter which IMHO requires a function that is not natively supported by the backend (you didn't specify your backend but anyway at least I don't know a backend that would support this natively). Something like this would work (note that you are getting the Employee records to local, this is not done at backend level):

Func<Employee, string[], bool> match = (emp, _parts) => {
     return
     ((emp.FirstName.IndexOf(_parts[0],StringComparison.CurrentCultureIgnoreCase  ) != -1) &&
     (_parts.Length == 1 || emp.LastName.IndexOf(_parts[1], StringComparison.CurrentCultureIgnoreCase) != -1)) ||
     ((_parts.Length == 1 || emp.FirstName.IndexOf(_parts[1], StringComparison.CurrentCultureIgnoreCase) != -1) &&
     (emp.LastName.IndexOf(_parts[0], StringComparison.CurrentCultureIgnoreCase) != -1));
};

string search = "ric jon";
var result = context.Employee.AsEnumerable()
              .Where(n => match(n, search.Split()));

Update:

You can use this one which would be supported by many backends:

string search = "ric jon";
string[] parts = search.ToLowerInvariant().Split();
string p1 = parts.Length < 1 ? "" :parts[0];
string p2 = parts.Length < 2 ? "" :parts[1];

var result = context.Employee.Where(n =>
    ((n.FirstName.ToLowerInvariant().Contains(p1) &&
     n.LastName.ToLowerInvariant().Contains(p2))) ||
     ((n.FirstName.ToLowerInvariant().Contains(p2) &&
     n.LastName.ToLowerInvariant().Contains(p1))));


问:
Unable to throw error in angular js promise
I have an as promise as :

```<code>try {
   myPromise().then(function(){
       console.log("ok");
     }, function(err) { throw err; });
} catch(e) {
    console.log("error");
}
</code>```

now my control goes to the function(err) and it throws the error but the error is not caught in catch().

答:
You have two options:

1) Use Promise.catch:

myPromise().then(function(){
       console.log("ok");
     }, function(err) { throw err; })
     .catch(function(err) { console.log("error"); });
```

<p><strong>2) If you have transpiler use async/await:</strong></p>

<pre class="lang-ts prettyprint-override"><code>async function parentFunction() {
  try {
    await myPromise();
    console.log("ok");
  }
  catch (e) {
    console.log("error");
  }
}
</code>```

Body:
I have an as promise as :

try {
   myPromise().then(function(){
       console.log("ok");
     }, function(err) { throw err; });
} catch(e) {
    console.log("error");
}

now my control goes to the function(err) and it throws the error but the error is not caught in catch().

Body:
You have two options:

1) Use Promise.catch:

myPromise().then(function(){
       console.log("ok");
     }, function(err) { throw err; })
     .catch(function(err) { console.log("error"); });

2) If you have transpiler use async/await:

async function parentFunction() {
  try {
    await myPromise();
    console.log("ok");
  }
  catch (e) {
    console.log("error");
  }
}


问:
(Spring) Can I use dependency injection inside a loop?
I am currently working on a Spring Boot application that allows users to save categories into a database. I can get my code to "work", however, I think it limits the amount of testing I can do, hence my question.

The controller receives a list of categories. The controller iterates over these categories, validates them and depending on whether they are valid, they are saved to a database. The controller finally returns a list of messages, such that the recipient can identify which category has been accepted or rejected, etc.

I have a list of model messages (List), which upon each iteration, the controller instantiates a new model message (new ModelMessage()) and eventually adds it to the List. Is there a way to inject a new ModelMessage upon each iteration or do I need to use the new keyword? If I do use the new keyword, I feel like this is limiting my testability/tightly coupling my controller to the model message.

The controller:

```<code>@PostMapping("/category")
    public String saveCategoryModelToDatabase(@RequestBody CategoryModelWrapper categoryModelWrapper){
        List<CategoryModel> categoryModelList = categoryModelWrapper.getCategoryModelList();
        modelMessageList.clear();

        for(CategoryModel categoryModel : categoryModelList){
            //Resetting model
            modelMessage = new ModelMessage(); //This tightly couples my method to the ModelMessage class, which is bad for testing?
            //@Autowired modelMessage; <-- something like this? Inject a new ModelMessage with each iteration.
            modelMessage.setName(categoryModel.getName());

            //Resetting categoryModelErrors
            Errors categoryModelErrors = new BeanPropertyBindingResult(categoryModel, "categoryModel");
            categoryModelValidator.validate(categoryModel, categoryModelErrors);

            if(categoryModelErrors.hasErrors()){
                modelMessage.setStatus(ModelMessageStatusEnum.REJECTED);
                modelMessage.setReason(MODEL_MESSAGE_0004);
            }

            if(categoryModelService.save(categoryModel)){
                modelMessage.setStatus(ModelMessageStatusEnum.ACCEPTED);
            }
            else{
                modelMessage.setStatus(ModelMessageStatusEnum.REJECTED);
                modelMessage.setReason(MODEL_MESSAGE_0005);
            }
            modelMessageList.add(modelMessage);
        }

        return gson.toJson(modelMessageList);
    }
</code>```

An example of the response to the recipient:

```<code>[{"name":"Arts","status":"ACCEPTED"},{"name":"Business","status":"ACCEPTED"},{"name":"Gaming","status":"ACCEPTED"},{"name":"Deals","status":"REJECTED","reason":"Category rejected because of an unexpected exception, i.e. possibly due to duplicate keys."}]
</code>```

Thanks for any help :)

答:
I think you can create new ModelMessages in your Controller, it's only a data object and not a service bean.
A junit can check the result of the method.

But if you really want to use Spring, I would look at the FactoryBean...

Example:

```<code>public class ModelMessage {
  String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

@Component
public class ModelMessageFactory implements FactoryBean<ModelMessage> {

  @Override
  public ModelMessage getObject() throws Exception {
    return new ModelMessage();
  }

  @Override
  public Class<?> getObjectType() {
    return ModelMessage.class;
  }
}

@RunWith(SpringRunner.class)
@SpringBootTest
@SpringJUnitConfig
public class ModelMessageFactoryTest {

  @Autowired
  private ModelMessageFactory messageFactory;

  @Test
  public void testGetObject() throws Exception {

    assertNotNull("Factory is null", messageFactory);
    IModelMessage modelMessage1 = messageFactory.getObject();
    IModelMessage modelMessage2 = messageFactory.getObject();

    assertNotEquals("error object is equal", System.identityHashCode(modelMessage1),
        System.identityHashCode(modelMessage2));
  }

  @Test
  public void testGetObjectType() throws Exception {
    assertEquals(ModelMessage.class, messageFactory.getObjectType());
  }
}
</code>```

Body:
I am currently working on a Spring Boot application that allows users to save categories into a database. I can get my code to "work", however, I think it limits the amount of testing I can do, hence my question.

The controller receives a list of categories. The controller iterates over these categories, validates them and depending on whether they are valid, they are saved to a database. The controller finally returns a list of messages, such that the recipient can identify which category has been accepted or rejected, etc.

I have a list of model messages (List), which upon each iteration, the controller instantiates a new model message (new ModelMessage()) and eventually adds it to the List. Is there a way to inject a new ModelMessage upon each iteration or do I need to use the new keyword? If I do use the new keyword, I feel like this is limiting my testability/tightly coupling my controller to the model message.

The controller:

@PostMapping("/category")
    public String saveCategoryModelToDatabase(@RequestBody CategoryModelWrapper categoryModelWrapper){
        List<CategoryModel> categoryModelList = categoryModelWrapper.getCategoryModelList();
        modelMessageList.clear();

        for(CategoryModel categoryModel : categoryModelList){
            //Resetting model
            modelMessage = new ModelMessage(); //This tightly couples my method to the ModelMessage class, which is bad for testing?
            //@Autowired modelMessage; <-- something like this? Inject a new ModelMessage with each iteration.
            modelMessage.setName(categoryModel.getName());

            //Resetting categoryModelErrors
            Errors categoryModelErrors = new BeanPropertyBindingResult(categoryModel, "categoryModel");
            categoryModelValidator.validate(categoryModel, categoryModelErrors);

            if(categoryModelErrors.hasErrors()){
                modelMessage.setStatus(ModelMessageStatusEnum.REJECTED);
                modelMessage.setReason(MODEL_MESSAGE_0004);
            }

            if(categoryModelService.save(categoryModel)){
                modelMessage.setStatus(ModelMessageStatusEnum.ACCEPTED);
            }
            else{
                modelMessage.setStatus(ModelMessageStatusEnum.REJECTED);
                modelMessage.setReason(MODEL_MESSAGE_0005);
            }
            modelMessageList.add(modelMessage);
        }

        return gson.toJson(modelMessageList);
    }

An example of the response to the recipient:

[{"name":"Arts","status":"ACCEPTED"},{"name":"Business","status":"ACCEPTED"},{"name":"Gaming","status":"ACCEPTED"},{"name":"Deals","status":"REJECTED","reason":"Category rejected because of an unexpected exception, i.e. possibly due to duplicate keys."}]

Thanks for any help :)

Body:
I think you can create new ModelMessages in your Controller, it's only a data object and not a service bean.
A junit can check the result of the method.

But if you really want to use Spring, I would look at the FactoryBean...

Example:

public class ModelMessage {
  String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
}

@Component
public class ModelMessageFactory implements FactoryBean<ModelMessage> {

  @Override
  public ModelMessage getObject() throws Exception {
    return new ModelMessage();
  }

  @Override
  public Class<?> getObjectType() {
    return ModelMessage.class;
  }
}

@RunWith(SpringRunner.class)
@SpringBootTest
@SpringJUnitConfig
public class ModelMessageFactoryTest {

  @Autowired
  private ModelMessageFactory messageFactory;

  @Test
  public void testGetObject() throws Exception {

    assertNotNull("Factory is null", messageFactory);
    IModelMessage modelMessage1 = messageFactory.getObject();
    IModelMessage modelMessage2 = messageFactory.getObject();

    assertNotEquals("error object is equal", System.identityHashCode(modelMessage1),
        System.identityHashCode(modelMessage2));
  }

  @Test
  public void testGetObjectType() throws Exception {
    assertEquals(ModelMessage.class, messageFactory.getObjectType());
  }
}


问:
What happens if we define wrong flag for -mfpu?
For example, if I have a chip -mcpu=cortex-a7 , I should define -mfpu=neon-vfpv4 , not -mfpu=neon . However, I'm wondering what will happen if I define -mfpu=neon on Cortex-A7? Will it just ignore the flag and don't do the SIMD, or what will it do with the wrong flag like that?

答:
It will use an older set of NEON instructions (-mfpu=neon is for selecting the NEON instructions that are available on the Cortex-A8 core). For example, it will not include the VFMA instructions.

Note that from GCC 8 (still in development) you will be able to just use -mfpu=auto or leave out the -mfpu entirely and have the compiler pick the optimal FPU setting for the -mcpu option you selected


问:
how to get the actual url in php while all pages are routing through index.php in MVC frameworks
When routing, all the php scripts request_uri showing only index.php.

I want to find the actual uri instead of index.php.

So,is there any php functions or variables that helps in getting the actual url.

I know they are different ways of getting the url for different frameworks but i want to know solution that works for every framework

答:
Since you stated that you are using laravel, the solution below only works for this particular framework.

```<code>$current = url()->current(); // Returns the current url
</code>```

If you need to pass parameters, getting the name of the route and building the url based on it works fine:

```<code>$current = URL::action(Route::currentRouteName(), ['arg' => 'value']); // Returns the current url and assign arguments to it
</code>```

Body:
Since you stated that you are using laravel, the solution below only works for this particular framework.

$current = url()->current(); // Returns the current url

If you need to pass parameters, getting the name of the route and building the url based on it works fine:

$current = URL::action(Route::currentRouteName(), ['arg' => 'value']); // Returns the current url and assign arguments to it


问:
finding the largest binary number from a range of cells
I have a data of some binary numbers in few range of cells, from A2 to A8, B2 to B8, and so on, till G column.
Now, I want to check the largest binary number from the above Rows and paste it to the cell, two row below the last used range. (i.e., Largest binary number from Row A to be paste in A10, and so on).
I am not finding any function which can find the value of binary numbers, and the code which I ran finds out the max number considering those as natural numbers.
Your help will be appreciated.
Thank You!</p>

答:
Assuming your binary values are text strings this formula converts the values to numbers, finds the MAX and then converts back to a text string

=TEXT(MAX(A2:A8+0),"00000")

confirmed with CTRL+SHIFT+ENTER

or you can use this version which finds the max using AGGREGATE function and doesn't require "array entry"

=DEC2BIN(AGGREGATE(14,6,BIN2DEC(A2:A8+0),1))


问:
How to make a pseudo element same height and width in pure CSS?
The .speech height may vary therefore looking for solution to make .speech::after's width same as .speech's height.

ideal result

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div></code>```

答:
You don't necessarily need pseudo elements for this, as long as you use CSS gradients, since all browsers that support gradients also support multiple backgrounds:

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background: linear-gradient(tomato,tomato),
              linear-gradient(to top right, tomato 49%,transparent 51%),
              linear-gradient(to bottom right, tomato 49%,transparent 51%);
  background-size: calc(100% - 30px) 100%, 30px 50%, 30px 50%;
  background-position: 0 0, 100% 0, 100% 100%;
  background-repeat: no-repeat;
  color: white;
  border: 1px solid;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div></code>```

Body:
The .speech height may vary therefore looking for solution to make .speech::after's width same as .speech's height.

ideal result

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background-color: tomato;
  color: white;
  border: 1px solid;
  position: relative;
}

.speech::after {
  content: '';
  position: absolute;
  top: 0;
  left: 100%;
  border: 3px solid deepskyblue;
  height: 100%;
  padding-left: 50%;
  background: linear-gradient(45deg, transparent 50%, green 0%);
  transform: translateX(-50%) rotate(45deg);
}

Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.

Body:
You don't necessarily need pseudo elements for this, as long as you use CSS gradients, since all browsers that support gradients also support multiple backgrounds:

body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.speech {
  width: 250px;
  padding: 1rem;
  background: linear-gradient(tomato,tomato),
              linear-gradient(to top right, tomato 49%,transparent 51%),
              linear-gradient(to bottom right, tomato 49%,transparent 51%);
  background-size: calc(100% - 30px) 100%, 30px 50%, 30px 50%;
  background-position: 0 0, 100% 0, 100% 100%;
  background-repeat: no-repeat;
  color: white;
  border: 1px solid;
  position: relative;
}

<div class="speech">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facilis minima possimus, maxime, fugit dolorum optio, tempora et doloribus doloremque ullam inventore repellendus veniam modi quasi iusto numquam amet eos! Exercitationem.</div>


问:
How to open a pyqt5 application from another pyqt5 application?

Filename : login.py

```<code># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_login(object):
    key=-1
    def overall_coordinator_clicked(self):
                self.overall_coordinator.setStyleSheet("border-bottom:3px solid red;\n"
"border-top:3px solid red;\n")
                self.coordinator.setStyleSheet("border:2px solid white;")
                self.member.setStyleSheet("border:2px solid white;")
                self.volunteer.setStyleSheet("border:2px solid white;")
                key=0
    def coordinator_clicked(self):
                self.overall_coordinator.setStyleSheet("border:2px solid white;")
                self.coordinator.setStyleSheet("border-bottom:3px solid red;\n"
"border-top:3px solid red;\n")
                self.member.setStyleSheet("border:2px solid white;")
                self.volunteer.setStyleSheet("border:2px solid white;")
                key=1
    def member_clicked(self):
                self.overall_coordinator.setStyleSheet("border:2px solid white;")
                self.coordinator.setStyleSheet("border:2px solid white;")
                self.member.setStyleSheet("border-bottom:3px solid red;\n"
"border-top:3px solid red;\n")
                self.volunteer.setStyleSheet("border:2px solid white;")
                key=2
    def volunteer_clicked(self):
                self.overall_coordinator.setStyleSheet("border:2px solid white;")
                self.coordinator.setStyleSheet("border:2px solid white;")
                self.member.setStyleSheet("border:2px solid white;")
                self.volunteer.setStyleSheet("border-bottom:3px solid red;\n"
"border-top:3px solid red;\n")
                key=3
    #def login(self):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(923, 606)
        MainWindow.setMinimumSize(QtCore.QSize(923, 606))
        MainWindow.setMaximumSize(QtCore.QSize(923, 606))
        MainWindow.setAutoFillBackground(False)
        MainWindow.setStyleSheet("background:#1A237E;")
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.widget = QtWidgets.QWidget(self.centralWidget)
        self.widget.setGeometry(QtCore.QRect(330, 30, 231, 201))
        self.widget.setStyleSheet("border-image:url(\"techfusion_logo.png\");")
        self.widget.setObjectName("widget")
        self.login_btn = QtWidgets.QPushButton(self.centralWidget)
        self.login_btn.setGeometry(QtCore.QRect(350, 480, 200, 41))
        self.login_btn.setStyleSheet(" color:white;\n"
" background-color:#1A237E;\n"
" border-radius:20px;\n"
"font-weight:bold;\n"
"font-size:18px;\n"
"border : 2px solid white;\n"
"\n"
"")
        self.login_btn.setObjectName("login_btn")
        #self.login_btn.clicked.connect(self.login)
        self.login_password = QtWidgets.QLineEdit(self.centralWidget)
        self.login_password.setGeometry(QtCore.QRect(290, 420, 331, 25))
        self.login_password.setStyleSheet("border: 1px solid transparent;\n"
"border-bottom:2px solid white;\n"
"color:white;\n"
"background-color:transparent;")
        self.login_password.setText("")
        self.login_password.setEchoMode(QtWidgets.QLineEdit.Password)
        self.login_password.setObjectName("login_password")
        self.login_username = QtWidgets.QLineEdit(self.centralWidget)
        self.login_username.setGeometry(QtCore.QRect(290, 370, 331, 25))
        self.login_username.setStyleSheet("border: 1px solid transparent;\n"
"border-bottom:2px solid white;\n"
"background-color:transparent;\n"
"color:white;\n"
"")
        self.login_username.setObjectName("login_username")
        self.designation = QtWidgets.QGroupBox(self.centralWidget)
        self.designation.setGeometry(QtCore.QRect(100, 280, 701, 61))
        self.designation.setStyleSheet("color:white;\n"
"font-weight:bold;\n"
"border:0px solid transparent;")
        self.designation.setAlignment(QtCore.Qt.AlignCenter)
        self.designation.setObjectName("designation")
        self.overall_coordinator = QtWidgets.QPushButton(self.designation)
        self.overall_coordinator.setGeometry(QtCore.QRect(-10, 30, 181, 28))
        self.overall_coordinator.setStyleSheet("border: 2px solid white;\n"
"background-color:transparent;\n"
"font-weight:normal;\n"
"color:white;\n"
"")
        self.overall_coordinator.setObjectName("overall_coordinator")
#######overall_coordinator selected######
        self.overall_coordinator.clicked.connect(self.overall_coordinator_clicked)
#########################################
        self.coordinator = QtWidgets.QPushButton(self.designation)
        self.coordinator.setGeometry(QtCore.QRect(170, 30, 181, 28))
        self.coordinator.setStyleSheet("border: 2px solid white;\n"
"background-color:transparent;\n"
"font-weight:normal;\n"
"color:white;\n"
"")
        self.coordinator.setObjectName("coordinator")
#######overall_coordinator selected######
        self.coordinator.clicked.connect(self.coordinator_clicked)
#########################################
        self.member = QtWidgets.QPushButton(self.designation)
        self.member.setGeometry(QtCore.QRect(350, 30, 181, 28))
        self.member.setStyleSheet("border: 2px solid white;\n"
"background-color:transparent;\n"
"font-weight:normal;\n"
"color:white;\n"
"")
        self.member.setObjectName("member")
#######overall_coordinator selected######
        self.member.clicked.connect(self.member_clicked)
#########################################
        self.volunteer = QtWidgets.QPushButton(self.designation)
        self.volunteer.setGeometry(QtCore.QRect(530, 30, 181, 28))
        self.volunteer.setStyleSheet("border: 2px solid white;\n"
"background-color:transparent;\n"
"font-weight:normal;\n"
"color:white;\n"
"")
        self.volunteer.setObjectName("volunteer")
#######overall_coordinator selected######
        self.volunteer.clicked.connect(self.volunteer_clicked)
#########################################
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 923, 22))
        self.menuBar.setObjectName("menuBar")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Voyage"))
        self.login_btn.setText(_translate("MainWindow", "LOGIN"))
        self.login_username.setPlaceholderText(_translate("MainWindow", "Username"))
        self.login_password.setPlaceholderText(_translate("MainWindow", "Password"))
        self.designation.setTitle(_translate("MainWindow", "LOGIN AS"))
        self.overall_coordinator.setText(_translate("MainWindow", "Overall Coordinator"))
        self.coordinator.setText(_translate("MainWindow", "Coordinator"))
        self.member.setText(_translate("MainWindow", "Member"))
        self.volunteer.setText(_translate("MainWindow", "Volunteer"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_login()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

Filename : dashboard.py

```<code># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from login import Ui_login

class Ui_dashboard(object):
    #def member(self):
    #def team(self):
    #def log_out(self):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(923, 606)
        MainWindow.setMinimumSize(QtCore.QSize(923, 606))
        MainWindow.setMaximumSize(QtCore.QSize(923, 606))
        MainWindow.setAutoFillBackground(False)
        MainWindow.setStyleSheet("background:#1A237E;")
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.widget = QtWidgets.QWidget(self.centralWidget)
        self.widget.setGeometry(QtCore.QRect(340, 40, 231, 201))
        self.widget.setStyleSheet("border-image:url(\"techfusion_logo.png\");")
        self.widget.setObjectName("widget")
        self.member = QtWidgets.QPushButton(self.centralWidget)
        self.member.setGeometry(QtCore.QRect(360, 320, 200, 41))
        self.member.setStyleSheet(" color:white;\n"
" background-color:#1A237E;\n"
" border-radius:20px;\n"
"border : 2px solid white;\n"
"font-weight:bold;\n"
"\n"
"")
        self.member.setObjectName("member")
        self.team = QtWidgets.QPushButton(self.centralWidget)
        self.team.setGeometry(QtCore.QRect(360, 400, 200, 41))
        self.team.setStyleSheet(" color:white;\n"
" background-color:#1A237E;\n"
" border-radius:20px;\n"
"font-weight:bold;\n"
"border : 2px solid white;\n"
"\n"
"")
        self.team.setObjectName("team")
        self.logout = QtWidgets.QPushButton(self.centralWidget)
        self.logout.setGeometry(QtCore.QRect(820, 10, 89, 25))
        self.logout.setStyleSheet(" color:white;\n"
                                  " background-color:#1A237E;\n"
                                  " border-radius:20px;\n"
                                  "font-weight:bold;\n"
                                  "text-decoration:underline;\n"
                                  "font-size:15px;\n"
                                  "\n"
                                  "")
        self.logout.setObjectName("logout")
        #self.logout.clicked.connect(self.log_out)
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 923, 22))
        self.menuBar.setObjectName("menuBar")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Voyage"))
        self.member.setText(_translate("MainWindow", "MEMBER"))
        self.team.setText(_translate("MainWindow", "TEAM"))
        self.logout.setText(_translate("MainWindow", "LOGOUT"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_dashboard()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())
</code>```

There is QPushButton named "logout" in dashboard.py . What I want is that when I click logout button, The dashboard.py exits and login.py opens up. What code should I use in order to achieve this. I am stuck on this since past 2 days. Gone through many webpages but I wasn't able to do it. Any help would be appreciated.

答:
It is not advisable to modify the design generated by Qt Designer, it is appropriate to create a class that manages the design and implement the logic. As your goal is to close the current window and open another window by pressing the button, then we must use the clicked signal of the button and connect them to both tasks as shown below:

```<code>.
├── dashboard.py
├── login.py
└── main.py
</code>```

main.py

```<code>from PyQt5.QtWidgets import *
from login import Ui_login
from dashboard import Ui_dashboard

class Login(QMainWindow, Ui_login):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)

class Dashboard(QMainWindow, Ui_dashboard):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.logout.clicked.connect(self.close)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = Dashboard()
    l = Login()
    w.logout.clicked.connect(l.show)
    w.show()
    sys.exit(app.exec_())
</code>```

Body:
Filename : login.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_login(object):
    key=-1
    def overall_coordinator_clicked(self):
                self.overall_coordinator.setStyleSheet("border-bottom:3px solid red;\n"
"border-top:3px solid red;\n")
                self.coordinator.setStyleSheet("border:2px solid white;")
                self.member.setStyleSheet("border:2px solid white;")
                self.volunteer.setStyleSheet("border:2px solid white;")
                key=0
    def coordinator_clicked(self):
                self.overall_coordinator.setStyleSheet("border:2px solid white;")
                self.coordinator.setStyleSheet("border-bottom:3px solid red;\n"
"border-top:3px solid red;\n")
                self.member.setStyleSheet("border:2px solid white;")
                self.volunteer.setStyleSheet("border:2px solid white;")
                key=1
    def member_clicked(self):
                self.overall_coordinator.setStyleSheet("border:2px solid white;")
                self.coordinator.setStyleSheet("border:2px solid white;")
                self.member.setStyleSheet("border-bottom:3px solid red;\n"
"border-top:3px solid red;\n")
                self.volunteer.setStyleSheet("border:2px solid white;")
                key=2
    def volunteer_clicked(self):
                self.overall_coordinator.setStyleSheet("border:2px solid white;")
                self.coordinator.setStyleSheet("border:2px solid white;")
                self.member.setStyleSheet("border:2px solid white;")
                self.volunteer.setStyleSheet("border-bottom:3px solid red;\n"
"border-top:3px solid red;\n")
                key=3
    #def login(self):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(923, 606)
        MainWindow.setMinimumSize(QtCore.QSize(923, 606))
        MainWindow.setMaximumSize(QtCore.QSize(923, 606))
        MainWindow.setAutoFillBackground(False)
        MainWindow.setStyleSheet("background:#1A237E;")
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.widget = QtWidgets.QWidget(self.centralWidget)
        self.widget.setGeometry(QtCore.QRect(330, 30, 231, 201))
        self.widget.setStyleSheet("border-image:url(\"techfusion_logo.png\");")
        self.widget.setObjectName("widget")
        self.login_btn = QtWidgets.QPushButton(self.centralWidget)
        self.login_btn.setGeometry(QtCore.QRect(350, 480, 200, 41))
        self.login_btn.setStyleSheet(" color:white;\n"
" background-color:#1A237E;\n"
" border-radius:20px;\n"
"font-weight:bold;\n"
"font-size:18px;\n"
"border : 2px solid white;\n"
"\n"
"")
        self.login_btn.setObjectName("login_btn")
        #self.login_btn.clicked.connect(self.login)
        self.login_password = QtWidgets.QLineEdit(self.centralWidget)
        self.login_password.setGeometry(QtCore.QRect(290, 420, 331, 25))
        self.login_password.setStyleSheet("border: 1px solid transparent;\n"
"border-bottom:2px solid white;\n"
"color:white;\n"
"background-color:transparent;")
        self.login_password.setText("")
        self.login_password.setEchoMode(QtWidgets.QLineEdit.Password)
        self.login_password.setObjectName("login_password")
        self.login_username = QtWidgets.QLineEdit(self.centralWidget)
        self.login_username.setGeometry(QtCore.QRect(290, 370, 331, 25))
        self.login_username.setStyleSheet("border: 1px solid transparent;\n"
"border-bottom:2px solid white;\n"
"background-color:transparent;\n"
"color:white;\n"
"")
        self.login_username.setObjectName("login_username")
        self.designation = QtWidgets.QGroupBox(self.centralWidget)
        self.designation.setGeometry(QtCore.QRect(100, 280, 701, 61))
        self.designation.setStyleSheet("color:white;\n"
"font-weight:bold;\n"
"border:0px solid transparent;")
        self.designation.setAlignment(QtCore.Qt.AlignCenter)
        self.designation.setObjectName("designation")
        self.overall_coordinator = QtWidgets.QPushButton(self.designation)
        self.overall_coordinator.setGeometry(QtCore.QRect(-10, 30, 181, 28))
        self.overall_coordinator.setStyleSheet("border: 2px solid white;\n"
"background-color:transparent;\n"
"font-weight:normal;\n"
"color:white;\n"
"")
        self.overall_coordinator.setObjectName("overall_coordinator")
#######overall_coordinator selected######
        self.overall_coordinator.clicked.connect(self.overall_coordinator_clicked)
#########################################
        self.coordinator = QtWidgets.QPushButton(self.designation)
        self.coordinator.setGeometry(QtCore.QRect(170, 30, 181, 28))
        self.coordinator.setStyleSheet("border: 2px solid white;\n"
"background-color:transparent;\n"
"font-weight:normal;\n"
"color:white;\n"
"")
        self.coordinator.setObjectName("coordinator")
#######overall_coordinator selected######
        self.coordinator.clicked.connect(self.coordinator_clicked)
#########################################
        self.member = QtWidgets.QPushButton(self.designation)
        self.member.setGeometry(QtCore.QRect(350, 30, 181, 28))
        self.member.setStyleSheet("border: 2px solid white;\n"
"background-color:transparent;\n"
"font-weight:normal;\n"
"color:white;\n"
"")
        self.member.setObjectName("member")
#######overall_coordinator selected######
        self.member.clicked.connect(self.member_clicked)
#########################################
        self.volunteer = QtWidgets.QPushButton(self.designation)
        self.volunteer.setGeometry(QtCore.QRect(530, 30, 181, 28))
        self.volunteer.setStyleSheet("border: 2px solid white;\n"
"background-color:transparent;\n"
"font-weight:normal;\n"
"color:white;\n"
"")
        self.volunteer.setObjectName("volunteer")
#######overall_coordinator selected######
        self.volunteer.clicked.connect(self.volunteer_clicked)
#########################################
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 923, 22))
        self.menuBar.setObjectName("menuBar")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Voyage"))
        self.login_btn.setText(_translate("MainWindow", "LOGIN"))
        self.login_username.setPlaceholderText(_translate("MainWindow", "Username"))
        self.login_password.setPlaceholderText(_translate("MainWindow", "Password"))
        self.designation.setTitle(_translate("MainWindow", "LOGIN AS"))
        self.overall_coordinator.setText(_translate("MainWindow", "Overall Coordinator"))
        self.coordinator.setText(_translate("MainWindow", "Coordinator"))
        self.member.setText(_translate("MainWindow", "Member"))
        self.volunteer.setText(_translate("MainWindow", "Volunteer"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_login()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

Filename : dashboard.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created by: PyQt5 UI code generator 5.9
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets
from login import Ui_login

class Ui_dashboard(object):
    #def member(self):
    #def team(self):
    #def log_out(self):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(923, 606)
        MainWindow.setMinimumSize(QtCore.QSize(923, 606))
        MainWindow.setMaximumSize(QtCore.QSize(923, 606))
        MainWindow.setAutoFillBackground(False)
        MainWindow.setStyleSheet("background:#1A237E;")
        self.centralWidget = QtWidgets.QWidget(MainWindow)
        self.centralWidget.setObjectName("centralWidget")
        self.widget = QtWidgets.QWidget(self.centralWidget)
        self.widget.setGeometry(QtCore.QRect(340, 40, 231, 201))
        self.widget.setStyleSheet("border-image:url(\"techfusion_logo.png\");")
        self.widget.setObjectName("widget")
        self.member = QtWidgets.QPushButton(self.centralWidget)
        self.member.setGeometry(QtCore.QRect(360, 320, 200, 41))
        self.member.setStyleSheet(" color:white;\n"
" background-color:#1A237E;\n"
" border-radius:20px;\n"
"border : 2px solid white;\n"
"font-weight:bold;\n"
"\n"
"")
        self.member.setObjectName("member")
        self.team = QtWidgets.QPushButton(self.centralWidget)
        self.team.setGeometry(QtCore.QRect(360, 400, 200, 41))
        self.team.setStyleSheet(" color:white;\n"
" background-color:#1A237E;\n"
" border-radius:20px;\n"
"font-weight:bold;\n"
"border : 2px solid white;\n"
"\n"
"")
        self.team.setObjectName("team")
        self.logout = QtWidgets.QPushButton(self.centralWidget)
        self.logout.setGeometry(QtCore.QRect(820, 10, 89, 25))
        self.logout.setStyleSheet(" color:white;\n"
                                  " background-color:#1A237E;\n"
                                  " border-radius:20px;\n"
                                  "font-weight:bold;\n"
                                  "text-decoration:underline;\n"
                                  "font-size:15px;\n"
                                  "\n"
                                  "")
        self.logout.setObjectName("logout")
        #self.logout.clicked.connect(self.log_out)
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtWidgets.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 923, 22))
        self.menuBar.setObjectName("menuBar")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QtWidgets.QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Voyage"))
        self.member.setText(_translate("MainWindow", "MEMBER"))
        self.team.setText(_translate("MainWindow", "TEAM"))
        self.logout.setText(_translate("MainWindow", "LOGOUT"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_dashboard()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

There is QPushButton named "logout" in dashboard.py . What I want is that when I click logout button, The dashboard.py exits and login.py opens up. What code should I use in order to achieve this. I am stuck on this since past 2 days. Gone through many webpages but I wasn't able to do it. Any help would be appreciated.

Body:
It is not advisable to modify the design generated by Qt Designer, it is appropriate to create a class that manages the design and implement the logic. As your goal is to close the current window and open another window by pressing the button, then we must use the clicked signal of the button and connect them to both tasks as shown below:

.
├── dashboard.py
├── login.py
└── main.py

main.py

from PyQt5.QtWidgets import *
from login import Ui_login
from dashboard import Ui_dashboard

class Login(QMainWindow, Ui_login):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)

class Dashboard(QMainWindow, Ui_dashboard):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        self.setupUi(self)
        self.logout.clicked.connect(self.close)

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = Dashboard()
    l = Login()
    w.logout.clicked.connect(l.show)
    w.show()
    sys.exit(app.exec_())


问:
Camel case converter in an excel
I am trying to convert a field in an excel sheet (e.g. REC_LEN) to camel case. I am using this formula to do that

```<code>=LEFT(A1) & RIGHT(SUBSTITUTE(PROPER(A1),"_",""), LEN( SUBSTITUTE(A1,"_",""))-1)
</code>```

This is giving me results like RecLen. I want to convert my first letter to lowercase too (The expected output is recLen). Can somebody help me out with this? I am not too familiar with excel formulae. Not sure if this has been already asked before but any help is much appreciated.

答:
Try this:

```<code>=LOWER(LEFT(A1)) & MID(SUBSTITUTE(PROPER(A1),"_",""),2,LEN(A1))
</code>```

With Office 365 we can use:

```<code>=LET(
    rr,A1,
    x,TEXTSPLIT(rr,"_"),
    CONCAT(LOWER(TAKE(x,,1)),PROPER(DROP(x,,1))))
</code>```

Title: Camel case converter in an excel

Body:
I am trying to convert a field in an excel sheet (e.g. REC_LEN) to camel case. I am using this formula to do that

=LEFT(A1) & RIGHT(SUBSTITUTE(PROPER(A1),"_",""), LEN( SUBSTITUTE(A1,"_",""))-1)

This is giving me results like RecLen. I want to convert my first letter to lowercase too (The expected output is recLen). Can somebody help me out with this? I am not too familiar with excel formulae. Not sure if this has been already asked before but any help is much appreciated.

Body:
Try this:

=LOWER(LEFT(A1)) & MID(SUBSTITUTE(PROPER(A1),"_",""),2,LEN(A1))

With Office 365 we can use:

=LET(
    rr,A1,
    x,TEXTSPLIT(rr,"_"),
    CONCAT(LOWER(TAKE(x,,1)),PROPER(DROP(x,,1))))


问:
Mouse scroll wheel with selenium webdriver, on element without scrollbar?
I'm trying to drive part of a web map akin to Google Maps, where zoom in/out is done by scrolling while moused over. Ideally, I'd like to be able to do something like this:

```<code>someElement.scroll(-50)
</code>```

The closest methods I saw in the documentation were click and send_keys, but neither of those do scrolling. I've also tried sending scrolls to the page via Javascript, e.g. driver.execute_script("scroll(0,-50)") This doesn't seem to do anything though.

How can I do this?

答:
To reproduce/test a mouse wheel, you'll have to emit the mouseover, mousemove and wheel events to the top element with a script injection.

Here's a working example with Google Map:

```<code>from selenium import webdriver
from selenium.common.exceptions import WebDriverException

def wheel_element(element, deltaY = 120, offsetX = 0, offsetY = 0):
  error = element._parent.execute_script("""
    var element = arguments[0];
    var deltaY = arguments[1];
    var box = element.getBoundingClientRect();
    var clientX = box.left + (arguments[2] || box.width / 2);
    var clientY = box.top + (arguments[3] || box.height / 2);
    var target = element.ownerDocument.elementFromPoint(clientX, clientY);

    for (var e = target; e; e = e.parentElement) {
      if (e === element) {
        target.dispatchEvent(new MouseEvent('mouseover', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY}));
        target.dispatchEvent(new MouseEvent('mousemove', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY}));
        target.dispatchEvent(new WheelEvent('wheel',     {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY, deltaY: deltaY}));
        return;
      }
    }
    return "Element is not interactable";
    """, element, deltaY, offsetX, offsetY)
  if error:
    raise WebDriverException(error)

options = webdriver.ChromeOptions()
options.add_argument("--disable-infobars --disable-extensions --window-size=1366,768")
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.google.co.uk/maps")

# get element
elm = driver.find_element_by_css_selector("#scene > div.widget-scene > canvas")

# zoom in with mouse wheel
wheel_element(elm, -120)

# zoom out with mouse wheel
wheel_element(elm, 120)
</code>```

As an alternative you could send the zoom shortucts which are +/- with Google map:

# get element
elm = driver.find_element_by_css_selector("#scene > div.widget-scene > canvas")

# zoom in with shortcut
elm.send_keys("+")

# zoom out with shortcut
elm.send_keys("-")
```

Body:
I'm trying to drive part of a web map akin to Google Maps, where zoom in/out is done by scrolling while moused over. Ideally, I'd like to be able to do something like this:

someElement.scroll(-50)

The closest methods I saw in the documentation were click and send_keys, but neither of those do scrolling. I've also tried sending scrolls to the page via Javascript, e.g. driver.execute_script("scroll(0,-50)") This doesn't seem to do anything though.

How can I do this?

Body:
To reproduce/test a mouse wheel, you'll have to emit the mouseover, mousemove and wheel events to the top element with a script injection.

Here's a working example with Google Map:

from selenium import webdriver
from selenium.common.exceptions import WebDriverException

def wheel_element(element, deltaY = 120, offsetX = 0, offsetY = 0):
  error = element._parent.execute_script("""
    var element = arguments[0];
    var deltaY = arguments[1];
    var box = element.getBoundingClientRect();
    var clientX = box.left + (arguments[2] || box.width / 2);
    var clientY = box.top + (arguments[3] || box.height / 2);
    var target = element.ownerDocument.elementFromPoint(clientX, clientY);

    for (var e = target; e; e = e.parentElement) {
      if (e === element) {
        target.dispatchEvent(new MouseEvent('mouseover', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY}));
        target.dispatchEvent(new MouseEvent('mousemove', {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY}));
        target.dispatchEvent(new WheelEvent('wheel',     {view: window, bubbles: true, cancelable: true, clientX: clientX, clientY: clientY, deltaY: deltaY}));
        return;
      }
    }
    return "Element is not interactable";
    """, element, deltaY, offsetX, offsetY)
  if error:
    raise WebDriverException(error)

options = webdriver.ChromeOptions()
options.add_argument("--disable-infobars --disable-extensions --window-size=1366,768")
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.google.co.uk/maps")

# get element
elm = driver.find_element_by_css_selector("#scene > div.widget-scene > canvas")

# zoom in with mouse wheel
wheel_element(elm, -120)

# zoom out with mouse wheel
wheel_element(elm, 120)

As an alternative you could send the zoom shortucts which are +/- with Google map:

# get element
elm = driver.find_element_by_css_selector("#scene > div.widget-scene > canvas")

# zoom in with shortcut
elm.send_keys("+")

# zoom out with shortcut
elm.send_keys("-")


问:
Azure API Management: Reload swagger file
I am creating a new API in API management by using

PUT https://management.azure.com/subscriptions/d00e3aca-15b5-4f4b-8204-1ded8025c65f/resourceGroups/Default-Web-NorthEurope/providers/Microsoft.ApiManagement/service/idfy-test/apis/demoapi2?api-version=2017-03-01

{
  "properties": {
    "contentFormat": "swagger-link-json",
    "contentValue": "http://demoapi2.azurewebsites.net/swagger/v1/swagger.json",
    "path": "demoapi2",
    }
}

PUT https://management.azure.com/subscriptions/d00e3aca-15b5-4f4b-8204-1ded8025c65f/resourceGroups/Default-Web-NorthEurope/providers/Microsoft.ApiManagement/service/idfy-test/products/free/apis/demoapi2?api-version=2017-03-01

(the "free" product is a product which does not require subscriptions)
GET http://idfy-test.azure-api.net/demoapi2/api/Values/
works perfect

I then try to make a new revision (to reflect a updated swaggerfile)
https://management.azure.com/subscriptions/d00e3aca-15b5-4f4b-8204-1ded8025c65f/resourceGroups/Default-Web-NorthEurope/providers/Microsoft.ApiManagement/service/idfy-test/apis/demoapi2;rev=2?api-version=2017-03-01
{
  "properties": {
    "contentFormat": "swagger-link-json",
    "contentValue": "http://demoapi2.azurewebsites.net/swagger/v1/swagger.json",
    "path": "demoapi2",
    }
}

The problem now is when calling
GET http://idfy-test.azure-api.net/demoapi2;rev=2/api/Values/

I get the following errormessage;
{
    "statusCode": 401,
    "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API."
}

When trying to connect the revision2 to the same product as revision1, this doesnt seem to work.....

This problem does not occur when I try to create the new revision as a copy from rev=1; My problem is that I want to create a new revision from a updated swagger file, apply policies, and then make the new reivison the active one

Are there any other ways to get the API management to "reload" a updated swaggerfile, test the changes, and then flip revisions?

答:
{ “statusCode”: 401, “message”: “Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API.” }
This error occurs when you miss the subscription key in the header. Let’s jump into the developer portal to see how to get the subscription key. The link to the developer portal is on the upper right corner (or you can remove /admin from the URL) and it looks like:

The portal is by default visible to everyone who knows the URL. So it makes sense to customize it to your corporate identity. But let’s focus on the development stuff and let’s test our API. Go to “API” and select your API on the right side:

You can now select a method and try it with the “try it” button. It opens a screen which allows you to enter parameters and other stuff. There we can also see the subscription key (Ocp-Apim-Subscription-Key):

Press the send button and you will see the API call including the subscription key and also the result of the API call.

Reference: https://codehollow.com/2016/09/introduction-azure-api-management-part-1/.


问:
JPA/Hibernate Custom Queries with optional parameters
I have an Entity

```<code>@Entity
@Table(name = "EVENT")
public class Event {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @Column(name = "EVENT", columnDefinition="VARCHAR(100)", nullable = false)
    private String event;

    @Column(name = "DATE", columnDefinition="DATETIME", nullable = false)
    @Convert(converter = InstantConverter.class)
    private Instant date;
}
</code>```

And a SearchParams class where all of the fields are optional

```<code>public class SearchParams {
    private Long id;
    private Instant startDate;
    private Instant endDate;
    private String event;

    public Optional<Long> getID() {
        return Optional.ofNullable(id);
    }
    // ... Similar for other fields ...
}
</code>```

I would like to be able to search like:

```<code>public List<Event> search(SearchParams searchParams) {
    // Do something with Entity Manager/another hibernate class to create a custom query based off the search params.
    return events;
}
</code>```

What's the easiest way to achieve this in JPA? Or is this not the right framework to use?

I could always resort to sql string building but its not a nice way of doing it.

答:
As far as remember JPA has method where, which takes array of Predicates as parameter.

So what you could do is create dynamic list of predicates from your params and then pass it to your query.

so your code will be something like that

```<code>List<Predicate> predicates= new ArrayList<>();
if (!searchParams.getId().isEmpty()){
predicates.add(cb.equal(root.get("id"), searchParams.getId());
}
....
query.where(predicates.toArray(new Predicate[predicates.size()]));
</code>```

Body:
I have an Entity

@Entity
@Table(name = "EVENT")
public class Event {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @Column(name = "EVENT", columnDefinition="VARCHAR(100)", nullable = false)
    private String event;

    @Column(name = "DATE", columnDefinition="DATETIME", nullable = false)
    @Convert(converter = InstantConverter.class)
    private Instant date;
}

And a SearchParams class where all of the fields are optional

public class SearchParams {
    private Long id;
    private Instant startDate;
    private Instant endDate;
    private String event;

    public Optional<Long> getID() {
        return Optional.ofNullable(id);
    }
    // ... Similar for other fields ...
}

I would like to be able to search like:

public List<Event> search(SearchParams searchParams) {
    // Do something with Entity Manager/another hibernate class to create a custom query based off the search params.
    return events;
}

What's the easiest way to achieve this in JPA? Or is this not the right framework to use?

I could always resort to sql string building but its not a nice way of doing it.

Body:
As far as remember JPA has method where, which takes array of Predicates as parameter.

So what you could do is create dynamic list of predicates from your params and then pass it to your query.

so your code will be something like that

List<Predicate> predicates= new ArrayList<>();
if (!searchParams.getId().isEmpty()){
predicates.add(cb.equal(root.get("id"), searchParams.getId());
}
....
query.where(predicates.toArray(new Predicate[predicates.size()]));


问:
How to GRANT permissions to a SQL role to create and manage temp tables
I'd like to grant permissions to a SQL role to create a temp table #foo and grant permissions to do anything with that table (SELECT, INSERT and DELETE). How is it possible if the table #foo is not created (the user that belongs to this role will create and manage it)?

Thanks

NOTE: If possible, the solution should work with both SQL 2008 and SQL Azure.

答:
You can't:

Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.
link text


问:
Parse specific XML file into object
I want to deserialize XML file into object, but my XML looks like this

```<code><ALLObjects>
<object ID ="1">
    <param1>Clicks</param1>
    <param2>NONE</param2>
    <param3>example</param3>
    <param4>example23</param4>
    <param5>1</param5>
    <param6>1</param6>
</object>

<object ID ="2">
    <param1>Clicks</param1>
    <param2>NONE</param2>
    <param3>Example23</param3>
    <param4>Example 1</param4>
    <param5>10</param5>
    <param6>1</param6>
</object>

 //more objects

</ALLObjects>
</code>```

I have a model that contains all params (including the ID value). I want to load all the object into a list and make some changes and then save it into the same XML file. I know how it works when the XML is int this format

```<code><object >
<ID>1</ID>
<param1>Clicks</param1>
<param2>NONE</param2>
<param3>example</param3>
<param4>example23</param4>
<param5>1</param5>
<param6>1</param6>
</object>
</code>```

But I don't want to manually rewrite the whole file to load it into that format. I need a hint what is the best practice for this case. Maybe I need to load it into the JSON and then parse into the object?

@chade_ currently I try to use XmlSerializer, but I've got an error

```<code>InvalidOperationException: <achievements xmlns=''> was not expected
</code>```

my code: LoadingFromFile

```<code>  private void LoadData()
    {
        List<AchievementModel> models;

        using (var reader = new StreamReader("test.xml"))
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(List<AchievementModel>),
                new XmlRootAttribute("ALLObjects"));
            models = (List<AchievementModel>)deserializer.Deserialize(reader);
        }
    }

[System.Serializable, XmlRoot("ALLObjects")]
public class AchievementList
{
    public AchievementList() { Items = new List<AchievementModel>(); }
    [XmlElement("object")]
    public List<AchievementModel> Items { get; set; }
}

[System.Serializable, XmlType( "object ")]
public class AchievementModel
{
    public AchievementModel() { }

    [XmlElement("ID")]
    public int ID { get; set; }
    [XmlElement("param1")]
    public string Progress { get; set; }
    [XmlElement("param2")]
    public string Reward { get; set; }

    [XmlElement("param3")]
    public string Title { get; set; }
    [XmlElement("param4")]
    public string Description { get; set; }
    [XmlElement("param5")]
    public int param6{ get; set; }
    [XmlElement("param6")]
    public int AchievementAnimalSubtitle { get; set; }
}
}
</code>```

答:
If you want to load an attribute value instead of an element from your XML you need to decorate the property in the model class with [XmlAttribute]:

This model:

```<code>[System.Serializable, XmlType( "object")]
public class AchievementModel
{
    // serialize attribute on the XmlNode
    [XmlAttribute("ID")]
    public int ID { get; set; }
    // serialize an element value
    [XmlElement("param1")]
    public string Progress { get; set; }
    // other properties omitted
}
</code>```

Will deserialise from this XML:

```<code><object ID="2"> <!-- Deserialize ID with XmlAttribute -->
    <param1>Clicks</param1>  <!-- deserialize with XmlElement -->
    <!-- other elements omitted -->
</object>
</code>```

Title: Parse specific XML file into object

Body:
I want to deserialize XML file into object, but my XML looks like this

<ALLObjects>
<object ID ="1">
    <param1>Clicks</param1>
    <param2>NONE</param2>
    <param3>example</param3>
    <param4>example23</param4>
    <param5>1</param5>
    <param6>1</param6>
</object>

<object ID ="2">
    <param1>Clicks</param1>
    <param2>NONE</param2>
    <param3>Example23</param3>
    <param4>Example 1</param4>
    <param5>10</param5>
    <param6>1</param6>
</object>

 //more objects

</ALLObjects>

I have a model that contains all params (including the ID value). I want to load all the object into a list and make some changes and then save it into the same XML file. I know how it works when the XML is int this format

<object >
<ID>1</ID>
<param1>Clicks</param1>
<param2>NONE</param2>
<param3>example</param3>
<param4>example23</param4>
<param5>1</param5>
<param6>1</param6>
</object>

But I don't want to manually rewrite the whole file to load it into that format. I need a hint what is the best practice for this case. Maybe I need to load it into the JSON and then parse into the object?

@chade_ currently I try to use XmlSerializer, but I've got an error

InvalidOperationException: <achievements xmlns=''> was not expected

my code: LoadingFromFile

  private void LoadData()
    {
        List<AchievementModel> models;

        using (var reader = new StreamReader("test.xml"))
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(List<AchievementModel>),
                new XmlRootAttribute("ALLObjects"));
            models = (List<AchievementModel>)deserializer.Deserialize(reader);
        }
    }

[System.Serializable, XmlRoot("ALLObjects")]
public class AchievementList
{
    public AchievementList() { Items = new List<AchievementModel>(); }
    [XmlElement("object")]
    public List<AchievementModel> Items { get; set; }
}

[System.Serializable, XmlType( "object ")]
public class AchievementModel
{
    public AchievementModel() { }

    [XmlElement("ID")]
    public int ID { get; set; }
    [XmlElement("param1")]
    public string Progress { get; set; }
    [XmlElement("param2")]
    public string Reward { get; set; }

    [XmlElement("param3")]
    public string Title { get; set; }
    [XmlElement("param4")]
    public string Description { get; set; }
    [XmlElement("param5")]
    public int param6{ get; set; }
    [XmlElement("param6")]
    public int AchievementAnimalSubtitle { get; set; }
}
}

Body:
If you want to load an attribute value instead of an element from your XML you need to decorate the property in the model class with [XmlAttribute]:

This model:

[System.Serializable, XmlType( "object")]
public class AchievementModel
{
    // serialize attribute on the XmlNode
    [XmlAttribute("ID")]
    public int ID { get; set; }
    // serialize an element value
    [XmlElement("param1")]
    public string Progress { get; set; }
    // other properties omitted
}

Will deserialise from this XML:

<object ID="2"> <!-- Deserialize ID with XmlAttribute -->
    <param1>Clicks</param1>  <!-- deserialize with XmlElement -->
    <!-- other elements omitted -->
</object>


问:
How to upgrade minikube?
I had installed minikube a few months ago and wanted to upgrade as newer versions are available.

I am unable to find out how to upgrade minikube. I see a feature request for an upgrade command here - https://github.com/kubernetes/minikube/issues/1171

I tried to then uninstall minikube and hit another brickwall again. I don't see a command to uninstall minikube. The information that came closest to this was not very helpful - https://github.com/kubernetes/minikube/issues/1043

I guess we need ways to upgrade these (at least once every 6 months or so).

答:
This should do the trick.</p>

```<code>brew cask reinstall minikube
</code>```

Title: How to upgrade minikube?

Body:
This should do the trick.

brew cask reinstall minikube