问:
Horizontal Row View : A RenderFlex overflowed by 66 pixels on the right
I put ListView to show tabs scrolling horizontally, but the problem is that they are displayed in the middle of screen and I want it to be shown at the top of screen.

Is there any way to solve this and show this list at top of screen?

Here is how I did it:

```<code>      body: Container(
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
            itemCount: 1,
            itemBuilder: (BuildContext context, int index){
            return  Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'All',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Cars',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Buildings',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Assorted Devices',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
              ],
            );
          }),
      ),
    );
</code>```

答:
Add crossAxisAlignment in Row, it will start your UI from Top

```<code>         Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            //...
             )
</code>```

Body:
I put ListView to show tabs scrolling horizontally, but the problem is that they are displayed in the middle of screen and I want it to be shown at the top of screen.

Is there any way to solve this and show this list at top of screen?

Here is how I did it:

      body: Container(
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
            itemCount: 1,
            itemBuilder: (BuildContext context, int index){
            return  Row(
              children: [
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'All',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Cars',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Buildings',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left:20.0, right:20,top: 10, ),
                  child: InkWell(
                    child: Text(
                      'Assorted Devices',
                      style: TextStyle(
                          fontSize: 20,
                          color: Colors.grey
                      ),),
                  ),
                ),
              ],
            );
          }),
      ),
    );

Body:
Add crossAxisAlignment in Row, it will start your UI from Top

         Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            //...
             )


来源: stackexchange

问:
Moving the `counter` position over its background (OR moving the background itself)
There's a li counter set inside purple circles. Circles themselves are perfectly vertically centered over li items (List item #...), so their position should stay as it is. However, the counter numbers are shifted to the bottom of the circle, while they should be in its center (i.e. at the same level as li text).

I tried adding padding-bottom to ol li::before to rise the counter a little, but this changes vertical proportion of the circle itself (as if i changed its height).

When i delete top and transform from the ol li::before class, the counter moves up to where i want it to be, but then the circles themselves also move up and counter is again not vertically centered over the circle.

Is there a way to solve this tricky problem?

ol {
  list-style: none;
  counter-reset: mycounter;
  font-size: calc(0.5em + 2.3vw);
  padding-left: 2.7em;
  border: 1px solid red;
}

ol li {
  counter-increment: mycounter;
  position: relative;
  border: 1px solid green;

    --size: calc(0.5em + 2.3vw);
  line-height: calc(var(--size) + 0.5em);
}

