问:
Build a slider based on the data returned from API call
Need to build a slider (carousel) which should be based on the data returned from the API call. There are 3 values which I need to pull. image, title and description.

It must be a picture, heading, and description (on each slide, pulled from JSON).

jQuery

```<code>var myJSON = 'apiCall';
$.getJSON('myJSON, { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<img>', {
        }));
    });
});
</code>```

HTML

```<code>   <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
             <ol class="carousel-indicators">
               <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-80" src="..." alt="First slide">
        <div class="carousel-caption d-none d-md-block">
         <h5></h5>
         <p></p>
        </div>
    </div>
    <div class="carousel-item">
      <img class="d-block w-80" src="..." alt="Second slide">
        <div class="carousel-caption d-none d-md-block">
         <h5></h5>
         <p></p>
        </div>
  </div>
    </div>
    <div class="carousel-item">
      <img class="d-block w-80" src="..." alt="Third slide">
       <div class="carousel-caption d-none d-md-block">
         <h5></h5>
         <p></p>
       </div>
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</code>```

答:
```<code>let html = `
<div class="carousel-item">
      <img class="d-block w-80" src="${imgSrc}" alt="Second slide">
        <div class="carousel-caption d-none d-md-block">
         <h5>${title}</h5>
         <p>${parangraph}</p>
        </div>
  </div>
`
$(".carousel-inner")[0].append(html)
</code>```

Put the above code in a loop, and you should be all set.
The imgSrc, title and parangraph should be dynamically generated from your API calls.

Body:
Need to build a slider (carousel) which should be based on the data returned from the API call. There are 3 values which I need to pull. image, title and description.

It must be a picture, heading, and description (on each slide, pulled from JSON).

jQuery

var myJSON = 'apiCall';
$.getJSON('myJSON, { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('', {
        }));
    });
});

HTML

    Previous

    Next

Body:
let html = `
<div class="carousel-item">
      <img class="d-block w-80" src="${imgSrc}" alt="Second slide">
        <div class="carousel-caption d-none d-md-block">
         <h5>${title}</h5>
         <p>${parangraph}</p>
        </div>
  </div>
`
$(".carousel-inner")[0].append(html)

Put the above code in a loop, and you should be all set.
The imgSrc, title and parangraph should be dynamically generated from your API calls.


来源: stackexchange

问:
Decorator pattern for a Customer class
Suppose I have a Customer class. A customer can have multiple kinds of loyalty points. For one promotion, the customer may be collecting Rewards. In another, the customer may be collecting Miles. And there is no fixed number of kinds of loyalty points that the Customer is built for. I am sure this is a common use case. Is the decorator pattern a good fit given below sample code?

```<code>    public interface ICustomer
    {
        void Display();
    }

    public class SimpleCustomer : ICustomer
    {
        public void Display()
        {
            Console.WriteLine("I am simple customer");
        }
    }

    public abstract class CustomerDecorator : ICustomer
    {
        protected ICustomer customer;

        public CustomerDecorator(ICustomer customer)
        {
            this.customer = customer ?? throw new ArgumentNullException("customer");
        }

        public abstract void Display();
    }

    public class RewardsDecorator : CustomerDecorator
    {
        private int rewards;
        public RewardsDecorator(ICustomer customer, int rewards) : base(customer)
        {
            this.rewards = rewards;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + rewards.ToString() + " rewards");
        }
    }

    public class MilesDecorator : CustomerDecorator
    {
        private int miles;
        public MilesDecorator(ICustomer customer, int miles) : base(customer)
        {
            this.miles = miles;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + miles.ToString() + " miles");
        }
    }
</code>```

答:
Don't think Decorator pattern does what you want it to do. Decorator adds new functionalities on top of the original class. A typical wiki example would say, we can add scroll bar, menu bar, overlays and other UI components on top of canvas. So to make a proper browser window, so you will have:

```<code>public class Canvas
public class ScrollableCanvas
public class OverlayedCanvas
etc.
</code>```

So that we add more functionalities to the original Canvas.

To solve your problem, you should have something like:

```<code>public abstract class LoyaltyProgramAccount {...}

public class RewardAccount extends LoyaltyProgramAccount {...}

public class MilesAccount extends LoyaltyProgramAccount {...}
</code>```

And then add a registery-ish enum:

```<code>public enum LoyaltyProgramTypes {
    miles,
    reward,
}
</code>```

and then let user be:

```<code>public class Customer {

    private List<LoyaltyProgramTypes, LoyaltyProgramAccount> accounts;

    public void openAccount(LoyaltyProgramTypes type, LoyaltyProgramAccount account) {
        accounts.put(type, account);
    }
    ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Decorator pattern for a Customer class

Body:
Suppose I have a Customer class. A customer can have multiple kinds of loyalty points. For one promotion, the customer may be collecting Rewards. In another, the customer may be collecting Miles. And there is no fixed number of kinds of loyalty points that the Customer is built for. I am sure this is a common use case. Is the decorator pattern a good fit given below sample code?

    public interface ICustomer
    {
        void Display();
    }

    public class SimpleCustomer : ICustomer
    {
        public void Display()
        {
            Console.WriteLine("I am simple customer");
        }
    }

    public abstract class CustomerDecorator : ICustomer
    {
        protected ICustomer customer;

        public CustomerDecorator(ICustomer customer)
        {
            this.customer = customer ?? throw new ArgumentNullException("customer");
        }

        public abstract void Display();
    }

    public class RewardsDecorator : CustomerDecorator
    {
        private int rewards;
        public RewardsDecorator(ICustomer customer, int rewards) : base(customer)
        {
            this.rewards = rewards;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + rewards.ToString() + " rewards");
        }
    }

    public class MilesDecorator : CustomerDecorator
    {
        private int miles;
        public MilesDecorator(ICustomer customer, int miles) : base(customer)
        {
            this.miles = miles;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + miles.ToString() + " miles");
        }
    }

Body:
Don't think Decorator pattern does what you want it to do. Decorator adds new functionalities on top of the original class. A typical wiki example would say, we can add scroll bar, menu bar, overlays and other UI components on top of canvas. So to make a proper browser window, so you will have:

public class Canvas
public class ScrollableCanvas
public class OverlayedCanvas
etc.

So that we add more functionalities to the original Canvas.

To solve your problem, you should have something like:

public abstract class LoyaltyProgramAccount {...}

public class RewardAccount extends LoyaltyProgramAccount {...}

public class MilesAccount extends LoyaltyProgramAccount {...}

And then add a registery-ish enum:

public enum LoyaltyProgramTypes {
    miles,
    reward,
}

and then let user be:

public class Customer {

    private List<LoyaltyProgramTypes, LoyaltyProgramAccount> accounts;

    public void openAccount(LoyaltyProgramTypes type, LoyaltyProgramAccount account) {
        accounts.put(type, account);
    }
    ...
}


问:
Will this code with unbuffered channel cause goroutine leak in Go?
I'm writing some golang concurrency codes with goroutines and channels, suspecting that my code may cause goroutine leaks. My situation is similar to the following code, or you can open this go playground link.

func main() {
    numCount := 3
    numChan := make(chan int)

    for i := 0; i < numCount; i++ {
        go func(num int) {
            fmt.Printf("Adding num: %d to chan\n", num)
            numChan <- num
            fmt.Printf("Adding num: %d to chan Done\n", num)
        }(i)
    }

    time.Sleep(time.Second)
    panic("Goroutine Resource Leak Test")
}
```

<p>In my opinion, when the main goroutine returns, three goroutines are blocked sending to the unbuffered channel and there will be goroutine leak. This post goroutine leak with buffered channel in Go also suggests that <code>So only if the channel was unbuffered the leak would occur</code>. </p>

<p><em>The Go Programming Language</em> suggests that: </p>

<blockquote>
  <p>There’s a handy trick we can use during testing: if instead of returning from main in the event of cancellation, we execute a call to panic, then the runtime will dump the stack of every goroutine in the program. If the main goroutine is the only one left, then it has cleaned up after itself. But if other goroutines remain, they may not have been properly canceled, or perhaps they have been canceled but the cancellation takes time; a little investigation may be worthwhile. The panic dump often contains sufﬁcient information to distinguish these cases.</p>
</blockquote>

<p>Therefore, I added <code>panic("Goroutine Resource Leak Test")</code> to the end of the main function to verify my assumption. However, the panic dump only contains main goroutine, that is, there is no resource leak.</p>

```Adding num: 0 to chan
Adding num: 1 to chan
Adding num: 2 to chan
panic: Goroutine Resource Leak Test

goroutine 1 [running]:
main.main()
    /tmp/sandbox011109649/prog.go:21 +0xc0
```

Can someone help explain

why there is no goroutine leak, or

how should I get the correct panic dump if there is leak

Any suggestion will be appreciated, thanks in advance!

答:
The problem with your code is twofold.

First, there is, theoretically, a goroutine leak since any attempt to send a value to a channel with zero capacity (an unbuffered channel or a filled up buffered channel) blocks the sending goroutine until a receive operation is done on that channel.

So, yes, by definition of how channels work, all your three goroutines will be blocked in the numChan <- num statement.

Second, since some revision of Go, an unhandled panic by default dumps only the stack trace of the panicking goroutine.
If you wish to dump the stacks of all the active goroutines, you'd have to tweak the runtime — from the documentation of the package runtime:

The GOTRACEBACK variable controls the amount of output generated when a Go program fails due to an unrecovered panic or an unexpected runtime condition. By default, a failure prints a stack trace for the current goroutine, eliding functions internal to the run-time system, and then exits with exit code 2. The failure prints stack traces for all goroutines if there is no current goroutine or the failure is internal to the run-time. GOTRACEBACK=none omits the goroutine stack traces entirely. GOTRACEBACK=single (the default) behaves as described above. GOTRACEBACK=all adds stack traces for all user-created goroutines. GOTRACEBACK=system is like “all” but adds stack frames for run-time functions and shows goroutines created internally by the run-time. GOTRACEBACK=crash is like “system” but crashes in an operating system-specific manner instead of exiting. For example, on Unix systems, the crash raises SIGABRT to trigger a core dump. For historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for none, all, and system, respectively. The runtime/debug package's SetTraceback function allows increasing the amount of output at run time, but it cannot reduce the amount below that specified by the environment variable. See https://golang.org/pkg/runtime/debug/#SetTraceback.

Also note that you must not ever use timers for (simulating) synchronization: in a toy example this might work but in real life nothing prevents your three goroutines from not having a chance to be run during the time span your main goroutine spent in the call to time.Sleep — so the outcome might be that any number of spawned goroutines had run: from 0 to 3.

Add there the fact that when main exits the runtime merely kills all the outstanding active goroutines, and the result of the test might be surprising at best.

Hence a proper solution would be to

Merely print the stacks where needed,

Make sure you synchronize the sends by the matching receives:

package main

import (
    "fmt"
    "log"
    "runtime"
)

func dumpStacks() {
    buf := make([]byte, 32 * 1024)
    n := runtime.Stack(buf, true)
    log.Println(string(buf[:n]))
}

func main() {
    numCount := 3
    numChan := make(chan int, numCount)

    for i := 0; i < numCount; i++ {
        go func(num int) {
            fmt.Printf("Adding num: %d to chan\n", num)
            numChan <- num
            fmt.Printf("Adding num: %d to chan Done\n", num)
        }(i)
    }

    dumpStacks()

    for i := 0; i < numCount; i++ {
        <-numChan
    }
}
```

Playground.

Body:
I'm writing some golang concurrency codes with goroutines and channels, suspecting that my code may cause goroutine leaks. My situation is similar to the following code, or you can open this go playground link.

func main() {
    numCount := 3
    numChan := make(chan int)

    for i := 0; i < numCount; i++ {
        go func(num int) {
            fmt.Printf("Adding num: %d to chan\n", num)
            numChan <- num
            fmt.Printf("Adding num: %d to chan Done\n", num)
        }(i)
    }

    time.Sleep(time.Second)
    panic("Goroutine Resource Leak Test")
}

In my opinion, when the main goroutine returns, three goroutines are blocked sending to the unbuffered channel and there will be goroutine leak. This post goroutine leak with buffered channel in Go also suggests that So only if the channel was unbuffered the leak would occur.

The Go Programming Language suggests that:

There’s a handy trick we can use during testing: if instead of returning from main in the event of cancellation, we execute a call to panic, then the runtime will dump the stack of every goroutine in the program. If the main goroutine is the only one left, then it has cleaned up after itself. But if other goroutines remain, they may not have been properly canceled, or perhaps they have been canceled but the cancellation takes time; a little investigation may be worthwhile. The panic dump often contains sufﬁcient information to distinguish these cases.

Therefore, I added panic("Goroutine Resource Leak Test") to the end of the main function to verify my assumption. However, the panic dump only contains main goroutine, that is, there is no resource leak.

Adding num: 0 to chan
Adding num: 1 to chan
Adding num: 2 to chan
panic: Goroutine Resource Leak Test

goroutine 1 [running]:
main.main()
    /tmp/sandbox011109649/prog.go:21 +0xc0

Can someone help explain

why there is no goroutine leak, or

how should I get the correct panic dump if there is leak

Any suggestion will be appreciated, thanks in advance!

Body:
The problem with your code is twofold.

First, there is, theoretically, a goroutine leak since any attempt to send a value to a channel with zero capacity (an unbuffered channel or a filled up buffered channel) blocks the sending goroutine until a receive operation is done on that channel.

So, yes, by definition of how channels work, all your three goroutines will be blocked in the numChan <- num statement.

Second, since some revision of Go, an unhandled panic by default dumps only the stack trace of the panicking goroutine.
If you wish to dump the stacks of all the active goroutines, you'd have to tweak the runtime — from the documentation of the package runtime:

The GOTRACEBACK variable controls the amount of output generated when a Go program fails due to an unrecovered panic or an unexpected runtime condition. By default, a failure prints a stack trace for the current goroutine, eliding functions internal to the run-time system, and then exits with exit code 2. The failure prints stack traces for all goroutines if there is no current goroutine or the failure is internal to the run-time. GOTRACEBACK=none omits the goroutine stack traces entirely. GOTRACEBACK=single (the default) behaves as described above. GOTRACEBACK=all adds stack traces for all user-created goroutines. GOTRACEBACK=system is like “all” but adds stack frames for run-time functions and shows goroutines created internally by the run-time. GOTRACEBACK=crash is like “system” but crashes in an operating system-specific manner instead of exiting. For example, on Unix systems, the crash raises SIGABRT to trigger a core dump. For historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for none, all, and system, respectively. The runtime/debug package's SetTraceback function allows increasing the amount of output at run time, but it cannot reduce the amount below that specified by the environment variable. See https://golang.org/pkg/runtime/debug/#SetTraceback.

Also note that you must not ever use timers for (simulating) synchronization: in a toy example this might work but in real life nothing prevents your three goroutines from not having a chance to be run during the time span your main goroutine spent in the call to time.Sleep — so the outcome might be that any number of spawned goroutines had run: from 0 to 3.

Add there the fact that when main exits the runtime merely kills all the outstanding active goroutines, and the result of the test might be surprising at best.

Hence a proper solution would be to

Merely print the stacks where needed,

Make sure you synchronize the sends by the matching receives:

package main

import (
    "fmt"
    "log"
    "runtime"
)

func dumpStacks() {
    buf := make([]byte, 32 * 1024)
    n := runtime.Stack(buf, true)
    log.Println(string(buf[:n]))
}

func main() {
    numCount := 3
    numChan := make(chan int, numCount)

    for i := 0; i < numCount; i++ {
        go func(num int) {
            fmt.Printf("Adding num: %d to chan\n", num)
            numChan <- num
            fmt.Printf("Adding num: %d to chan Done\n", num)
        }(i)
    }

    dumpStacks()

    for i := 0; i < numCount; i++ {
        <-numChan
    }
}

Playground.


问:
"ValueError: could not convert string to float: " machine learning fit classifier
When I try to fit classifier I got error:

ValueError: could not convert string to float: '4/1/2010'

```<code># Load the Pandas libraries with alias 'pd'
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from math import sqrt
from ml_metrics import rmse

# Read data from file 'filename.csv'
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later)
data = pd.read_csv("NASDAQ.csv")
data.dropna(inplace=True)

#df.drop_duplicates(inplace=True)
nInstances, nAttributes = data.shape
if data.shape[0]:
    train = data[:1762]
    test = data[1762:]
x_train= train.values[:,0:nAttributes-1]
y_train= train.values[:,nAttributes-1]

# classifiers Linear Regression, Logistic Regression, kNN, SVM και MLP
clf = LinearRegression().fit(x_train, y_train)
</code>```

could you please check this and help me out to figure where is the issue ?

答: Specifically for the date column, you can use parse_dates=['column name'] when reading the csv as suggested by this answer.

Body:
When I try to fit classifier I got error:

ValueError: could not convert string to float: '4/1/2010'

# Load the Pandas libraries with alias 'pd'
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from math import sqrt
from ml_metrics import rmse

# Read data from file 'filename.csv'
# (in the same directory that your python process is based)
# Control delimiters, rows, column names with read_csv (see later)
data = pd.read_csv("NASDAQ.csv")
data.dropna(inplace=True)

#df.drop_duplicates(inplace=True)
nInstances, nAttributes = data.shape
if data.shape[0]:
    train = data[:1762]
    test = data[1762:]
x_train= train.values[:,0:nAttributes-1]
y_train= train.values[:,nAttributes-1]

# classifiers Linear Regression, Logistic Regression, kNN, SVM και MLP
clf = LinearRegression().fit(x_train, y_train)

could you please check this and help me out to figure where is the issue ?


问:
using spring boot app as resource server and google oauth2 as authorization server
I have a web app using angular6 for frontend and spring boot for the rest apis.

My angular app is running on localhost:4200 and is able to authenticate successfully with google and I can see authToken and idToken. (I used angularx-social-login plugin in angular)

Now, I want to use this auth token to secure my spring boot api server running at localhost:8080 as well.

I am trying to do similar to (image source)

Here client is my angular app, resource server is spring boot application and authorization server is google

I tried using EnableResourceServer annotation and many different approaches but nothing seems to work. It always gives me invalid token by checking in memory token store and doesn't even try to validate with google for the right token.

I am using the same client-id and secret for the oauth2 configuration in spring app and angular app.

How can I make spring boot application validate the token with google for every request?

My application.properties

```<code>server.servlet.context-path=/api

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:file:~/h2/testdb