ol li::before {
  content: counter(mycounter);
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  color: black;
  font-weight: bold;
  border-radius: 50%;

    --size: calc(0.5em + 2.3vw);
  left: calc(-1 * var(--size) - 0.5em);
  width: var(--size);
  height: var(--size);
  text-align: center;
  border: 1px solid purple;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>List item #1</li>
  <li>List item #2</li>
</ol></code>```

答:
Just add line-heigh to your :before element, Increase or decrease it as per your need

ol {
  list-style: none;
  counter-reset: mycounter;
  font-size: calc(0.5em + 2.3vw);
  padding-left: 2.7em;
  border: 1px solid red;
}

ol li {
  counter-increment: mycounter;
  position: relative;
  border: 1px solid green;

    --size: calc(0.5em + 2.3vw);
  line-height: calc(var(--size) + 0.5em);
}

ol li::before {
  content: counter(mycounter);
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  color: black;
  font-weight: bold;
  border-radius: 50%;

    --size: calc(0.5em + 2.3vw);
  left: calc(-1 * var(--size) - 0.5em);
  width: var(--size);
  height: var(--size);
  text-align: center;
line-height: 25px;
  border: 1px solid purple;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>List item #1</li>
  <li>List item #2</li>
</ol></code>```

ContentLicense: CC BY-SA 4.0

Body:
There's a li counter set inside purple circles. Circles themselves are perfectly vertically centered over li items (List item #...), so their position should stay as it is. However, the counter numbers are shifted to the bottom of the circle, while they should be in its center (i.e. at the same level as li text).

I tried adding padding-bottom to ol li::before to rise the counter a little, but this changes vertical proportion of the circle itself (as if i changed its height).

When i delete top and transform from the ol li::before class, the counter moves up to where i want it to be, but then the circles themselves also move up and counter is again not vertically centered over the circle.

Is there a way to solve this tricky problem?

ol {
  list-style: none;
  counter-reset: mycounter;
  font-size: calc(0.5em + 2.3vw);
  padding-left: 2.7em;
  border: 1px solid red;
}

ol li {
  counter-increment: mycounter;
  position: relative;
  border: 1px solid green;

    --size: calc(0.5em + 2.3vw);
  line-height: calc(var(--size) + 0.5em);
}

ol li::before {
  content: counter(mycounter);
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  color: black;
  font-weight: bold;
  border-radius: 50%;

    --size: calc(0.5em + 2.3vw);
  left: calc(-1 * var(--size) - 0.5em);
  width: var(--size);
  height: var(--size);
  text-align: center;
  border: 1px solid purple;
}

List item #1

List item #2

Body:
Just add line-heigh to your :before element, Increase or decrease it as per your need

ol {
  list-style: none;
  counter-reset: mycounter;
  font-size: calc(0.5em + 2.3vw);
  padding-left: 2.7em;
  border: 1px solid red;
}

ol li {
  counter-increment: mycounter;
  position: relative;
  border: 1px solid green;

    --size: calc(0.5em + 2.3vw);
  line-height: calc(var(--size) + 0.5em);
}

ol li::before {
  content: counter(mycounter);
  position: absolute;
  top: 50%;
  transform: translate(0, -50%);
  color: black;
  font-weight: bold;
  border-radius: 50%;

    --size: calc(0.5em + 2.3vw);
  left: calc(-1 * var(--size) - 0.5em);
  width: var(--size);
  height: var(--size);
  text-align: center;
line-height: 25px;
  border: 1px solid purple;
}

<ol>
  <li>List item #1</li>
  <li>List item #2</li>
</ol>


问:
Basic authentication for website to secure site login and API access
I'm looking at the security model of a website that's being developed. After researching the web i have found that there are several security models to secure websites i.e. Basic Auth, JWT ...

At the moment, SSL is not enabled as still in dev. Website has a login page and communicates via API's (including login and logout). On the login page, as a test, I have attempted to log in with false details, and then I have looked at the developer tools to identify the security mechanism and found the following screenshots. I think the site is using basic authentication, though I noted that the email / password is not encoded and is using a custom login form. Could someone confirm if it is basic authentication being utilised?

Developer Tools Images

[Request Header Image][2]

UPDATE:
I discovered that once the user is authenticated by email/password, I should have posted the screenshots as this is where keys are returned. In the below screenshot a bidder token and bidder secret is sent back to client. I think these are generated through crypto on backend. So I don't think its JWT, but is this a suitable way in creating keys and not sending in header but in response body?

Network tab after user logged in

Login Form Code :

```<code> {

        /* prepare ui */
        progress.classList.remove('hide');
        login_btn.innerText = 'Logging In';
        login_btn.setAttribute('disabled', true);

        /* make http request */
        var http = new XMLHttpRequest();
        var url = SERVER + '/api/bidder/login';
        var body = {
            email: email.value,
            password: password.value
        };

        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/JSON');

        http.onreadystatechange = function () { //Call a function when the state changes.
            if (http.readyState == 4 && http.status == 200) {
                var res = JSON.parse(http.responseText);

                if (res.status) {

                    localStorage.setItem("bidData", JSON.stringify(res.data));
                    window.location.href = window.location.href.replace('login.html','');

                } else {
                    Toast.show('Danger', res.message);
                }

                /* reset ui */
                progress.classList.add('hide');
                login_btn.innerText = 'Log In';
                login_btn.removeAttribute('disabled');

            }
        }
        http.send(JSON.stringify(body));

    }
</code>```

答:
When you use basic access authentication, credentials wouldn't be loaded in a request payload. They reside in an authorization header like "Authorization: Basic ~some credential here~".

So if you neither see this authorization header in your request nor a popup like below on the website, basic access authentication is not enabled.

Body:
I'm looking at the security model of a website that's being developed. After researching the web i have found that there are several security models to secure websites i.e. Basic Auth, JWT ...

At the moment, SSL is not enabled as still in dev. Website has a login page and communicates via API's (including login and logout). On the login page, as a test, I have attempted to log in with false details, and then I have looked at the developer tools to identify the security mechanism and found the following screenshots. I think the site is using basic authentication, though I noted that the email / password is not encoded and is using a custom login form. Could someone confirm if it is basic authentication being utilised?

Developer Tools Images

[Request Header Image][2]

UPDATE:
I discovered that once the user is authenticated by email/password, I should have posted the screenshots as this is where keys are returned. In the below screenshot a bidder token and bidder secret is sent back to client. I think these are generated through crypto on backend. So I don't think its JWT, but is this a suitable way in creating keys and not sending in header but in response body?

Network tab after user logged in

Login Form Code :

 {

        /* prepare ui */
        progress.classList.remove('hide');
        login_btn.innerText = 'Logging In';
        login_btn.setAttribute('disabled', true);

        /* make http request */
        var http = new XMLHttpRequest();
        var url = SERVER + '/api/bidder/login';
        var body = {
            email: email.value,
            password: password.value
        };

        http.open('POST', url, true);
        http.setRequestHeader('Content-type', 'application/JSON');

        http.onreadystatechange = function () { //Call a function when the state changes.
            if (http.readyState == 4 && http.status == 200) {
                var res = JSON.parse(http.responseText);

                if (res.status) {

                    localStorage.setItem("bidData", JSON.stringify(res.data));
                    window.location.href = window.location.href.replace('login.html','');

                } else {
                    Toast.show('Danger', res.message);
                }

                /* reset ui */
                progress.classList.add('hide');
                login_btn.innerText = 'Log In';
                login_btn.removeAttribute('disabled');

            }
        }
        http.send(JSON.stringify(body));

    }


问:
How to share html component amount different page
In ASP.NET, I have a master page, and five other pages which are under master page.

In all five pages, I need to implement a button, after clicking it, will generate different download results.

My original implementation is, in all five page, will all have a "Button", so in code behind will have corresponding event method to generate the download.

But my approach, will have duplicated html compoents.

Is there a way I can define the download button in my master page, when clicking button in different page, event method from different page will be invoked?

答: You can use the SHTML instead of HTML and include it every where that you need it.  </p>

ContentLicense: CC BY-SA 3.0


问:
Change part of an adserver tag with javasript
I insert ads on my website from a local adserver with the following code:

```<code><ins data-revive-zoneid="XX" data-revive-id="YYYYYYYYYYYYYYYY"></ins>
<script async src="//www.website.com/adserver/www/delivery/asyncjs.php"></script>
</code>```

I also use a cookie-bar on this website. I can check if a user has agreed to use cookies with this Javascript-code:

```<code><script>
if (Drupal.eu_cookie_compliance.hasAgreed()) {... user has agreed, do something ...}
</script>
</code>```

Now I want to do the following:
The "data-revive-zoneid" from the ad tag should be

"1" if the user has not agreed to cookies => if (!Drupal.eu_cookie_compliance.hasAgreed())

"2" if the user has agreed to cookies => if (Drupal.eu_cookie_compliance.hasAgreed())

How can I change the adserver code to achieve this?

答:
I think you should also create script tag dynamically after changing data-revive-zoneid

```<code>
    function setZoneId(value) {
      document.querySelector("ins").setAttribute("data-revive-zoneid", value);

      const script = document.createElement("script);
      script.src = '//www.website.com/adserver/www/delivery/asyncjs.php';
      document.body.appendChild(script);
    }

    if (Drupal.eu_cookie_compliance.hasAgreed()) {
      setZoneId(2);
    }
    else {
      setZoneId(1);
    }

</code>```

Body:
I insert ads on my website from a local adserver with the following code:

I also use a cookie-bar on this website. I can check if a user has agreed to use cookies with this Javascript-code:

Now I want to do the following:
The "data-revive-zoneid" from the ad tag should be

"1" if the user has not agreed to cookies => if (!Drupal.eu_cookie_compliance.hasAgreed())

"2" if the user has agreed to cookies => if (Drupal.eu_cookie_compliance.hasAgreed())

How can I change the adserver code to achieve this?

Body:
I think you should also create script tag dynamically after changing data-revive-zoneid

    function setZoneId(value) {
      document.querySelector("ins").setAttribute("data-revive-zoneid", value);

      const script = document.createElement("script);
      script.src = '//www.website.com/adserver/www/delivery/asyncjs.php';
      document.body.appendChild(script);
    }

    if (Drupal.eu_cookie_compliance.hasAgreed()) {
      setZoneId(2);
    }
    else {
      setZoneId(1);
    }


问:
Extract non-negative number from the ending of a string in js
Just like the title says
Description of the example:
x) example string -> what I need as the output

examples:

```<code>1) "asdf"      ->    null or -1 or undefined (because nothing was found)
2) "asdf1"     ->    1
3) "asdf0"     ->    0
4) "asdf-1"    ->    1
5) "asdf001"   ->    1
6) "asdf1234"  ->    1234
7) "asdf12.34" ->    34 (ending value, so number after .)
8) "123asdf78" ->    78 (integer from ending)
</code>```

I hope these examples will be enough. I tried doing this with for loop, but it didn't work out. Does anyone know if there are functions which enable to do something like this or similar?

More info about my approach:
In the for loop I checked for every character if is  >= '0' && <= '9' then added to previous tmp variable which responsible for concatenate all characters, and at the end I parsed this to int. But I think this solution is bad...

答:
You can use simple regular expression for this purpose:

function numericSuffix(string) {
    const match = string.match(/\d+$/);
    return match !== null ? Number(match[0]) : null;
}

numericSuffix('abc-123') // 123
numericSuffix('abc-123x') // null
```

Body:
Just like the title says
Description of the example:
x) example string -> what I need as the output

examples:

1) "asdf"      ->    null or -1 or undefined (because nothing was found)
2) "asdf1"     ->    1
3) "asdf0"     ->    0
4) "asdf-1"    ->    1
5) "asdf001"   ->    1
6) "asdf1234"  ->    1234
7) "asdf12.34" ->    34 (ending value, so number after .)
8) "123asdf78" ->    78 (integer from ending)

I hope these examples will be enough. I tried doing this with for loop, but it didn't work out. Does anyone know if there are functions which enable to do something like this or similar?

More info about my approach:
In the for loop I checked for every character if is  >= '0' && <= '9' then added to previous tmp variable which responsible for concatenate all characters, and at the end I parsed this to int. But I think this solution is bad...


问:
variable visibility from calling function
I have 2 classes. In one class i have 4 variables. I instantiate another class and use methods which use these variables. I dont want to pass them as parameters. They are set to public. Both classes are in the default package with each other. heres my code:

```<code>public class c1 {
     public int x, y, x1, y1;
     public static void main(String args[]) {
          c1 a = new c1();
     }
     public c1() {
          c2 b = new c2();
          b.getSlope();
     }
}

public class c2 {
     public c2() {}
     public int getSlope() {
          return (y-y1)/(x-x1);
     }
}
</code>```

i get an error which says: cannot find symbol

答:
Variables x, y, x1, y1 do not exist in your c2 class so your code will never compile. </p>

<p>If you want to use x, y , x1 and y1 in your c2 class, consider trying another method. </p>

Body:
I have 2 classes. In one class i have 4 variables. I instantiate another class and use methods which use these variables. I dont want to pass them as parameters. They are set to public. Both classes are in the default package with each other. heres my code:

public class c1 {
     public int x, y, x1, y1;
     public static void main(String args[]) {
          c1 a = new c1();
     }
     public c1() {
          c2 b = new c2();
          b.getSlope();
     }
}

public class c2 {
     public c2() {}
     public int getSlope() {
          return (y-y1)/(x-x1);
     }
}

i get an error which says: cannot find symbol

Body:
Variables x, y, x1, y1 do not exist in your c2 class so your code will never compile.

If you want to use x, y , x1 and y1 in your c2 class, consider trying another method.


问:
InternalViewResolver in spring boot is unable to find the view
I don't know I have tried multiple times but never really understood how the InternalViewResolver or any view resolver work under the hood. I have configured the view resolution using WebMvcConfigurer. like this one.

```<code>@Configuration
public class WebViewConfigurer implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/register").setViewName("registration");
    }
}
</code>```

I have put my html file registration.html in the location: src/main/resources/templates.

Whenever I try to access the page localhost:8080/register I get the whitelabel error page

```<code>There was an unexpected error (type=Not Found, status=404).
</code>```

I have configured view like this many times before and I have always faced problem in the beginning but I always get on top of it after some tweak and this time also I know I would get it. So the problem is not just how I solve my current problem but how can I stop this repetitive mistakes. Has any one faced these problems with ViewResolvers in spring or is it just me.

答:
In case of any one wondering I solved the current problem: I added prefix and suffix in InternalViewResolved and placed the html file in target/class/resources/templates.

My current code after solving:

```<code>    @Configuration
    public class WebViewConfigurer implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/register").setViewName("registration");
        }

        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            registry.viewResolver(new InternalResourceViewResolver(){{setPrefix("templates/");setSuffix(".html");}});
        }
}
</code>```

Body:
I don't know I have tried multiple times but never really understood how the InternalViewResolver or any view resolver work under the hood. I have configured the view resolution using WebMvcConfigurer. like this one.

@Configuration
public class WebViewConfigurer implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/register").setViewName("registration");
    }
}

I have put my html file registration.html in the location: src/main/resources/templates.

Whenever I try to access the page localhost:8080/register I get the whitelabel error page

There was an unexpected error (type=Not Found, status=404).

I have configured view like this many times before and I have always faced problem in the beginning but I always get on top of it after some tweak and this time also I know I would get it. So the problem is not just how I solve my current problem but how can I stop this repetitive mistakes. Has any one faced these problems with ViewResolvers in spring or is it just me.

Body:
In case of any one wondering I solved the current problem: I added prefix and suffix in InternalViewResolved and placed the html file in target/class/resources/templates.

My current code after solving:

    @Configuration
    public class WebViewConfigurer implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/register").setViewName("registration");
        }

        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            registry.viewResolver(new InternalResourceViewResolver(){{setPrefix("templates/");setSuffix(".html");}});
        }
}


问:
Factory girl problems accessing certain attributes
I have a user model and an operator model which belongs to user. I created some factories that associate them(in my feature, a user account is created when an operator signs up) so I made this step:

```<code>def create_operator_with_user(operator_name)
  user = Factory(:user)
  puts "MY PASS: #{user.password}"
  operator = Factory(:operator, :chief_pilot_or_business_owner => operator_name, :user_id => user.id)
  pew = User.find(operator.user_id)
  puts "USER: #{operator.user.inspect} PASS: #{operator.user.password} PEWPASS: #{pew.password}"
end
</code>```

this is my user factory:

```<code>Factory.define :admin, :class => User do |f|
  f.sequence(:login)            { |n| "admin#{n}"}
  f.is_admin                    true
  f.password                    "password"
  f.password_confirmation       "password"
  f.sequence(:email)            { |n| "test#{n}@test.com"}
end

Factory.define :user, :parent => :admin do |f|
  f.sequence(:login)            { |n| "user_#{n}" }
  f.sequence(:email)            { |n| "the_user_#{n}@asdf.com" }
end
</code>```

I tried to run my feature and here was the output:

```<code>MY PASS: password
USER: #<User id: 181, login: "user_1", email: "the_user_1@asdf.com", crypted_password: "e9f6932a07cbe6e49073a331530f9dc01a3482502d25770be00...", password_salt: "YEjT9Q8EGYdrNh4qGZda", persistence_token: "259a61440f6ecd001e79a4aaf1c5c343e50be04388bbf1718c3...", created_at: "2011-06-02 04:24:34", updated_at: "2011-06-02 04:24:34", is_admin: true>
PASS:
PEWPASS:
</code>```

So the question is, the user DOES have a password, since it was allowed to be created, not to mention it printed it out after being created using the factory. Problem is, when I try to access the password via User.find(user.id) or operator.user, why is it that password is blank?

If it helps, this is for authlogic

答:
Does this work?</p>

```<code>Factory.define :admin, :class => :user do |f|
</code>```

Body:
I have a user model and an operator model which belongs to user. I created some factories that associate them(in my feature, a user account is created when an operator signs up) so I made this step:

def create_operator_with_user(operator_name)
  user = Factory(:user)
  puts "MY PASS: #{user.password}"
  operator = Factory(:operator, :chief_pilot_or_business_owner => operator_name, :user_id => user.id)
  pew = User.find(operator.user_id)
  puts "USER: #{operator.user.inspect} PASS: #{operator.user.password} PEWPASS: #{pew.password}"
end

this is my user factory:

Factory.define :admin, :class => User do |f|
  f.sequence(:login)            { |n| "admin#{n}"}
  f.is_admin                    true
  f.password                    "password"
  f.password_confirmation       "password"
  f.sequence(:email)            { |n| "test#{n}@test.com"}
end

Factory.define :user, :parent => :admin do |f|
  f.sequence(:login)            { |n| "user_#{n}" }
  f.sequence(:email)            { |n| "the_user_#{n}@asdf.com" }
end

I tried to run my feature and here was the output:

MY PASS: password
USER: #<User id: 181, login: "user_1", email: "the_user_1@asdf.com", crypted_password: "e9f6932a07cbe6e49073a331530f9dc01a3482502d25770be00...", password_salt: "YEjT9Q8EGYdrNh4qGZda", persistence_token: "259a61440f6ecd001e79a4aaf1c5c343e50be04388bbf1718c3...", created_at: "2011-06-02 04:24:34", updated_at: "2011-06-02 04:24:34", is_admin: true>
PASS:
PEWPASS:

So the question is, the user DOES have a password, since it was allowed to be created, not to mention it printed it out after being created using the factory. Problem is, when I try to access the password via User.find(user.id) or operator.user, why is it that password is blank?

If it helps, this is for authlogic

Body:
Does this work?

Factory.define :admin, :class => :user do |f|


问:
Project fails to compile after renaming
I had to rename an android project and generated package.

Now I have this annoying error message at build time telling that it can't find something:

android/CardioSensys/build/intermediates/external_file_lib_dex_archives/debug/out

This is what I have:

android/CardioSensys/build/intermediates/external_libs_dex/debug/mergeExtDexDebug/out

Basically it is looking for external_file_lib_dex_archives instead of external_libs_dex

```<code>org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
    at org.gradle.workers.internal.DefaultWorkerExecutor$WorkerExecution.waitForCompletion(DefaultWorkerExecutor.java:285)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:115)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.access$000(DefaultAsyncWorkTracker.java:34)
    at org.gradle.internal.work.DefaultAsyncWorkTracker$2.run(DefaultAsyncWorkTracker.java:83)
    at org.gradle.internal.Factories$1.create(Factories.java:25)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutLocks(DefaultWorkerLeaseService.java:254)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutProjectLock(DefaultWorkerLeaseService.java:165)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutProjectLock(DefaultWorkerLeaseService.java:159)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withoutProjectLock(StopShieldingWorkerLeaseService.java:90)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForCompletion(DefaultAsyncWorkTracker.java:79)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$5.run(ExecuteActionsTaskExecuter.java:412)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:393)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:376)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:213)
    at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$1(ExecuteStep.java:33)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:33)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:58)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:35)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:33)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:39)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
    at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:35)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:45)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:31)
    at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:201)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:70)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:45)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:43)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:32)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:96)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:89)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:54)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:77)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:90)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:48)
    at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:75)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
    at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:94)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.android.build.api.transform.TransformException: java.nio.file.NoSuchFileException: /Users/omatrot/Documents/sensoria_analyics/application/android/CardioSensys/build/intermediates/external_file_lib_dex_archives/debug/out
    at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:471)
    at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:335)
    at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:39)
    at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.execute(NoIsolationWorkerFactory.java:61)
    at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
    at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
    at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:55)
    at org.gradle.workers.internal.DefaultWorkerExecutor$1.call(DefaultWorkerExecutor.java:105)
    at org.gradle.workers.internal.DefaultWorkerExecutor$1.call(DefaultWorkerExecutor.java:99)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    ... 6 more