logging.level.org.springframework.web=TRACE
logging.level.org.springframework.security=TRACE
logging.level.org.hibernate=TRACE

security.oauth2.resource.filter-order = 3
spring.security.oauth2.client.registration.google.client-id=#google-client-id
spring.security.oauth2.client.registration.google.client-secret=#google-client-secret
security.oauth2.resource.user-info-uri= https://www.googleapis.com/oauth2/v3/userinfo # URI of the user endpoint.
</code>```

Here is my resource server configuration class

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "rest_api";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .requestMatcher(new RequestHeaderRequestMatcher("Authorization"))
            .authorizeRequests().anyRequest().fullyAuthenticated();
    }

    @EnableGlobalMethodSecurity(prePostEnabled = true)
    protected static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }
    }
}
```

答:
Hopefully you've already found a solution. Otherwise have a look at this article.

On a side note: you're declaring the resource stateful

```<code>resources.resourceId(RESOURCE_ID).stateless(false);
</code>```

Have you tried using it stateless?

```<code>resources.resourceId(RESOURCE_ID).stateless(true);
</code>```

Body:
I have a web app using angular6 for frontend and spring boot for the rest apis.

My angular app is running on localhost:4200 and is able to authenticate successfully with google and I can see authToken and idToken. (I used angularx-social-login plugin in angular)

Now, I want to use this auth token to secure my spring boot api server running at localhost:8080 as well.

I am trying to do similar to (image source)

Here client is my angular app, resource server is spring boot application and authorization server is google

I tried using EnableResourceServer annotation and many different approaches but nothing seems to work. It always gives me invalid token by checking in memory token store and doesn't even try to validate with google for the right token.

I am using the same client-id and secret for the oauth2 configuration in spring app and angular app.

How can I make spring boot application validate the token with google for every request?

My application.properties

server.servlet.context-path=/api

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:file:~/h2/testdb

logging.level.org.springframework.web=TRACE
logging.level.org.springframework.security=TRACE
logging.level.org.hibernate=TRACE

security.oauth2.resource.filter-order = 3
spring.security.oauth2.client.registration.google.client-id=#google-client-id
spring.security.oauth2.client.registration.google.client-secret=#google-client-secret
security.oauth2.resource.user-info-uri= https://www.googleapis.com/oauth2/v3/userinfo # URI of the user endpoint.

Here is my resource server configuration class

@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "rest_api";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(RESOURCE_ID).stateless(false);
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .requestMatcher(new RequestHeaderRequestMatcher("Authorization"))
            .authorizeRequests().anyRequest().fullyAuthenticated();
    }

    @EnableGlobalMethodSecurity(prePostEnabled = true)
    protected static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration {
        @Override
        protected MethodSecurityExpressionHandler createExpressionHandler() {
            return new OAuth2MethodSecurityExpressionHandler();
        }
    }
}

Body:
Hopefully you've already found a solution. Otherwise have a look at this article.

On a side note: you're declaring the resource stateful

resources.resourceId(RESOURCE_ID).stateless(false);

Have you tried using it stateless?

resources.resourceId(RESOURCE_ID).stateless(true);


问:
Flutter device shake iOS plugin
Evening guys,

Im looking into building a plugin for Flutter that detects if the device is shaking. Now i've found how to technically do it in Swift (Detect shake gesture IOS Swift) but im stuck on how to hook it up as a Flutter plugin, because i don't have direct access to the view controller lifecycle events.

Need a way to hook up

viewDidLoad

canBecomeFirstResponder

motionEnded

Can anyone nudge me in the right direction?

答:
You could try this plugin: shake_event

It's pretty simple to work with and works both for iOS and Android.

Title: Flutter device shake iOS plugin


问:
Request mapping not working between jsp page and a method in controller
I have a spring mvc project. Im trying to delete an announcement but im getting a 404 error and it cant seem to find the method. All my other mapping is working fine and Ive done this the same way so I cant seem to figure out where I went wrong

This is my link for the button to delete the announcement, it is correctly getting the ID in the url so i know this works

```<code><c:url value="/deleteAnnouncement?id=" var="deleteAnnouncementURL" />

<security:authorize access="hasRole('ADMIN')">
<a href= "${deleteAnnouncementURL}${announcements.id}" class= "btn-outline-danger btn-sm pull-right">Delete</a>
</security:authorize>
</code>```

This is my method in my controller

```<code>@RequestMapping(value = {"/deleteAnnouncement/{id}"}, method = RequestMethod.GET)
public String deleteAnnouncement(@PathVariable("id") int id, Model model)
    {

        Announcement announcement = announcementService.findOne(id);
        announcementService.deleteAnnouncement(announcement);
        return "success";
    }
</code>```

Any help would be appreciated!

答:
The way you are sending the request is wrong.

From front end the value you are sending as a request parameter but in backend you are receiving it as a path variable.

Change value="/deleteAnnouncement?id=

to

value="/deleteAnnouncement

and add slash between URL and id like below.

${deleteAnnouncementURL}/${announcements.id}

Body:
I have a spring mvc project. Im trying to delete an announcement but im getting a 404 error and it cant seem to find the method. All my other mapping is working fine and Ive done this the same way so I cant seem to figure out where I went wrong

This is my link for the button to delete the announcement, it is correctly getting the ID in the url so i know this works

<c:url value="/deleteAnnouncement?id=" var="deleteAnnouncementURL" />

<security:authorize access="hasRole('ADMIN')">
Delete
</security:authorize>

This is my method in my controller

@RequestMapping(value = {"/deleteAnnouncement/{id}"}, method = RequestMethod.GET)
public String deleteAnnouncement(@PathVariable("id") int id, Model model)
    {

        Announcement announcement = announcementService.findOne(id);
        announcementService.deleteAnnouncement(announcement);
        return "success";
    }

Any help would be appreciated!


问:
When using jQuery's ".nextAll()", how would i make "$(this)" equal the current element?
im trying to get an element, then every element after that make the placeholder attribute of #taskid the current value - 1

this is what im currently working with:

```<code>$(this).nextAll('div').find('#taskid').attr('placeholder', ((parseInt($(this)
    .find('#taskid').attr('placeholder')) - 1).toString()))
</code>```

html:

```<code><div id="i0HYh" class="task" select="yes" style="background-color: rgb(240, 239, 255);">
  <input type="text" name="taskid" placeholder="1" readonly="" id="taskid">
  <input type="text" name="email1" placeholder="sdf" readonly="">
  <input type="text" name="taskproxy" id="esfes" placeholder="N/A" readonly="">
  <div id="headlessbox">
    <p>t</p>
  </div>
  <input type="text" name="status" placeholder="Idle" readonly="">
</div>
</code>```

The above jquery line works, it just changes the placeholder value to the first elements value - 1

for example, if the first elements value was 1, the rest of them would be 0

example of the placeholders right now (before running above code):
1
2
3
4
5
6

example of the placeholders right now (after running above code):
1
0
0
0
0
0

what i want (before running above code):
1
2
3
4
5
6

what i want (after running above code):
1
1
2
3
4
5