Caused by: java.nio.file.NoSuchFileException: /Users/omatrot/Documents/sensoria_analyics/application/android/CardioSensys/build/intermediates/external_file_lib_dex_archives/debug/out
    at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
    at sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:407)
    at java.nio.file.Files.newDirectoryStream(Files.java:457)
    at java.nio.file.Files.list(Files.java:3451)
    at com.android.build.gradle.internal.tasks.DexMergingParams.getAllDexFiles(DexMergingTask.kt:502)
    at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:423)
    ... 28 more
</code>```

Cleaning/rebuilding or restarting Android Studio dit not fix the problem.

Any help appreciated.

答:
Delete .gradle folder and rebuild project works for me.

It is not related to compileSdkVersion. your package name changed and so some file which cached in Android project have the old package name. For update that files, you should delete both the build folder and the .gradle folder and build the project again.

Title: Project fails to compile after renaming

Body:
I had to rename an android project and generated package.

Now I have this annoying error message at build time telling that it can't find something:

android/CardioSensys/build/intermediates/external_file_lib_dex_archives/debug/out

This is what I have:

android/CardioSensys/build/intermediates/external_libs_dex/debug/mergeExtDexDebug/out

Basically it is looking for external_file_lib_dex_archives instead of external_libs_dex

org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
    at org.gradle.workers.internal.DefaultWorkerExecutor$WorkerExecution.waitForCompletion(DefaultWorkerExecutor.java:285)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForItemsAndGatherFailures(DefaultAsyncWorkTracker.java:115)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.access$000(DefaultAsyncWorkTracker.java:34)
    at org.gradle.internal.work.DefaultAsyncWorkTracker$2.run(DefaultAsyncWorkTracker.java:83)
    at org.gradle.internal.Factories$1.create(Factories.java:25)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutLocks(DefaultWorkerLeaseService.java:254)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutProjectLock(DefaultWorkerLeaseService.java:165)
    at org.gradle.internal.work.DefaultWorkerLeaseService.withoutProjectLock(DefaultWorkerLeaseService.java:159)
    at org.gradle.internal.work.StopShieldingWorkerLeaseService.withoutProjectLock(StopShieldingWorkerLeaseService.java:90)
    at org.gradle.internal.work.DefaultAsyncWorkTracker.waitForCompletion(DefaultAsyncWorkTracker.java:79)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$5.run(ExecuteActionsTaskExecuter.java:412)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:393)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:376)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:213)
    at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$1(ExecuteStep.java:33)
    at java.util.Optional.orElseGet(Optional.java:267)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:33)
    at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:58)
    at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:35)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48)
    at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:33)
    at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:39)
    at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
    at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
    at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:35)
    at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:45)
    at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:31)
    at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:201)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:70)
    at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:45)
    at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:43)
    at org.gradle.internal.execution.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:32)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
    at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:96)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:89)
    at java.util.Optional.map(Optional.java:215)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:54)
    at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:77)
    at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
    at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:90)
    at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:48)
    at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:120)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:75)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:108)
    at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
    at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:94)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:95)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:49)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.android.build.api.transform.TransformException: java.nio.file.NoSuchFileException: /Users/omatrot/Documents/sensoria_analyics/application/android/CardioSensys/build/intermediates/external_file_lib_dex_archives/debug/out
    at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:471)
    at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:335)
    at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:39)
    at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.execute(NoIsolationWorkerFactory.java:61)
    at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
    at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
    at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
    at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
    at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:55)
    at org.gradle.workers.internal.DefaultWorkerExecutor$1.call(DefaultWorkerExecutor.java:105)
    at org.gradle.workers.internal.DefaultWorkerExecutor$1.call(DefaultWorkerExecutor.java:99)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
    at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    ... 6 more
Caused by: java.nio.file.NoSuchFileException: /Users/omatrot/Documents/sensoria_analyics/application/android/CardioSensys/build/intermediates/external_file_lib_dex_archives/debug/out
    at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
    at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
    at sun.nio.fs.UnixFileSystemProvider.newDirectoryStream(UnixFileSystemProvider.java:407)
    at java.nio.file.Files.newDirectoryStream(Files.java:457)
    at java.nio.file.Files.list(Files.java:3451)
    at com.android.build.gradle.internal.tasks.DexMergingParams.getAllDexFiles(DexMergingTask.kt:502)
    at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:423)
    ... 28 more

Cleaning/rebuilding or restarting Android Studio dit not fix the problem.

Any help appreciated.


问:
Is there a faster way to count non-overlapping occurrences in a string than count()?
Given a minimum length N and a string S of 1's and 0's (e.g. "01000100"), I am trying to return the number of non-overlapping occurrences of a sub-string of length n containing all '0's. For example, given n=2 and the string "01000100", the number of non-overlapping "00"s is 2.

This is what I have done:

```<code>def myfunc(S,N):
  return S.count('0'*N)
</code>```

My question: is there a faster way of performing this for very long strings? This is from an online coding practice site and my code passes all but one of the test cases, which fails due to not being able to finish within a time limit. Doing some research it seems I can only find that count() is the fastest method for this.

答:
This might be faster:

```<code>>>> s = "01000100"
>>> def my_count( a, n ) :
...     parts = a.split('1')
...     return sum( len(p)//n for p in parts )
...
>>> my_count(s, 2)
2
>>>
</code>```

Worst case scenario for count() is O(N^2), the function above is strictly linear O(N). Here's the discussion where O(N^2) number came from: What's the computational cost of count operation on strings Python?

Also, you may always do this manually, without using split(), just loop over the string, reset counter (once saved counter // n somewhere) on 1 and increase counter on 0. This would definitely beat any other approach because strictly O(N).

Finally, for relatively large values of n (n > 10 ?), there might be a sub-linear (or still linear, but with a smaller constant) algorithm, which starts with comparing a[n-1] to 0, and going back to beginning. Chances are, there going to be a 1 somewhere, so we don't have to analyse the beginning of the string if a[n-1] is 1 -- simply because there's no way to fit enough zeros in there. Assuming we have found 1 at position k, the next position to compare would be a[k+n-1], again going back to the beginning of the string.

This way we can effectively skip most of the string during the search.

Body:
Given a minimum length N and a string S of 1's and 0's (e.g. "01000100"), I am trying to return the number of non-overlapping occurrences of a sub-string of length n containing all '0's. For example, given n=2 and the string "01000100", the number of non-overlapping "00"s is 2.

This is what I have done:

def myfunc(S,N):
  return S.count('0'*N)

My question: is there a faster way of performing this for very long strings? This is from an online coding practice site and my code passes all but one of the test cases, which fails due to not being able to finish within a time limit. Doing some research it seems I can only find that count() is the fastest method for this.

Body:
This might be faster:

>>> s = "01000100"
>>> def my_count( a, n ) :
...     parts = a.split('1')
...     return sum( len(p)//n for p in parts )
...
>>> my_count(s, 2)
2
>>>

Worst case scenario for count() is O(N^2), the function above is strictly linear O(N). Here's the discussion where O(N^2) number came from: What's the computational cost of count operation on strings Python?

Also, you may always do this manually, without using split(), just loop over the string, reset counter (once saved counter // n somewhere) on 1 and increase counter on 0. This would definitely beat any other approach because strictly O(N).

Finally, for relatively large values of n (n > 10 ?), there might be a sub-linear (or still linear, but with a smaller constant) algorithm, which starts with comparing a[n-1] to 0, and going back to beginning. Chances are, there going to be a 1 somewhere, so we don't have to analyse the beginning of the string if a[n-1] is 1 -- simply because there's no way to fit enough zeros in there. Assuming we have found 1 at position k, the next position to compare would be a[k+n-1], again going back to the beginning of the string.

This way we can effectively skip most of the string during the search.


问:
How to set JAVA_HOME in Linux for all users
I am new to Linux system and there seem to be too many Java folders.

java -version gives me:

java version "1.7.0_55"

OpenJDK Runtime Environment (rhel-2.4.7.1.el6_5-x86_64 u55-b13)

OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)

When I am trying to build a Maven project , I am getting error:

```<code>Error: JAVA_HOME is not defined correctly.
We cannot execute /usr/java/jdk1.7.0_05/bin/java
</code>```

Could you please tell me which files I need to modify for root as well as not-root user and where exactly is java located?

答:
All operational steps(finding java, parent dir, editing file,...) one solution

```<code>zFileProfile="/etc/profile"
zJavaHomePath=$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)
echo $zJavaHomePath

echo "export JAVA_HOME=\"${zJavaHomePath}\"" >> $zFileProfile
echo "export PATH=\$PATH:\$JAVA_HOME/bin" >> $zFileProfile
</code>```

Result:

```<code># tail -2 $zFileProfile
export JAVA_HOME="/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"
export PATH=$PATH:$JAVA_HOME/bin
</code>```

Explanation:

1) Let's break the full command into pieces

```<code>$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)
</code>```

2) Find java path from java command

```<code># $(which java)
"/usr/bin/java"
</code>```

3) Get relative path from symbolic path

```<code># readlink -ze /usr/bin/java
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java"
</code>```

4) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java

```<code># readlink -ze /usr/bin/java | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin"
</code>```

5) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/

```<code># readlink -ze /usr/bin/java | xargs -0 dirname | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"
</code>```

Body:
I am new to Linux system and there seem to be too many Java folders.

java -version gives me:

java version "1.7.0_55"

OpenJDK Runtime Environment (rhel-2.4.7.1.el6_5-x86_64 u55-b13)

OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)

When I am trying to build a Maven project , I am getting error:

Error: JAVA_HOME is not defined correctly.
We cannot execute /usr/java/jdk1.7.0_05/bin/java

Could you please tell me which files I need to modify for root as well as not-root user and where exactly is java located?

Body:
All operational steps(finding java, parent dir, editing file,...) one solution

zFileProfile="/etc/profile"
zJavaHomePath=$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)
echo $zJavaHomePath

echo "export JAVA_HOME=\"${zJavaHomePath}\"" >> $zFileProfile
echo "export PATH=\$PATH:\$JAVA_HOME/bin" >> $zFileProfile

Result:

# tail -2 $zFileProfile
export JAVA_HOME="/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"
export PATH=$PATH:$JAVA_HOME/bin

Explanation:

1) Let's break the full command into pieces

$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)

2) Find java path from java command

# $(which java)
"/usr/bin/java"

3) Get relative path from symbolic path

# readlink -ze /usr/bin/java
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java"

4) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java

# readlink -ze /usr/bin/java | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin"

5) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/

# readlink -ze /usr/bin/java | xargs -0 dirname | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"


问:
How to get size of image
I want to get size of image and assign to variable. I have no idea to do it</p>

```<code>OpenFile = new OpenFileDialog();
            OpenFile.Filter = "Image Files (*.bmp;*.png;*.jpg)|*.bmp;*.png;*.jpg";
            if (OpenFile.ShowDialog() == true)
            {
                ImagePath = string.Format($"{OpenFile.FileName}");

            }

            BitmapImage image = new BitmapImage();

            image.UriSource = new Uri(OpenFile.FileName);

            image.BeginInit();
            WindowWidth = image.Width;
            WindowHeight = image.Height;
            image.EndInit();
</code>```

答:
You should get the size after EndInit.

There is however no need to call BeginInit and EndInit at all:

```<code>var image = new BitmapImage(new Uri(OpenFile.FileName));

WindowWidth = image.Width;
WindowHeight = image.Height;
</code>```

Title: How to get size of image

Body:
I want to get size of image and assign to variable. I have no idea to do it

OpenFile = new OpenFileDialog();
            OpenFile.Filter = "Image Files (*.bmp;*.png;*.jpg)|*.bmp;*.png;*.jpg";
            if (OpenFile.ShowDialog() == true)
            {
                ImagePath = string.Format($"{OpenFile.FileName}");

            }

            BitmapImage image = new BitmapImage();

            image.UriSource = new Uri(OpenFile.FileName);

            image.BeginInit();
            WindowWidth = image.Width;
            WindowHeight = image.Height;
            image.EndInit();

Body:
You should get the size after EndInit.

There is however no need to call BeginInit and EndInit at all:

var image = new BitmapImage(new Uri(OpenFile.FileName));

WindowWidth = image.Width;
WindowHeight = image.Height;


问:
How to Create a Python Dictionary after iterating over three Lists for matching words
I need to create a Dictionary after iterating over three LISTs.
For matching sentences (list_sent as KEYs) and list of words (list_wordset as VALUEs) for matching
 keywords (list_keywords). Please see below LISTs and expected output Dictionary with explanation.  Please suggest.

```<code>list_sent = ['one more shock like Covid-19',
             'The number of people suffering acute',
             'people must collectively act now',
             'handling the novel coronavirus outbreak',
              'After a three-week nationwide',
              'strengthening medical quarantine']