(sorry if this makes no sense, im trying my best to explain :( )

答:
If I have understood what you try to do, this code should do what you want :

var pl = parseInt($("input[name='taskid']").first().attr('placeholder'));
$("input[name='taskid']").each(function() {
    $(this).attr('placeholder', pl--);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="i0HYh" class="task" select="yes" style="background-color: rgb(240, 239, 255);">
  <input type="text" name="taskid" placeholder="1" readonly="" id="taskid">
</div>

<div id="i0HYh" class="task" select="yes" style="background-color: rgb(240, 239, 255);">
  <input type="text" name="taskid" placeholder="1" readonly="" id="taskid">
</div></code>```

For the example I've cleaned the useless inputs.

So it iterates through all the inputs and set as placeholder value of the #taskId placeholder value - 1.

Body:
im trying to get an element, then every element after that make the placeholder attribute of #taskid the current value - 1

this is what im currently working with:

$(this).nextAll('div').find('#taskid').attr('placeholder', ((parseInt($(this)
    .find('#taskid').attr('placeholder')) - 1).toString()))

html:

  <input type="text" name="taskid" placeholder="1" readonly="" id="taskid">
  <input type="text" name="email1" placeholder="sdf" readonly="">
  <input type="text" name="taskproxy" id="esfes" placeholder="N/A" readonly="">

t

  <input type="text" name="status" placeholder="Idle" readonly="">

The above jquery line works, it just changes the placeholder value to the first elements value - 1

for example, if the first elements value was 1, the rest of them would be 0

example of the placeholders right now (before running above code):
1
2
3
4
5
6

example of the placeholders right now (after running above code):
1
0
0
0
0
0

what i want (before running above code):
1
2
3
4
5
6

what i want (after running above code):
1
1
2
3
4
5

(sorry if this makes no sense, im trying my best to explain :( )

Body:
If I have understood what you try to do, this code should do what you want :

var pl = parseInt($("input[name='taskid']").first().attr('placeholder'));
$("input[name='taskid']").each(function() {
    $(this).attr('placeholder', pl--);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="i0HYh" class="task" select="yes" style="background-color: rgb(240, 239, 255);">
  <input type="text" name="taskid" placeholder="1" readonly="" id="taskid">
</div>

<div id="i0HYh" class="task" select="yes" style="background-color: rgb(240, 239, 255);">
  <input type="text" name="taskid" placeholder="1" readonly="" id="taskid">
</div>

For the example I've cleaned the useless inputs.

So it iterates through all the inputs and set as placeholder value of the #taskId placeholder value - 1.


问:
OptimisticLockException using @Version vs ConcurrentModificationException
I have an entity:

```<code>@Entity
public class Book {

    @Version
    private Integer version;

}
</code>```

In concurent transaction I have an error OptimisticLockException because I used an @Version attribute. Without @Version I have an error:
ConcurrentModificationException.

What is the difrence between OptimisticLockException and ConcurrentModificationException?

答:
OptimisticLockException and ConcurrentModificationException (I assume it's from java.util) are two completely different exceptions and are not being thrown interchangeably.

First one, as its name suggest, are related to optimistic locking which basically means other transaction has committed changes to entities you were trying to update.

Second one is being thrown on concurrent modification of an object when such modification is not permissible. For example when you try to remove an element from a collection you're iterating through. I cannot deduce from the snippet you provided what exactly triggers this exception in your case but it is not related to optimistic locking and JPA in general.

Body:
I have an entity:

@Entity
public class Book {

    @Version
    private Integer version;

}

In concurent transaction I have an error OptimisticLockException because I used an @Version attribute. Without @Version I have an error:
ConcurrentModificationException.

What is the difrence between OptimisticLockException and ConcurrentModificationException?


问:
scipy.optimize.curve_fit run in Java using Runtime.getRuntime().exec()
I am running a curve fitting Python script in Java using Process p = Runtime.getRuntime().exec and Java is not getting output after one of my calls to scipy.optimize.curve_fit.
I am fitting to a piecewise error function as shown below.

I created a "dummy" version of the function to check that the curve fitting would work on that, and it did. But when I apply the curve fit to actual data, Java does not get any of the output below that statement.

I ran the Python code in the terminal and it worked fine.

Java code:

```<code>String[] command = new String[2];
command[0] = "python";
command[1] = "python/curvefit.py";

try {
    Process p = Runtime.getRuntime().exec(command);
    BufferedReader stdInput = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    while ((s1 = stdInput.readLine()) != null) {
        System.out.println(s1);
    }
}catch (IOException e) {
    e.printStackTrace();
}
</code>```

Python code

```<code>## modifiable error function
def easyerf(x,a,b,c, d):
    return a*scipy.special.erf((b * x) - c) + d

## piecewise error function
def pwerf(x, a1, a2, b, c1, c2, h, e):
    returnarray = []
    for i in x:
        if i < e:
            returnarray.append(easyerf(i, a1, b, c1, h - a1))
        else:
            returnarray.append(easyerf(i, a2, b, c2, h + a2))
    return returnarray

array = np.linspace(-5, 10, 15)
array2 = np.linspace(10, 25, 15)
array3 = [easyerf(i, 4, 1, 1, 1) for i in array]
array4 = [easyerf(i, -4, 1, 15, 1) for i in array2]
array5 = np.concatenate((array,array2)) # x values
array6 = np.concatenate((array3,array4)) # y values
pguess7 = [10, -4, 17, 1, 15, 1, 10]

par3, con3 = scipy.optimize.curve_fit(pwerf, array5, array6, p0 = pguess7)

print("got here")

indexes = [1, 2, 3, 4, 5, 6, 7, 8,... ## long array
intensities = [0.050938000000000004, 0.049611, 0.054938, 0.047958,... ## long array

## fit piecewise error function and find ends/length
par4, con4 = scipy.optimize.curve_fit(pwerf, indexes, intensities, [10, 1, 1, 5, 17, 25,120])
print("now got here")
</code>```

Java prints only the first "got here" but not the "now got here" that should follow after the second curve fit. Again, it works perfectly fine in the terminal. I need to get the output from the second curve fit. What's happening?

答: UPDATE: Figured it out. Java is running an older version of Python and requires the arguments of curve_fit to be numpy arrays, not lists.</p>

Body:
I am running a curve fitting Python script in Java using Process p = Runtime.getRuntime().exec and Java is not getting output after one of my calls to scipy.optimize.curve_fit.
I am fitting to a piecewise error function as shown below.

I created a "dummy" version of the function to check that the curve fitting would work on that, and it did. But when I apply the curve fit to actual data, Java does not get any of the output below that statement.

I ran the Python code in the terminal and it worked fine.

Java code:

String[] command = new String[2];
command[0] = "python";
command[1] = "python/curvefit.py";

try {
    Process p = Runtime.getRuntime().exec(command);
    BufferedReader stdInput = new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    while ((s1 = stdInput.readLine()) != null) {
        System.out.println(s1);
    }
}catch (IOException e) {
    e.printStackTrace();
}

Python code

## modifiable error function
def easyerf(x,a,b,c, d):
    return a*scipy.special.erf((b * x) - c) + d

## piecewise error function
def pwerf(x, a1, a2, b, c1, c2, h, e):
    returnarray = []
    for i in x:
        if i < e:
            returnarray.append(easyerf(i, a1, b, c1, h - a1))
        else:
            returnarray.append(easyerf(i, a2, b, c2, h + a2))
    return returnarray

array = np.linspace(-5, 10, 15)
array2 = np.linspace(10, 25, 15)
array3 = [easyerf(i, 4, 1, 1, 1) for i in array]
array4 = [easyerf(i, -4, 1, 15, 1) for i in array2]
array5 = np.concatenate((array,array2)) # x values
array6 = np.concatenate((array3,array4)) # y values
pguess7 = [10, -4, 17, 1, 15, 1, 10]

par3, con3 = scipy.optimize.curve_fit(pwerf, array5, array6, p0 = pguess7)

print("got here")

indexes = [1, 2, 3, 4, 5, 6, 7, 8,... ## long array
intensities = [0.050938000000000004, 0.049611, 0.054938, 0.047958,... ## long array

## fit piecewise error function and find ends/length
par4, con4 = scipy.optimize.curve_fit(pwerf, indexes, intensities, [10, 1, 1, 5, 17, 25,120])
print("now got here")

Java prints only the first "got here" but not the "now got here" that should follow after the second curve fit. Again, it works perfectly fine in the terminal. I need to get the output from the second curve fit. What's happening?


问:
Excel Formula to Match Items Within a Date Range
I'm trying to match a product sale date with the range date of sales. I have the following so far:

```<code>=INDEX(A3,MATCH(1,((H:H=A3)*(B:B>=I3)*(B:B<=J3)),0))
</code>```

I'm trying to have the formula produce a result if column A matches column H
and if column B is between column I & J, where J may not have occurred yet.

EDIT: column E15 isn't returning any results
See Here

答:
Could you use something like this in the cell where you want the value to occur?

```<code>=IF(A1=H1,IF(AND(I2<B2,B2<J2),TRUE,FALSE),FALSE)
</code>```

You can then replace "True" and "False" with other statements to produce different outcomes.

Body:
I'm trying to match a product sale date with the range date of sales. I have the following so far:

=INDEX(A3,MATCH(1,((H:H=A3)*(B:B>=I3)*(B:B<=J3)),0))

I'm trying to have the formula produce a result if column A matches column H
and if column B is between column I & J, where J may not have occurred yet.

EDIT: column E15 isn't returning any results
See Here

Body:
Could you use something like this in the cell where you want the value to occur?

=IF(A1=H1,IF(AND(I2<B2,B2<J2),TRUE,FALSE),FALSE)

You can then replace "True" and "False" with other statements to produce different outcomes.


问:
Rounding Numbers with bc in Bash
I want to compute an average with 3 decimal figures, rounded to nearest, using bc.

For example:

average of 3, 3 and 5 should yield 3.667

and

average of 3, 3 and 4 should yield 3.333

I tried:

```<code>echo "scale=3; $sum/$n+0.0005" | bc
</code>```

but scale doesn't behave as I expect. What can I do to solve my problem?

答:
This solution is not that flexibile (it just converts float to int), but it can deal with negative numbers:</p>

```<code>e=$( echo "scale=0; (${e}+0.5)/1" | bc -l )
if [[ "${e}" -lt 0 ]] ; then
    e=$(( e - 1 ))
fi
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rounding Numbers with bc in Bash

Body:
I want to compute an average with 3 decimal figures, rounded to nearest, using bc.

For example:

average of 3, 3 and 5 should yield 3.667

and

average of 3, 3 and 4 should yield 3.333

I tried:

echo "scale=3; $sum/$n+0.0005" | bc

but scale doesn't behave as I expect. What can I do to solve my problem?

Body:
This solution is not that flexibile (it just converts float to int), but it can deal with negative numbers:

e=$( echo "scale=0; (${e}+0.5)/1" | bc -l )
if [[ "${e}" -lt 0 ]] ; then
    e=$(( e - 1 ))
fi


问:
PHP RSA encryption openssl issue
I have been racking my brain.  I am using the latest version of php 7.  I can get rsa working with short text, however long text seems to not work.  I read to use openssl_seal/open.. when I demoed the code on a test page it works great.. when I put it into practice with mysql its not working the way its supposed to..

Encryption code:

```<code>$messageiv = openssl_random_pseudo_bytes(32);
openssl_seal($_POST[$_SESSION['message']], $encryptedmessage, $ekeys, array($_SESSION['recipient_publickey']), "AES256", $messageiv);
openssl_seal($_POST[$_SESSION['subject']], $encryptedsubject, $ekeys, array($_SESSION['recipient_publickey']), "AES256", $messageiv);
</code>```

The above is then base91_encoded and stored into blobs/varchar.

To decrypt it

```<code>openssl_open(base91_decode($row['messagesubject']), $decryptedsubject, $ekeys[0], $_SESSION['privatersakey'], "AES256", base91_decode($row['messageiv']));
    openssl_open(base91_decode($row['messagebody']), $decryptedbody, $ekeys[0], $_SESSION['privatersakey'], "AES256", base91_decode($row['messageiv']));
</code>```

The above variables $decryptedsubject and $decryptedmessage are blank.

I had this issue before using openssl_public/private key encrypt/decrypt and added the padding, this worked, however with long text it won't encrypt/decrypt....

Any assistance would be great...

答:
I can get rsa working with short text, however long text seems to not work.

This is expected. RSA only operates on short inputs. If you want to encrypt a long message with RSA, you need to do one of two things:

Break your message into several distinct chunks and encrypt them separately. This is slow, inefficient, and insecure. (Attackers can drop or reorder chunks.)

Use a secure construction combining RSA and AES, like so.

Thus, you end up with something like this:

Encryption

Generate a random 32-byte key, k.

Encrypt k with your RSA public key to get C.

Calculate the HMAC-SHA256(C, k) to get the message key m.

Encrypt your message (P) with m, using AES-256-GCM to get D.

Return C and D.

Decryption

Generate a random dummy key, which we'll call k'.

Decrypt C using your RSA private key, to obtain k (one-time AES key).

If step 2 failed, use a constant-time algorithm to swap k out for k'.

Calculate the HMAC-SHA256(C, k) to get the message key m.

Decrypt D using m.

Return the decrypted plaintext (or fail because of the authentication tag).

I read to use openssl_seal/open.. when I demoed the code on a test page it works great.. when I put it into practice with mysql its not working the way its supposed to..

First, consider using libsodium instead.

Whether or not you continue to use OpenSSL, you probably want to base64-encode your output (and make sure you're storing data in a text field rather than a short varchar).

Title: PHP RSA encryption openssl issue

Body:
I have been racking my brain.  I am using the latest version of php 7.  I can get rsa working with short text, however long text seems to not work.  I read to use openssl_seal/open.. when I demoed the code on a test page it works great.. when I put it into practice with mysql its not working the way its supposed to..

Encryption code:

$messageiv = openssl_random_pseudo_bytes(32);
openssl_seal($_POST[$_SESSION['message']], $encryptedmessage, $ekeys, array($_SESSION['recipient_publickey']), "AES256", $messageiv);
openssl_seal($_POST[$_SESSION['subject']], $encryptedsubject, $ekeys, array($_SESSION['recipient_publickey']), "AES256", $messageiv);

The above is then base91_encoded and stored into blobs/varchar.

To decrypt it

openssl_open(base91_decode($row['messagesubject']), $decryptedsubject, $ekeys[0], $_SESSION['privatersakey'], "AES256", base91_decode($row['messageiv']));
    openssl_open(base91_decode($row['messagebody']), $decryptedbody, $ekeys[0], $_SESSION['privatersakey'], "AES256", base91_decode($row['messageiv']));

The above variables $decryptedsubject and $decryptedmessage are blank.

I had this issue before using openssl_public/private key encrypt/decrypt and added the padding, this worked, however with long text it won't encrypt/decrypt....

Any assistance would be great...


问:
Repeat a command while true or x times (equivalent of while/for loop)
I would like to repeat this command as many times as there is still sometextin the field note (several rows from the table itemNotes could have one or more sometext in the field note):

```<code>UPDATE itemNotes
SET
  note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
WHERE
  INSTR(LOWER(note), 'sometext') >= 0;
</code>```

So a proto-code would be :

```<code>While (SELECT * FROM itemNotes  WHERE note like "%sometext%") >1

    UPDATE itemNotes
    SET
      note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
    WHERE
      INSTR(LOWER(note), 'sometext') >= 0;
END
</code>```

But apparently Sqlite3 doesn't support While loop or for loop. They can be emulated with something like this but I have difficulties integrating what I want with this query:

```<code>    WITH b(x,y) AS
    (
        SELECT 1,2
        UNION ALL
        SELECT x+ 1, y + 1

    FROM b
    WHERE x < 20
) SELECT * FROM b;
</code>```

Any idea how to do this?

PS: I don't use replace because I want to replace all the case combinations of sometext (e.g. sometext, SOMEtext, SOmeText...) cf this question

Current input and desired output:

For a single row, a note field could look like (and many rows in the table itemNotescould look like this one):

```<code>There is SOmetext and also somETExt and more SOMETEXT and even more sometext
</code>```

The query should output:

```<code>There is abc and also abc and more abc and even more abc
</code>```

I am doing it on the zotero.sqlite, which is created by this file (line 85). The table is created by this query

```<code>CREATE TABLE itemNotes (
    itemID INTEGER PRIMARY KEY,
    parentItemID INT,
    note TEXT,
    title TEXT,
    FOREIGN KEY (itemID) REFERENCES items(itemID) ON DELETE CASCADE,
    FOREIGN KEY (parentItemID) REFERENCES items(itemID) ON DELETE CASCADE
);
</code>```

答:
As recommended by Stephan in his last comment, I used python to do this. </p>

<p>Here is my code : </p>

```<code>import sqlite3
import re
keyword = "sometext"
replacement = "abc"

db = sqlite3.connect(path_to_sqlite)
cursor = db.cursor()

cursor.execute(f'SELECT * FROM itemNotes  WHERE note like "%{keyword}%"')

for row in cursor.fetchall():
    row_regex = re.compile(re.escape(keyword), re.IGNORECASE)
    row_regex_replaced = row_regex.sub(replacement, row[2])

    rowID = row[0]
    sql = "REPLACE INTO itemNotes (itemID,note) VALUES (?,?)"
    data = (rowID, row_regex_replaced)
    cursor.execute(sql, data)
    db.commit()
</code>```

Body:
I would like to repeat this command as many times as there is still sometextin the field note (several rows from the table itemNotes could have one or more sometext in the field note):

UPDATE itemNotes
SET
  note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
WHERE
  INSTR(LOWER(note), 'sometext') >= 0;

So a proto-code would be :

While (SELECT * FROM itemNotes  WHERE note like "%sometext%") >1

    UPDATE itemNotes
    SET
      note = SUBSTR(note, 0, INSTR(LOWER(note), 'sometext')) || 'abc' || SUBSTR(note, INSTR(LOWER(note), 'sometext')+sometext_len)
    WHERE
      INSTR(LOWER(note), 'sometext') >= 0;
END

But apparently Sqlite3 doesn't support While loop or for loop. They can be emulated with something like this but I have difficulties integrating what I want with this query:

    WITH b(x,y) AS
    (
        SELECT 1,2
        UNION ALL
        SELECT x+ 1, y + 1

    FROM b
    WHERE x < 20
) SELECT * FROM b;

Any idea how to do this?

PS: I don't use replace because I want to replace all the case combinations of sometext (e.g. sometext, SOMEtext, SOmeText...) cf this question

Current input and desired output:

For a single row, a note field could look like (and many rows in the table itemNotescould look like this one):

There is SOmetext and also somETExt and more SOMETEXT and even more sometext

The query should output:

There is abc and also abc and more abc and even more abc

I am doing it on the zotero.sqlite, which is created by this file (line 85). The table is created by this query

CREATE TABLE itemNotes (
    itemID INTEGER PRIMARY KEY,
    parentItemID INT,
    note TEXT,
    title TEXT,
    FOREIGN KEY (itemID) REFERENCES items(itemID) ON DELETE CASCADE,
    FOREIGN KEY (parentItemID) REFERENCES items(itemID) ON DELETE CASCADE
);

Body:
As recommended by Stephan in his last comment, I used python to do this.

Here is my code :

import sqlite3
import re
keyword = "sometext"
replacement = "abc"

db = sqlite3.connect(path_to_sqlite)
cursor = db.cursor()

cursor.execute(f'SELECT * FROM itemNotes  WHERE note like "%{keyword}%"')

for row in cursor.fetchall():
    row_regex = re.compile(re.escape(keyword), re.IGNORECASE)
    row_regex_replaced = row_regex.sub(replacement, row[2])

    rowID = row[0]
    sql = "REPLACE INTO itemNotes (itemID,note) VALUES (?,?)"
    data = (rowID, row_regex_replaced)
    cursor.execute(sql, data)
    db.commit()


问:
What is WAW Hazard?

Wikipedia's Hazard (computer architecture) article:

Write after write (WAW) (i2 tries to write an operand before it is
  written by i1) A write after write (WAW) data hazard may occur in a
  concurrent execution environment.

Example For example:

```<code>i1. R2 <- R4 + R7
i2. R2 <- R1 + R3
</code>```

The write back (WB) of i2 must be
  delayed until i1 finishes executing.

I haven't understood this.

What is the problem if i2 is executed before i1?

答:
Both operations affect R2. If i2 write back occurs before the write back of i1, but the write back of i1 does eventually occur, then R2 will have the result of R4 + R7 instead of the value of R1 + R3.

The WAW Hazard is about result values being overwritten by a subsequent write that should not have overwritten that value.

Title: What is WAW Hazard?

Body:
Wikipedia's Hazard (computer architecture) article:

Write after write (WAW) (i2 tries to write an operand before it is
  written by i1) A write after write (WAW) data hazard may occur in a
  concurrent execution environment.

Example For example:

i1. R2 <- R4 + R7
i2. R2 <- R1 + R3

The write back (WB) of i2 must be
  delayed until i1 finishes executing.

I haven't understood this.

What is the problem if i2 is executed before i1?


问:
Is there a way to link already existing entries in a mysql instead of creating a new one?
I am coding a system in which users can tag articles with already existing tags or by creating new ones. But I want to prevent that there are duplicate entries in my "tag-table".
Instead of creating a new one, hibernate should just link an existing one (if there is already an entry existing).

-> One article should be capable of having zero or more tags

-> One Tag can be assigned to one or more arcticles

So my question:

Is there a way to link already existing entries in a mysql instead of creating a new one (with hibernate)?

答:
You can divide your problem in 2 subtasks.
1. creating/searching tags in your db.
2. storing tags related to any article.

you can provide user access to find a tag and if not found then create it.

when user want to attach tags to any article, provide him a list of existing tags, and based on user selection you can create their entry in relation table.

This way you will have a manageable list of tags, no duplication and easily list article based on tags.


问:
Execute same logic for multiple multidimensional arrays
I'm currently trying the following:

I have multiple arrays defined. They all are filled by fetching data from the database, so they all contain the same columns/data structure, but with different data. For example, lets say the arrays are different schools, so there is:

```<code>//pseudoCode:
array1 = ({"Name: Peter", "Surname: not peter"},{"Name: doe", "Surname: john"});
array2 = ({"Name: asfwe", "Surname: qwfqwf"},{"Name: asfas", "Surname: fsbng"});
array3 = ({"Name: weqw", "Surname: wqeqewqw"},{"Name: doqweqwee", "Surname: wewe"});
</code>```

Now, for all these arrays, I want to do the same things. In my case, I have multiple if else cases, checking the length of the array and doing some stuff.

So far I'm only doing it for array 1 though. Now my first idea was to simply copy  the logic and refactor all variable names to array2 respectively to array3, but this wouldn't make sense, because in my real case, its 10 arrays instead of 3 and the logic is about 150 lines of code, so I would have a lot of duplicate code and would need to change it everywhere, if something in the logic changes.

Now the question is: How can I do the same procedure for every array?

So what I would need is something like:

```<code>//pseudoCode again
foreach(array in array1, array2, array3, array4, array5,....){
//do something with variable "array", which is actually one of the defined arrays
}
</code>```

A hint in the right direction would be great.

Thank you in advance.

答:
Procedure code demand exporting logic to function:

```<code>function foo($array) {
    // modify the array or do what ever you need
    return $array; // in case it has been modify
}
</code>```

Now can you function as:

```<code>foreach($arrays as &$arr)
    $arr = foo($arr); // calling the function on each array
    // the re-assign is just in case it has been modify
</code>```

In this example $arrays stand for array with all your inner arrays as:

```<code>$arrays = array($array1, $array2, $array3, ...)
</code>```

if your array as getting dynamicly from some other function / SQL code do:

```<code>$arrays = []; // init empty array
while (@SOME_CONDITION@) {
    $arrays[] = getAnotherArrayFunction(); // append the array to your array
}
</code>```

Body:
I'm currently trying the following:

I have multiple arrays defined. They all are filled by fetching data from the database, so they all contain the same columns/data structure, but with different data. For example, lets say the arrays are different schools, so there is:

//pseudoCode:
array1 = ({"Name: Peter", "Surname: not peter"},{"Name: doe", "Surname: john"});
array2 = ({"Name: asfwe", "Surname: qwfqwf"},{"Name: asfas", "Surname: fsbng"});
array3 = ({"Name: weqw", "Surname: wqeqewqw"},{"Name: doqweqwee", "Surname: wewe"});

Now, for all these arrays, I want to do the same things. In my case, I have multiple if else cases, checking the length of the array and doing some stuff.

So far I'm only doing it for array 1 though. Now my first idea was to simply copy  the logic and refactor all variable names to array2 respectively to array3, but this wouldn't make sense, because in my real case, its 10 arrays instead of 3 and the logic is about 150 lines of code, so I would have a lot of duplicate code and would need to change it everywhere, if something in the logic changes.

Now the question is: How can I do the same procedure for every array?

So what I would need is something like:

//pseudoCode again
foreach(array in array1, array2, array3, array4, array5,....){
//do something with variable "array", which is actually one of the defined arrays
}

A hint in the right direction would be great.

Thank you in advance.

Body:
Procedure code demand exporting logic to function:

function foo($array) {
    // modify the array or do what ever you need
    return $array; // in case it has been modify
}

Now can you function as:

foreach($arrays as &$arr)
    $arr = foo($arr); // calling the function on each array
    // the re-assign is just in case it has been modify

In this example $arrays stand for array with all your inner arrays as:

$arrays = array($array1, $array2, $array3, ...)

if your array as getting dynamicly from some other function / SQL code do:

$arrays = []; // init empty array
while (@SOME_CONDITION@) {
    $arrays[] = getAnotherArrayFunction(); // append the array to your array
}


问:
ERROR : This app was built with the iOS 12.0 SDK. Starting March 2019, all iOS apps submitted to the App Store must be built with the iOS 12.1 SDK
I get this ERROR that's preventing me from uploading to the AppStore

```<code>ERROR ITMS-90725: "SDK Version Issue.

This app was built with the iOS 12.0 SDK.

All iOS apps submitted to the App Store must be built with the iOS 12.1 SDK or later, included in Xcode 10.1 or later."
</code>```

I don't have two xcode versions in my mac

I checked xcodebuild -sdk -version and I have 12.1 and I checked command line tools path by using "sudo xcode-select -s /Applications/Xcode.app/Contents/Developer"

Output of xcodebuild -sdk -version:

```<code>iPhoneOS12.1.sdk - iOS 12.1 (iphoneos12.1)
    SDKVersion: 12.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk
    PlatformVersion: 12.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform
    BuildID: ...
    ProductBuildVersion: 16B91
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: iPhone OS
    ProductVersion: 12.1

    iPhoneSimulator12.1.sdk - Simulator - iOS 12.1 (iphonesimulator12.1)
    SDKVersion: 12.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk
    PlatformVersion: 12.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform
    BuildID: ...
    ProductBuildVersion: 16B91
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: iPhone OS
    ProductVersion: 12.1

    MacOSX10.14.sdk - macOS 10.14 (macosx10.14)
    SDKVersion: 10.14
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk
    PlatformVersion: 1.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform
    ProductBuildVersion: 18B71
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Mac OS X
    ProductUserVisibleVersion: 10.14.1
    ProductVersion: 10.14.1

    AppleTVOS12.1.sdk - tvOS 12.1 (appletvos12.1)
    SDKVersion: 12.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS12.1.sdk
    PlatformVersion: 12.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform
    BuildID: ...
    ProductBuildVersion: 16J602
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Apple TVOS
    ProductVersion: 12.1

    AppleTVSimulator12.1.sdk - Simulator - tvOS 12.1 (appletvsimulator12.1)
    SDKVersion: 12.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator12.1.sdk
    PlatformVersion: 12.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform
    BuildID: ...
    ProductBuildVersion: 16J602
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Apple TVOS
    ProductVersion: 12.1

    WatchOS5.1.sdk - watchOS 5.1 (watchos5.1)
    SDKVersion: 5.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS5.1.sdk
    PlatformVersion: 5.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform
    BuildID: ...
    ProductBuildVersion: 16R591
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Watch OS
    ProductVersion: 5.1

    WatchSimulator5.1.sdk - Simulator - watchOS 5.1 (watchsimulator5.1)
    SDKVersion: 5.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator5.1.sdk
    PlatformVersion: 5.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform
    BuildID: ...
    ProductBuildVersion: 16R591
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Watch OS
    ProductVersion: 5.1

    Xcode 10.1
    Build version 10B61
</code>```

I have base sdk set to iOS in my build settings

I use xcode 10.1  (10B61)

I uninstalled and reinstalled Xcode

Any ideas? I can't upload to the AppStore anymore, it's been a week now of searching for a solution, I can't find the solution.

答:
I had the same issue with Xcode 10.1 (For other reasons I can not update to Xcode 10.2 yet). Everything in my project was pointing at SDK 12.1 and I still got the error message when trying to upload to the App Store.

I eventually resolved the issue by removing the "iPhoneOS12.0.sdk" folder from "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs" and leaving the one for "iPhoneOS12.1.sdk". There was no need to reinstall Xcode.

Body:
I get this ERROR that's preventing me from uploading to the AppStore

ERROR ITMS-90725: "SDK Version Issue.

This app was built with the iOS 12.0 SDK.

All iOS apps submitted to the App Store must be built with the iOS 12.1 SDK or later, included in Xcode 10.1 or later."

I don't have two xcode versions in my mac

I checked xcodebuild -sdk -version and I have 12.1 and I checked command line tools path by using "sudo xcode-select -s /Applications/Xcode.app/Contents/Developer"

Output of xcodebuild -sdk -version:

iPhoneOS12.1.sdk - iOS 12.1 (iphoneos12.1)
    SDKVersion: 12.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.1.sdk
    PlatformVersion: 12.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform
    BuildID: ...
    ProductBuildVersion: 16B91
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: iPhone OS
    ProductVersion: 12.1

    iPhoneSimulator12.1.sdk - Simulator - iOS 12.1 (iphonesimulator12.1)
    SDKVersion: 12.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.1.sdk
    PlatformVersion: 12.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform
    BuildID: ...
    ProductBuildVersion: 16B91
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: iPhone OS
    ProductVersion: 12.1

    MacOSX10.14.sdk - macOS 10.14 (macosx10.14)
    SDKVersion: 10.14
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk
    PlatformVersion: 1.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform
    ProductBuildVersion: 18B71
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Mac OS X
    ProductUserVisibleVersion: 10.14.1
    ProductVersion: 10.14.1

    AppleTVOS12.1.sdk - tvOS 12.1 (appletvos12.1)
    SDKVersion: 12.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform/Developer/SDKs/AppleTVOS12.1.sdk
    PlatformVersion: 12.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVOS.platform
    BuildID: ...
    ProductBuildVersion: 16J602
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Apple TVOS
    ProductVersion: 12.1

    AppleTVSimulator12.1.sdk - Simulator - tvOS 12.1 (appletvsimulator12.1)
    SDKVersion: 12.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform/Developer/SDKs/AppleTVSimulator12.1.sdk
    PlatformVersion: 12.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/AppleTVSimulator.platform
    BuildID: ...
    ProductBuildVersion: 16J602
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Apple TVOS
    ProductVersion: 12.1

    WatchOS5.1.sdk - watchOS 5.1 (watchos5.1)
    SDKVersion: 5.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform/Developer/SDKs/WatchOS5.1.sdk
    PlatformVersion: 5.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/WatchOS.platform
    BuildID: ...
    ProductBuildVersion: 16R591
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Watch OS
    ProductVersion: 5.1

    WatchSimulator5.1.sdk - Simulator - watchOS 5.1 (watchsimulator5.1)
    SDKVersion: 5.1
    Path: /Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform/Developer/SDKs/WatchSimulator5.1.sdk
    PlatformVersion: 5.1
    PlatformPath: /Applications/Xcode.app/Contents/Developer/Platforms/WatchSimulator.platform
    BuildID: ...
    ProductBuildVersion: 16R591
    ProductCopyright: 1983-2018 Apple Inc.
    ProductName: Watch OS
    ProductVersion: 5.1

    Xcode 10.1
    Build version 10B61

I have base sdk set to iOS in my build settings

I use xcode 10.1  (10B61)

I uninstalled and reinstalled Xcode

Any ideas? I can't upload to the AppStore anymore, it's been a week now of searching for a solution, I can't find the solution.


问:
Pivot table aggregation by index
I have two dataframes containing information about student grades and test scores. The first looks like this:

```<code>     ID    Test_Score    Class1    Class2    Class3
0    001   85            B-        A         C+
1    002   78            B         NaN       B+
2    003   93            A         B         NaN
...
</code>```

The second looks like this:

```<code>     0                1
0    Algebra          A
0    Calculus_1       B
0    Calculus_2       C-
1    Algebra          C+
1    Trig             F
1    Trig             C
1    Calculus_1       C-
...
</code>```

The indices in each dataframe refer to the same student. So the student at index 0 is the same in both dataframes.

What I want to do is create a pivot table from the second dataframe, where the rows correspond to students (i.e. indices), the columns are the math classes, and the values are the highest grade they made in each class (since it's possible for a student to have taken a class more than once). I will then concatenate this to the first dataframe.

I have already written an aggregation function that finds the highest grade.

I tried the following knowing it would fail:

```<code>p = pd.pivot_table(u, columns=0, values=1, aggfunc=highest)
</code>```

Instead of returning a dataframe with a row for each student, I get a single row that contains the highest grade that any student made in the given class:

```<code>     Algebra   Trig    Precalculus   Calculus_1   Calculus_2
1    A         A+      A+            A            A
</code>```

The way I've framed the problem in my mind, I just need to aggregate across the rows which share in index, which I am unsure how to do.

I'm also open to an entirely different approach.

Desired output:

```<code>     ID    Test_Score    Class1    Class2    Class3   Algebra   Trig ...
0    001   85            B-        A         C+       A         NaN
1    002   78            B         NaN       B+       C+        C
2    003   93            A         B         NaN      B         B-
...
</code>```

EDIT:
Here is the code for my 'highest' function:

```<code>def highest(x):
    q = 0
    z = None
    for g in x:
        if qpoints(g) > q:
            q = qpoints(g)
            z = g
    return z
</code>```

where qpoints is the following function that I was already using elsewhere:

```<code>def qpoints(x):
    qvalue = {'W': 0,
              'F': 0,
              'D': 1.0,
              'D+': 1.33,
              'C-': 1.67,
              'C': 2.0,
              'C+': 2.33,
              'B-': 2.67,
              'B': 3.0,
              'B+': 3.33,
              'A-': 3.84,
              'A': 4.0,
              'A+': 4.0}
    return qvalue[x]
</code>```

答:
This is what you want.  However with pivot you aren't allowed to have duplicate column names, so having Trig twice for the same user is going to result in an error.

So after renaming the duplicate Trig value to Trig2, the join/pivot works well.

```<code>df = pd.DataFrame({'ID':['001','002','003'],'Test_Score':[85,78,93],'Class1':['B-','B','A'],'Class2':['A','','B'],'Class3':['C+','B+','',]})

df2 = pd.DataFrame({0:['Algebra','Calculus_1','Calculus_2','Algebra','Trig','Trig2','Calculus_1'],1:['A','B','C-','C+','F','C','C-']}, index=[0,0,0,1,1,1,1])

df.join(df2.pivot(columns=0, values=1))
    ID  Test_Score Class1 Class2 Class3 Algebra Calculus_1 Calculus_2 Trig Trig2
0  001          85     B-      A     C+       A          B         C-  NaN   NaN
1  002          78      B            B+      C+         C-        NaN    F     C
2  003          93      A      B            NaN        NaN        NaN  NaN   NaN
</code>```

Title: Pivot table aggregation by index

Body:
I have two dataframes containing information about student grades and test scores. The first looks like this:

     ID    Test_Score    Class1    Class2    Class3
0    001   85            B-        A         C+
1    002   78            B         NaN       B+
2    003   93            A         B         NaN
...

The second looks like this:

     0                1
0    Algebra          A
0    Calculus_1       B
0    Calculus_2       C-
1    Algebra          C+
1    Trig             F
1    Trig             C
1    Calculus_1       C-
...

The indices in each dataframe refer to the same student. So the student at index 0 is the same in both dataframes.

What I want to do is create a pivot table from the second dataframe, where the rows correspond to students (i.e. indices), the columns are the math classes, and the values are the highest grade they made in each class (since it's possible for a student to have taken a class more than once). I will then concatenate this to the first dataframe.

I have already written an aggregation function that finds the highest grade.

I tried the following knowing it would fail:

p = pd.pivot_table(u, columns=0, values=1, aggfunc=highest)

Instead of returning a dataframe with a row for each student, I get a single row that contains the highest grade that any student made in the given class:

     Algebra   Trig    Precalculus   Calculus_1   Calculus_2
1    A         A+      A+            A            A

The way I've framed the problem in my mind, I just need to aggregate across the rows which share in index, which I am unsure how to do.

I'm also open to an entirely different approach.

Desired output:

     ID    Test_Score    Class1    Class2    Class3   Algebra   Trig ...
0    001   85            B-        A         C+       A         NaN
1    002   78            B         NaN       B+       C+        C
2    003   93            A         B         NaN      B         B-
...

EDIT:
Here is the code for my 'highest' function:

def highest(x):
    q = 0
    z = None
    for g in x:
        if qpoints(g) > q:
            q = qpoints(g)
            z = g
    return z

where qpoints is the following function that I was already using elsewhere:

def qpoints(x):
    qvalue = {'W': 0,
              'F': 0,
              'D': 1.0,
              'D+': 1.33,
              'C-': 1.67,
              'C': 2.0,
              'C+': 2.33,
              'B-': 2.67,
              'B': 3.0,
              'B+': 3.33,
              'A-': 3.84,
              'A': 4.0,
              'A+': 4.0}
    return qvalue[x]

Body:
This is what you want.  However with pivot you aren't allowed to have duplicate column names, so having Trig twice for the same user is going to result in an error.

So after renaming the duplicate Trig value to Trig2, the join/pivot works well.

df = pd.DataFrame({'ID':['001','002','003'],'Test_Score':[85,78,93],'Class1':['B-','B','A'],'Class2':['A','','B'],'Class3':['C+','B+','',]})

df2 = pd.DataFrame({0:['Algebra','Calculus_1','Calculus_2','Algebra','Trig','Trig2','Calculus_1'],1:['A','B','C-','C+','F','C','C-']}, index=[0,0,0,1,1,1,1])

df.join(df2.pivot(columns=0, values=1))
    ID  Test_Score Class1 Class2 Class3 Algebra Calculus_1 Calculus_2 Trig Trig2
0  001          85     B-      A     C+       A          B         C-  NaN   NaN
1  002          78      B            B+      C+         C-        NaN    F     C
2  003          93      A      B            NaN        NaN        NaN  NaN   NaN


问:
get the latest fragment in backstack
How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?</p>

```<code>FragmentManager fragManager = activity.getSupportFragmentManager();
FragmentTransaction fragTransacion = fragMgr.beginTransaction();

/****After add , replace fragments
  (some of the fragments are add to backstack , some are not)***/

//HERE, How can I get the latest added fragment from backstack ??
</code>```

答:
Kotlin</p>
```<code>// In activities
activity.supportFragmentManager.fragments.lastOrNull()

// In fragments
fragment.childFragmentManager.fragments.lastOrNull()
</code>```

Title: get the latest fragment in backstack

Body:
How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?

FragmentManager fragManager = activity.getSupportFragmentManager();
FragmentTransaction fragTransacion = fragMgr.beginTransaction();

/****After add , replace fragments
  (some of the fragments are add to backstack , some are not)***/

//HERE, How can I get the latest added fragment from backstack ??

Body:
Kotlin

// In activities
activity.supportFragmentManager.fragments.lastOrNull()

// In fragments
fragment.childFragmentManager.fragments.lastOrNull()


问:
How can I count docs in find in Mongodb?
I am trying to count docs in mongodb request.

I can count count = docs.length in toArray()-s callback but allways gives 10. A can do 2 same requests just replace find to count but it seems wrong

```<code>let count;
  db.get().collection('images').find({
     $and: [
     {tags: { $in: tags }},
     {date: {$gte: date.toISOString()}},
     {title:{$regex: query, $options: "$i"}},
  ]},
  (err, docs)=>{docs.toArray((err, res)=>{
    count= res.length
  })}
)
  .skip(0).limit(10).toArray((err, docs)=>{
    res = {data:docs, dataLength:count }
    cb(err, res);
// })
});
</code>```

I am getting this err: TypeError: Cannot read property 'skip' of undefined

答:
You're probably always receiving 10 back because you are specifically saying "give me 10 back" when you do .limit(10). Now, the reason you are getting that error is because .skip has to be added to the end of the .find(). This is what your query should look like:

```<code>db.collection('images').find({
  $and: [
    {tags: { $in: tags }},
    {date: {$gte: date.toISOString()}},
    {title:{$regex: query, $options: "$i"}},
  ]
}).skip(0).limit(10).toArray((err, docs) => {
  if (err) { console.log(err) }
  else {
    let res = {data:docs, dataLength:docs.length}
    // do any other logic here
  }
})
</code>```

Body:
I am trying to count docs in mongodb request.

I can count count = docs.length in toArray()-s callback but allways gives 10. A can do 2 same requests just replace find to count but it seems wrong

let count;
  db.get().collection('images').find({
     $and: [
     {tags: { $in: tags }},
     {date: {$gte: date.toISOString()}},
     {title:{$regex: query, $options: "$i"}},
  ]},
  (err, docs)=>{docs.toArray((err, res)=>{
    count= res.length
  })}
)
  .skip(0).limit(10).toArray((err, docs)=>{
    res = {data:docs, dataLength:count }
    cb(err, res);
// })
});

I am getting this err: TypeError: Cannot read property 'skip' of undefined

Body:
You're probably always receiving 10 back because you are specifically saying "give me 10 back" when you do .limit(10). Now, the reason you are getting that error is because .skip has to be added to the end of the .find(). This is what your query should look like:

db.collection('images').find({
  $and: [
    {tags: { $in: tags }},
    {date: {$gte: date.toISOString()}},
    {title:{$regex: query, $options: "$i"}},
  ]
}).skip(0).limit(10).toArray((err, docs) => {
  if (err) { console.log(err) }
  else {
    let res = {data:docs, dataLength:docs.length}
    // do any other logic here
  }
})


问:
how to split a pandas row into several rows and process some of their values?
I am trying to write a function that splits a pandas row into several rows AND updates some values at a particular column.

The problem would look like this;

```<code>   Id  Values
 0  A    2000
 1  B     600
</code>```

and the expected results after splitting only those Ids with a Value larger than 800 into smaller quantities. That would be;

```<code>  Id  Values
0  A     800
1  A     800
2  A     400
3  B     600
</code>```

The logic to split the values is not so relevant. For example;

```<code>2000 = 800 + 800 + 400
2000 = 700 + 700 + 600
</code>```

any ideas on how to tack this problem?

答:
Define a function to be applied to each row:

```<code>def fn2(val, maxVal):
    tbl = []
    v1 = val // maxVal
    v2 = val % maxVal
    if v1:
        tbl.extend([maxVal] * v1)
    if v2:
        tbl.append(v2)
    return pd.Series(tbl)
</code>```

In the above function maxVal is the maximal value to be set in
an output row.

And the actual processing can be done in a single (although chained)
instruction:

```<code>df.set_index('Id').Values.apply(fn2, maxVal=800).stack()\
    .rename('Values').astype(int)\
    .reset_index(level=1, drop=True).reset_index()
</code>```

Note that before stack some values are NaN, so the type was changed
to float. To change it back to int, I added astype(int).

For your sample data the result is:

```<code>  Id Values
0  A    800
1  A    800
2  A    400
3  B    600
</code>```

Edit following your comment

If you have only one another column, you can "divide" Values
into chunks almost as you proposed:

```<code>df.set_index(['Id', 'AnotherCol']).Values.apply(fn2, maxVal=800)\
    .stack().rename('Values').astype(int)\
    .reset_index(level=2, drop=True).reset_index()
</code>```

The difference from your proposal is that the index level to drop is 2
(not 0).

But if you have more such "additional" columns, a more natural way seems to:

Calculate the Series of "divided Values" (I called it vals),
with the index taken from source Id column.

Drop "original" Values column from df.

Merge it with vals. The merge keys are:

for df - Id,

for vals - the index.

So the code is:

```<code>vals = df.set_index(['Id']).Values.apply(fn2, maxVal=800)\
    .stack().rename('Values').astype(int)\
    .reset_index(level=1, drop=True)
pd.merge(df.drop(columns=['Values']), vals,
    left_on='Id', right_index=True)
</code>```

If you are unhappy about repeating index values, add .reset_index(drop=True)
to the last instruction.

Body:
I am trying to write a function that splits a pandas row into several rows AND updates some values at a particular column.

The problem would look like this;

   Id  Values
 0  A    2000
 1  B     600

and the expected results after splitting only those Ids with a Value larger than 800 into smaller quantities. That would be;

  Id  Values
0  A     800
1  A     800
2  A     400
3  B     600

The logic to split the values is not so relevant. For example;

2000 = 800 + 800 + 400
2000 = 700 + 700 + 600

any ideas on how to tack this problem?

Body:
Define a function to be applied to each row:

def fn2(val, maxVal):
    tbl = []
    v1 = val // maxVal
    v2 = val % maxVal
    if v1:
        tbl.extend([maxVal] * v1)
    if v2:
        tbl.append(v2)
    return pd.Series(tbl)

In the above function maxVal is the maximal value to be set in
an output row.

And the actual processing can be done in a single (although chained)
instruction:

df.set_index('Id').Values.apply(fn2, maxVal=800).stack()\
    .rename('Values').astype(int)\
    .reset_index(level=1, drop=True).reset_index()

Note that before stack some values are NaN, so the type was changed
to float. To change it back to int, I added astype(int).

For your sample data the result is:

  Id Values
0  A    800
1  A    800
2  A    400
3  B    600

Edit following your comment

If you have only one another column, you can "divide" Values
into chunks almost as you proposed:

df.set_index(['Id', 'AnotherCol']).Values.apply(fn2, maxVal=800)\
    .stack().rename('Values').astype(int)\
    .reset_index(level=2, drop=True).reset_index()

The difference from your proposal is that the index level to drop is 2
(not 0).

But if you have more such "additional" columns, a more natural way seems to:

Calculate the Series of "divided Values" (I called it vals),
with the index taken from source Id column.

Drop "original" Values column from df.

Merge it with vals. The merge keys are:

for df - Id,

for vals - the index.

So the code is:

vals = df.set_index(['Id']).Values.apply(fn2, maxVal=800)\
    .stack().rename('Values').astype(int)\
    .reset_index(level=1, drop=True)
pd.merge(df.drop(columns=['Values']), vals,
    left_on='Id', right_index=True)

If you are unhappy about repeating index values, add .reset_index(drop=True)
to the last instruction.


问:
how to load form with many controls Smooth on Winform?
I have a C# program with a DataGridView on the form.

When the user selects a row and presses a button, I present control panel with some textboxes that fill from the DataGridView.

When the control panel is shown,  I see the controls building on the screen and it's not pleasing to the eye.

How do I show this control panel instantly?

Thanks in advance

答:
Control.SuspendLayout can be used to stop the control painting while you modify it and ResumeLayout when you are done

If the drawing is too slow you can finesse the control double buffering. Thanks to Sergio for the link.