list_wordset = [['people','suffering','acute'],
                ['Covid-19','Corona','like'],
                ['people','jersy','country'],
                ['novel', 'coronavirus', 'outbreak']]

list_keywords = ['people', 'Covid-19', 'nationwide','quarantine','handling']
</code>```

'Covid-19' key word is present in list_sent and list_wordset, so they are captured in Dictionary.
'people' key word is present in 2 different items in list_sent and 2 different lists in list_wordset, so they needs to be captured.  Even if single word from the list_wordset is matching with keyword, then also its a match.

Expected Output is:

out_dict =

```<code>{'one more shock like Covid-19': ['Covid-19','Corona','like'],
 'The number of people suffering acute': [['people','suffering','acute'],['people','jersy','country']],
 'people must collectively act now' : [['people','suffering','acute'],['people','jersy','country']]}
</code>```

答:
```<code>>>> {sent: [
    wordset for wordset in list_wordset if any(word in sent for word in wordset)
] for sent in list_sent}
{'one more shock like Covid-19': [['Covid-19', 'Corona', 'like']],
 'The number of people suffering acute': [['people', 'suffering', 'acute'], ['people', 'jersy', 'country']],
 'people must collectively act now': [['people', 'suffering', 'acute'], ['people', 'jersy', 'country']],
 'handling the novel coronavirus outbreak': [['novel', 'coronavirus', 'outbreak']],
 'After a three-week nationwide': [],
 'strengthening medical quarantine': []}
</code>```

Body:
I need to create a Dictionary after iterating over three LISTs.
For matching sentences (list_sent as KEYs) and list of words (list_wordset as VALUEs) for matching
 keywords (list_keywords). Please see below LISTs and expected output Dictionary with explanation.  Please suggest.

list_sent = ['one more shock like Covid-19',
             'The number of people suffering acute',
             'people must collectively act now',
             'handling the novel coronavirus outbreak',
              'After a three-week nationwide',
              'strengthening medical quarantine']

list_wordset = [['people','suffering','acute'],
                ['Covid-19','Corona','like'],
                ['people','jersy','country'],
                ['novel', 'coronavirus', 'outbreak']]

list_keywords = ['people', 'Covid-19', 'nationwide','quarantine','handling']

'Covid-19' key word is present in list_sent and list_wordset, so they are captured in Dictionary.
'people' key word is present in 2 different items in list_sent and 2 different lists in list_wordset, so they needs to be captured.  Even if single word from the list_wordset is matching with keyword, then also its a match.

Expected Output is:

out_dict =

{'one more shock like Covid-19': ['Covid-19','Corona','like'],
 'The number of people suffering acute': [['people','suffering','acute'],['people','jersy','country']],
 'people must collectively act now' : [['people','suffering','acute'],['people','jersy','country']]}


问:
Pie chart with non labelled data?
How can I produce a pie chart when the data is not labelled as usual? See the example  dataframe below:

```<code>             First_Half Second_Half
Div
Bundesliga      0.438       0.562
EPL             0.434       0.566
La Liga         0.441       0.559

</code>```

This just shows the proportion of first half goals vs second half goals for the divisions listed. I want to create a separate pie chart for each division with the proportion of First Half vs Second Half goals, how do I do this with this data?

答:
Given your dataframe, you can also do something like this:

import pandas as pd
import matplotlib.pyplot as plt

df = # your data

for i in range(len(df)):
    df.iloc[i].plot.pie()
    plt.show()
```

Title: Pie chart with non labelled data?

Body:
How can I produce a pie chart when the data is not labelled as usual? See the example  dataframe below:

             First_Half Second_Half
Div
Bundesliga      0.438       0.562
EPL             0.434       0.566
La Liga         0.441       0.559

This just shows the proportion of first half goals vs second half goals for the divisions listed. I want to create a separate pie chart for each division with the proportion of First Half vs Second Half goals, how do I do this with this data?


问:
How can i save and read a linked list to/from a binary file?
So im making a program that involves multiple linked lists like the one bellow, what im trying to do is saving the nodes from a certain linked list, in case the program crashes, and the read the binary file so that i dont loose the nodes that id already added.
I just dont know how to do this.
i was thinking of doing a method like this

```<code>void LinkedList::saveOn(std::ostream& os) {
    Node* temp = head;
    while (temp != NULL) {
        os << temp->data;
        temp = temp->next;
    }
}
</code>```

for each linked list that i have, but i not sure if this will work and how to read back from the file

```<code>class Node {
    public:
        int code;
        doble price;
        string name;
        Node* next;
    };

class LinkedList{
public:
    LinkedList() { // constructor
        head = NULL;
    }
    ~LinkedList() {}; // destructor
    void addNode(int val);
    void reverseList();
    void display();
private:
    Node* head;
};

// function to add node to a list
void LinkedList::addNode(int val) {
    Node* newnode = new Node();
    newnode->data = val;
    newnode->next = NULL;
    if (head == NULL) {
        head = newnode;
    }
    else {
        Node* temp = head; // head is not NULL
        while (temp->next != NULL) {
            temp = temp->next; // go to end of list
        }
        temp->next = newnode; // linking to newnode
    }
}

// reverse Linked List
void LinkedList::reverseList() {
    Node* temp = head;
    Node* nextnode = NULL;
    Node* revnode = NULL;
    while (temp != NULL) {
        head = temp;
        nextnode = temp->next;
        temp->next = revnode;
        revnode = temp;
        temp = nextnode;
    }
}

void LinkedList::display() {
    if (head == NULL) {
        cout << "List is empty!" << endl;
    }
    else {
        Node* temp = head;
        while (temp != NULL) {
            cout << temp->data << " ";
            temp = temp->next;
        }
        cout << endl;
    }
}
</code>```

答:
NOTE: This solution requires an int to be of constant size across all machines you run this code on.

Since your "Node" object is a fixed size, you should be able to just write the raw data (i.e int) to a file (without any spaces). The "next" pointer doesn't have to be saved since it will change when you recreate the linked list from the file.

When you want to recreate the linked list, simply read the whole file to a buffer and keep creating new elements while you haven't reached the end of the buffer.

Example:
To Write:

```<code>Node* current = head;
FILE* fp = fopen("save.bin", "wb");

while (current != NULL) {
    fwrite(&current->data, sizeof(int), 1, fp);
    current = current->next;
}

fclose(fp);
</code>```

To Read:

```<code>FILE* fp = fopen("save.bin", "rb");

int newData;
while (fread(&newData, sizeof(int), 1, fp) > 0) {
    addNode(newData);
}

fclose(fp);
</code>```

Now that I know that you want to store strings, you can store each node as a single line you can do the following:

To Write:

```<code>Node* current = head;
FILE* fp = fopen("save.bin", "wb");

while (current != NULL) {
    fwrite(&current->code, sizeof(int), 1, fp);
    fwrite(&current->price, sizeof(double), 1, fp);

    // The string (plus the null byte)
    fwrite(current->name.c_str(), sizeof(char), current->name.length() + 1, fp);
    // newline to indicate new node
    if (current->next != NULL)
        fprintf(fp, "\n");

    current = current->next;
}

fclose(fp);
</code>```

Body:
So im making a program that involves multiple linked lists like the one bellow, what im trying to do is saving the nodes from a certain linked list, in case the program crashes, and the read the binary file so that i dont loose the nodes that id already added.
I just dont know how to do this.
i was thinking of doing a method like this

void LinkedList::saveOn(std::ostream& os) {
    Node* temp = head;
    while (temp != NULL) {
        os << temp->data;
        temp = temp->next;
    }
}

for each linked list that i have, but i not sure if this will work and how to read back from the file

class Node {
    public:
        int code;
        doble price;
        string name;
        Node* next;
    };

class LinkedList{
public:
    LinkedList() { // constructor
        head = NULL;
    }
    ~LinkedList() {}; // destructor
    void addNode(int val);
    void reverseList();
    void display();
private:
    Node* head;
};

// function to add node to a list
void LinkedList::addNode(int val) {
    Node* newnode = new Node();
    newnode->data = val;
    newnode->next = NULL;
    if (head == NULL) {
        head = newnode;
    }
    else {
        Node* temp = head; // head is not NULL
        while (temp->next != NULL) {
            temp = temp->next; // go to end of list
        }
        temp->next = newnode; // linking to newnode
    }
}

// reverse Linked List
void LinkedList::reverseList() {
    Node* temp = head;
    Node* nextnode = NULL;
    Node* revnode = NULL;
    while (temp != NULL) {
        head = temp;
        nextnode = temp->next;
        temp->next = revnode;
        revnode = temp;
        temp = nextnode;
    }
}

void LinkedList::display() {
    if (head == NULL) {
        cout << "List is empty!" << endl;
    }
    else {
        Node* temp = head;
        while (temp != NULL) {
            cout << temp->data << " ";
            temp = temp->next;
        }
        cout << endl;
    }
}

Body:
NOTE: This solution requires an int to be of constant size across all machines you run this code on.

Since your "Node" object is a fixed size, you should be able to just write the raw data (i.e int) to a file (without any spaces). The "next" pointer doesn't have to be saved since it will change when you recreate the linked list from the file.

When you want to recreate the linked list, simply read the whole file to a buffer and keep creating new elements while you haven't reached the end of the buffer.

Example:
To Write:

Node* current = head;
FILE* fp = fopen("save.bin", "wb");

while (current != NULL) {
    fwrite(&current->data, sizeof(int), 1, fp);
    current = current->next;
}

fclose(fp);

To Read:

FILE* fp = fopen("save.bin", "rb");

int newData;
while (fread(&newData, sizeof(int), 1, fp) > 0) {
    addNode(newData);
}

fclose(fp);

Now that I know that you want to store strings, you can store each node as a single line you can do the following:

To Write:

Node* current = head;
FILE* fp = fopen("save.bin", "wb");

while (current != NULL) {
    fwrite(&current->code, sizeof(int), 1, fp);
    fwrite(&current->price, sizeof(double), 1, fp);

    // The string (plus the null byte)
    fwrite(current->name.c_str(), sizeof(char), current->name.length() + 1, fp);
    // newline to indicate new node
    if (current->next != NULL)
        fprintf(fp, "\n");

    current = current->next;
}

fclose(fp);


问:
C# return search results (items) if a given user input is contained within that item
I've successfully created a class that contains a method which return a list of items paths within a given directory.

Problem is, the search criteria only return search results that initially include the user's input.

What I would like is that the search results will include any item that contains the user's input anywhere within the string of the item, not just if it starts with the input provided by the user.

Here is the source code:

```<code>    public class SearchManager
    {
        //Returns a list of items that contain the user's input within a given path
        public static List<string> SearchResults(string current_path, string user_input)
        {
            //Here we access the class 'DirectoryInfo'
            DirectoryInfo dir_info = new DirectoryInfo(current_path);

            //This array stores all the directories found within the current path/directory
            DirectoryInfo[] directories = dir_info.GetDirectories(user_input + "*", SearchOption.TopDirectoryOnly);
            //This array stores all the files found within the current path/directory
            FileInfo[] files = dir_info.GetFiles(user_input + "*", SearchOption.TopDirectoryOnly);

            //This list will store both directories and files found within the search result
            List<string> ItemsFound = new List<string>();

            //Here we loop through each item within both arrays in order to populate that list of items

            //Adds all the given paths of the directories
            foreach (DirectoryInfo dir in directories)
                ItemsFound.Add(dir.FullName);

            //Adds all the given paths of the files
            foreach (FileInfo file in files)
                ItemsFound.Add(file.FullName);

            //Here, we return a list of items data, from our search result to populate the data grid
            return ItemsFound;
        }
</code>```

How do I solve this issue?
Thanks! :)

答:
you can simply add a wildcard at the beginning as well like this :

//This array stores all the directories found within the current path/directory
DirectoryInfo[] directories = dir_info.GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly);
//This array stores all the files found within the current path/directory
FileInfo[] files = dir_info.GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly);
```

<p>Moreover, you can use linq to shorten your entire method.</p>

<pre class="lang-cs prettyprint-override"><code>public static List<string> SearchResults(string current_path, string user_input)
{
    //Here we access the class 'DirectoryInfo'
    DirectoryInfo dir_info = new DirectoryInfo(current_path);
    //This array stores all the directories found within the current path/directory
    DirectoryInfo[] directories = dir_info.GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly);
    //This array stores all the files found within the current path/directory
    FileInfo[] files = dir_info.GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly);

    //This list will store both directories and files found within the search result
    List<string> ItemsFound = new List<string>(); ;
    ItemsFound.AddRange(directories.Select(x => x.FullName));
    ItemsFound.AddRange(files.Select(x => x.FullName));

    //Here, we return a list of items data, from our search result to populate the data grid
    return ItemsFound;
}
</code>```

Or even shorter by combining the dir_info into the linq :

public static List<string> SearchResults(string current_path, string user_input)
{
    //Here we access the class 'DirectoryInfo'
    DirectoryInfo dir_info = new DirectoryInfo(current_path);

    //This list will store both directories and files found within the search result
    List<string> ItemsFound = new List<string>();
    ItemsFound.AddRange(dir_info.GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly).Select(x => x.FullName));
    ItemsFound.AddRange(dir_info.GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly).Select(x => x.FullName));

    //Here, we return a list of items data, from our search result to populate the data grid
    return ItemsFound;
}
```

<p>Or even shorter, but I dont recommend doing this (im just having fine and having nothing to do right now)</p>

<pre class="lang-cs prettyprint-override"><code>public static List<string> SearchResults(string current_path, string user_input)
            => (new DirectoryInfo(current_path)).GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly).Select(x => x.FullName).Concat(((new DirectoryInfo(current_path)).GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly).Select(x => x.FullName))).ToList();
</code>```

Body:
I've successfully created a class that contains a method which return a list of items paths within a given directory.

Problem is, the search criteria only return search results that initially include the user's input.

What I would like is that the search results will include any item that contains the user's input anywhere within the string of the item, not just if it starts with the input provided by the user.

Here is the source code:

    public class SearchManager
    {
        //Returns a list of items that contain the user's input within a given path
        public static List<string> SearchResults(string current_path, string user_input)
        {
            //Here we access the class 'DirectoryInfo'
            DirectoryInfo dir_info = new DirectoryInfo(current_path);

            //This array stores all the directories found within the current path/directory
            DirectoryInfo[] directories = dir_info.GetDirectories(user_input + "*", SearchOption.TopDirectoryOnly);
            //This array stores all the files found within the current path/directory
            FileInfo[] files = dir_info.GetFiles(user_input + "*", SearchOption.TopDirectoryOnly);

            //This list will store both directories and files found within the search result
            List<string> ItemsFound = new List<string>();

            //Here we loop through each item within both arrays in order to populate that list of items

            //Adds all the given paths of the directories
            foreach (DirectoryInfo dir in directories)
                ItemsFound.Add(dir.FullName);

            //Adds all the given paths of the files
            foreach (FileInfo file in files)
                ItemsFound.Add(file.FullName);

            //Here, we return a list of items data, from our search result to populate the data grid
            return ItemsFound;
        }

How do I solve this issue?
Thanks! :)

Body:
you can simply add a wildcard at the beginning as well like this :

//This array stores all the directories found within the current path/directory
DirectoryInfo[] directories = dir_info.GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly);
//This array stores all the files found within the current path/directory
FileInfo[] files = dir_info.GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly);

Moreover, you can use linq to shorten your entire method.

public static List<string> SearchResults(string current_path, string user_input)
{
    //Here we access the class 'DirectoryInfo'
    DirectoryInfo dir_info = new DirectoryInfo(current_path);
    //This array stores all the directories found within the current path/directory
    DirectoryInfo[] directories = dir_info.GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly);
    //This array stores all the files found within the current path/directory
    FileInfo[] files = dir_info.GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly);

    //This list will store both directories and files found within the search result
    List<string> ItemsFound = new List<string>(); ;
    ItemsFound.AddRange(directories.Select(x => x.FullName));
    ItemsFound.AddRange(files.Select(x => x.FullName));

    //Here, we return a list of items data, from our search result to populate the data grid
    return ItemsFound;
}

Or even shorter by combining the dir_info into the linq :

public static List<string> SearchResults(string current_path, string user_input)
{
    //Here we access the class 'DirectoryInfo'
    DirectoryInfo dir_info = new DirectoryInfo(current_path);

    //This list will store both directories and files found within the search result
    List<string> ItemsFound = new List<string>();
    ItemsFound.AddRange(dir_info.GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly).Select(x => x.FullName));
    ItemsFound.AddRange(dir_info.GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly).Select(x => x.FullName));

    //Here, we return a list of items data, from our search result to populate the data grid
    return ItemsFound;
}

Or even shorter, but I dont recommend doing this (im just having fine and having nothing to do right now)

public static List<string> SearchResults(string current_path, string user_input)
            => (new DirectoryInfo(current_path)).GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly).Select(x => x.FullName).Concat(((new DirectoryInfo(current_path)).GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly).Select(x => x.FullName))).ToList();


问:
How to send notifications from php server side to Visual Basic client side like android
Is it possible to send a notification from php server side to Visual Basic or do I have to synchronize the server side database with the local database every x minutes to check for any changes?</p>

```<code><?php
require("connection.php");
include 'send_notification.php';
if (!$conn) {
    $response["response"] = false;
    $response["log"] = mysqli_error($conn);
    $response["exception"] = 1;
    echo json_encode($response);
} else {
    $pricing = json_decode($_POST['pricing'], true);
    $user = json_decode($_POST['user'], true);

    // Here update database....

    $company_token = getCompanyToken($user["id"]); // Find company token from MySql database to send FCM to Android Client

    sendNotification($company_token); // Send Notification To Android...It works fine..

    // Same notification to Visual Basic Windows Client...
    // Help!! Synchronize local database with the server or is there any other way?

    }
    mysqli_close($conn);
    }
?>
</code>```

答:
The only official SDKs for receiving messages from Firebase Cloud Messaging are for Android, iOS, and Web clients. Unless you are targeting one of these platforms, there is no SDK for receiving messages on VB.Net.

Also see:

How to receive push notifications from Firebase cloud messaging

Is it possible to receive FCM in .NET Core App (e.g. WPF Core client)

Body:
Is it possible to send a notification from php server side to Visual Basic or do I have to synchronize the server side database with the local database every x minutes to check for any changes?

<?php
require("connection.php");
include 'send_notification.php';
if (!$conn) {
    $response["response"] = false;
    $response["log"] = mysqli_error($conn);
    $response["exception"] = 1;
    echo json_encode($response);
} else {
    $pricing = json_decode($_POST['pricing'], true);
    $user = json_decode($_POST['user'], true);

    // Here update database....

    $company_token = getCompanyToken($user["id"]); // Find company token from MySql database to send FCM to Android Client

    sendNotification($company_token); // Send Notification To Android...It works fine..

    // Same notification to Visual Basic Windows Client...
    // Help!! Synchronize local database with the server or is there any other way?

    }
    mysqli_close($conn);
    }
?>


答:
change the searchpattern = *userinput*</p>

```<code>        DirectoryInfo[] directories = dir_info.GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly);
        //This array stores all the files found within the current path/directory
        FileInfo[] files = dir_info.GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly);
</code>```

Title: C# return search results (items) if a given user input is contained within that item

Body:
change the searchpattern = *userinput*

        DirectoryInfo[] directories = dir_info.GetDirectories("*" + user_input + "*", SearchOption.TopDirectoryOnly);
        //This array stores all the files found within the current path/directory
        FileInfo[] files = dir_info.GetFiles("*" + user_input + "*", SearchOption.TopDirectoryOnly);


问:
How to reverse the index value in Python using for loop with a given list
I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

For example: a given list

test_board = ['O','O','X','X','X','O','X','O','X']

That show print out like this:

```<code> X | O | X
---|---|---
 X | X | O
---|---|---
 O | O | X
</code>```

I wrote this function:

```<code>def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
</code>```

But i get this print out when i call the function with the given list:

```<code>test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)
</code>```

Output:

```<code> X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O

</code>```

Edited:
Can i use for loop to achieve this without writing multiple print statement like this:

```<code>print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")
</code>```

答:
In your second for you are printing it 3 times before going to the next line.

Your function with the following modifications would work for your problem:

```<code>def display_board(board):
h_sep = '-' * 3
for i in reversed(range(3)):

    print(f"{board[i*3]:^3}|{board[i*3+1]:^3}|{board[i*3+2]:^3}")

    if i != 0:
        print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
</code>```

Body:
I want to create a function that prints out a tic-tac-toe board with a given list that position its index value on the board in a reverse order like on a number keyboard that is from 9 to 1, with the 1st row having the index value of 7, 8, 9: 2nd row 4, 5, 6: 3rd row 1, 2, 3.

For example: a given list

test_board = ['O','O','X','X','X','O','X','O','X']

That show print out like this:

 X | O | X
---|---|---
 X | X | O
---|---|---
 O | O | X

I wrote this function:

def display_board(board):

    h_sep = '-' * 3
    for i in range(3):

        for j in reversed(board[1:]):

            print(f"{j:^3}|{j:^3}|{j:^3}")

        if i != 2:
            print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")

But i get this print out when i call the function with the given list:

test_board = ['O','O','X','X','X','O','X','O','X']
display_board(test_board)

Output:

 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O
---|---|---
 X | X | X
 O | O | O
 X | X | X
 O | O | O
 X | X | X
 X | X | X
 X | X | X
 O | O | O

Edited:
Can i use for loop to achieve this without writing multiple print statement like this:

print(f"{board[6]:^3}|{board[7]:^3}|{board[8]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[3]:^3}|{board[4]:^3}|{board[5]:^3}")
print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")
print(f"{board[0]:^3}|{board[1]:^3}|{board[2]:^3}")

Body:
In your second for you are printing it 3 times before going to the next line.

Your function with the following modifications would work for your problem:

def display_board(board):
h_sep = '-' * 3
for i in reversed(range(3)):

    print(f"{board[i*3]:^3}|{board[i*3+1]:^3}|{board[i*3+2]:^3}")

    if i != 0:
        print(f"{h_sep:^3}|{h_sep:^3}|{h_sep:^3}")