问:
parse meta header for URL address in Objective c
I'm trying to get meta data for a URL address and I'm using this code

```<code>NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.youtube.com/watch?v=1cuMAeGOCng"]];
    [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Safari/601.1.42"
   forHTTPHeaderField:@"User-Agent"];

    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",data);
    }];
    [task resume];
</code>```

is this right ?
Also the returned data is encoded and can't figure how to decode it! any clues ?

Thanks

答:
```<code>NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:@"https://www.youtube.com/watch?v=1cuMAeGOCng"]];
[request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Safari/601.1.42"
forHTTPHeaderField:@"User-Agent"];

session = [NSURLSession sessionWithConfiguration:
[NSURLSessionConfiguration defaultSessionConfiguration]];

 NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                          {

   NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
         NSLog(@"Data = %@",text);

                          }];
  [task resume];
</code>```

Body:
I'm trying to get meta data for a URL address and I'm using this code

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.youtube.com/watch?v=1cuMAeGOCng"]];
    [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Safari/601.1.42"
   forHTTPHeaderField:@"User-Agent"];

    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionTask *task = [self.session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",data);
    }];
    [task resume];

is this right ?
Also the returned data is encoded and can't figure how to decode it! any clues ?

Thanks


来源: stackexchange

问:
Refresh Kendo dropdownlist after event change of another dropdownlist
When I change the value from the first ddl I get the data from Ajax of the other ddl but it doesnt refresh.

This is my grid

```<code>$("#grid").kendoGrid({
        dataSource:
height: 500,
                toolbar: ["create"],
                columns: [
                     { command: ["edit"], title: " ", width: "150px", locked: true },
                    { field: "RowLabels", title: "Row Labels", width: "180px", locked: true },
                    { field: "IdValueStream", title: "VS", width: "90px", locked: true, editor: vsDropDownEditor, template: "#=getVsName(IdValueStream)#" }, //, template: "#=IdValueStream.ValueStream#"
                    { field: "IdLine", title: "Line", width: "180px", locked: true, editor: linesDropDownEditor }, //, template: "#=getLineName(IdLine)#"
                       { field: "W1", title: Weeks[0].W1.substring(0, 10), width: "98px" }, //
                       { field: "W2", title: Weeks[0].W2.substring(0, 10), width: "90px" },
                       { field: "W3", title: Weeks[0].W3.substring(0, 10), width: "90px" },
                       { field: "W4", title: Weeks[0].W4.substring(0, 10), width: "90px" },
                       { field: "W5", title: Weeks[0].W5.substring(0, 10), width: "90px" },
                       { field: "W6", title: Weeks[0].W6.substring(0, 10), width: "90px" },
                       { field: "W7", title: Weeks[0].W7.substring(0, 10), width: "90px" },
                       { field: "W8", title: Weeks[0].W8.substring(0, 10), width: "90px" },
                       { field: "W9", title: Weeks[0].W9.substring(0, 10), width: "90px" },
                       { field: "W10", title: Weeks[0].W10.substring(0, 10), width: "90px" },
                       { field: "W11", title: Weeks[0].W11.substring(0, 10), width: "90px" },
                       { field: "W12", title: Weeks[0].W12.substring(0, 10), width: "90px" },
                       { field: "W13", title: Weeks[0].W13.substring(0, 10), width: "90px" }
                ],
                editable: "inline"
            });
</code>```

This is the method from the editor of the first ddl

```<code>function vsDropDownEditor(container, options) {
    $('<input id="ddlVs" data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDropDownList({
                    dataTextField: "ValueStream",
                    dataValueField: "Id",
                    dataSource: categories,
                    select: onSelect
                });
}
</code>```

And this the other method from editor of the second ddl

```<code>function linesDropDownEditor(container, options) {

    $('<input data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDropDownList({
                    autoBind: false,
                    dataTextField: "Line",
                    dataValueField: "Id",
                    dataSource: lines
                });
}
</code>```

So when I select an item of the first ddl I want to refresh the second ddl

答:
You can also check out the following example - Cascading DropDownLists used as editors in Grid:

Add Cascading DropDownList Editors

ContentLicense: CC BY-SA 3.0

Body:
When I change the value from the first ddl I get the data from Ajax of the other ddl but it doesnt refresh.

This is my grid

$("#grid").kendoGrid({
        dataSource:
height: 500,
                toolbar: ["create"],
                columns: [
                     { command: ["edit"], title: " ", width: "150px", locked: true },
                    { field: "RowLabels", title: "Row Labels", width: "180px", locked: true },
                    { field: "IdValueStream", title: "VS", width: "90px", locked: true, editor: vsDropDownEditor, template: "#=getVsName(IdValueStream)#" }, //, template: "#=IdValueStream.ValueStream#"
                    { field: "IdLine", title: "Line", width: "180px", locked: true, editor: linesDropDownEditor }, //, template: "#=getLineName(IdLine)#"
                       { field: "W1", title: Weeks[0].W1.substring(0, 10), width: "98px" }, //
                       { field: "W2", title: Weeks[0].W2.substring(0, 10), width: "90px" },
                       { field: "W3", title: Weeks[0].W3.substring(0, 10), width: "90px" },
                       { field: "W4", title: Weeks[0].W4.substring(0, 10), width: "90px" },
                       { field: "W5", title: Weeks[0].W5.substring(0, 10), width: "90px" },
                       { field: "W6", title: Weeks[0].W6.substring(0, 10), width: "90px" },
                       { field: "W7", title: Weeks[0].W7.substring(0, 10), width: "90px" },
                       { field: "W8", title: Weeks[0].W8.substring(0, 10), width: "90px" },
                       { field: "W9", title: Weeks[0].W9.substring(0, 10), width: "90px" },
                       { field: "W10", title: Weeks[0].W10.substring(0, 10), width: "90px" },
                       { field: "W11", title: Weeks[0].W11.substring(0, 10), width: "90px" },
                       { field: "W12", title: Weeks[0].W12.substring(0, 10), width: "90px" },
                       { field: "W13", title: Weeks[0].W13.substring(0, 10), width: "90px" }
                ],
                editable: "inline"
            });

This is the method from the editor of the first ddl

function vsDropDownEditor(container, options) {
    $('<input id="ddlVs" data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDropDownList({
                    dataTextField: "ValueStream",
                    dataValueField: "Id",
                    dataSource: categories,
                    select: onSelect
                });
}

And this the other method from editor of the second ddl

function linesDropDownEditor(container, options) {

    $('<input data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDropDownList({
                    autoBind: false,
                    dataTextField: "Line",
                    dataValueField: "Id",
                    dataSource: lines
                });
}

So when I select an item of the first ddl I want to refresh the second ddl


问:
k-means with a centroid constraint
I'm working on a data science project for my intro to Data Science class, and we've decided to tackle a problem relating to desalination plants in california: "Where should we place k plants to minimize the distance to zip codes?"

The data that we have so far is, zip, city, county, pop, lat, long, amount of water.

The issue is, I can't find any resources on how to force the centroid to be constrained to staying on the coast. What we've thought of so far is:
Use a normal kmeans algorithm, but move the centroid to the coast once clusters have settled (bad)
Use a normal kmeans algorithm with weights, making the coastal zips have infinite weight (I've been told this isn't a great solution)

What do you guys think?

答:
I would approach this by setting possible points that could be centers, i.e. your coastline.

I think this is close to Nathaniel Saul's first comment.

This way, for each iteration, instead of choosing a mean, a point out of the possible set would be chosen by proximity to the cluster.

I’ve simplified the conditions to only 2 data columns (lon. and lat.) but you should be able to extrapolate the concept. For simplicity, to demonstrate, I based this on code from here.

In this example, the purple dots are places on the coastline. If I understood correctly, the optimal Coastline locations should look something like this:

See code below:

```<code>#! /usr/bin/python3.6

# Code based on:
# https://datasciencelab.wordpress.com/2013/12/12/clustering-with-k-means-in-python/

import matplotlib.pyplot as plt
import numpy as np
import random

##### Simulation START #####
# Generate possible points.
def possible_points(n=20):
    y=list(np.linspace( -1, 1, n ))
    x=[-1.2]
    X=[]
    for i in list(range(1,n)):
        x.append(x[i-1]+random.uniform(-2/n,2/n) )
    for a,b in zip(x,y):
        X.append(np.array([a,b]))
    X = np.array(X)
    return X

# Generate sample
def init_board_gauss(N, k):
    n = float(N)/k
    X = []
    for i in range(k):
        c = (random.uniform(-1, 1), random.uniform(-1, 1))
        s = random.uniform(0.05,0.5)
        x = []
        while len(x) < n:
            a, b = np.array([np.random.normal(c[0], s), np.random.normal(c[1], s)])
            # Continue drawing points from the distribution in the range [-1,1]
            if abs(a) < 1 and abs(b) < 1:
                x.append([a,b])
        X.extend(x)
    X = np.array(X)[:N]
    return X
##### Simulation END #####

# Identify points for each center.
def cluster_points(X, mu):
    clusters  = {}
    for x in X:
        bestmukey = min([(i[0], np.linalg.norm(x-mu[i[0]])) \
                    for i in enumerate(mu)], key=lambda t:t[1])[0]
        try:
            clusters[bestmukey].append(x)
        except KeyError:
            clusters[bestmukey] = [x]
    return clusters

# Get closest possible point for each cluster.
def closest_point(cluster,possiblePoints):
    closestPoints=[]
    # Check average distance for each point.
    for possible in possiblePoints:
        distances=[]
        for point in cluster:
            distances.append(np.linalg.norm(possible-point))
            closestPoints.append(np.sum(distances)) # minimize total distance
            # closestPoints.append(np.mean(distances))
    return possiblePoints[closestPoints.index(min(closestPoints))]

# Calculate new centers.
# Here the 'coast constraint' goes.
def reevaluate_centers(clusters,possiblePoints):
    newmu = []
    keys = sorted(clusters.keys())
    for k in keys:
        newmu.append(closest_point(clusters[k],possiblePoints))
    return newmu

# Check whether centers converged.
def has_converged(mu, oldmu):
    return (set([tuple(a) for a in mu]) == set([tuple(a) for a in oldmu]))

# Meta function that runs the steps of the process in sequence.
def find_centers(X, K, possiblePoints):
    # Initialize to K random centers
    oldmu = random.sample(list(possiblePoints), K)
    mu = random.sample(list(possiblePoints), K)
    while not has_converged(mu, oldmu):
        oldmu = mu
        # Assign all points in X to clusters
        clusters = cluster_points(X, mu)
        # Re-evaluate centers
        mu = reevaluate_centers(clusters,possiblePoints)
    return(mu, clusters)

K=3
X = init_board_gauss(30,K)
possiblePoints=possible_points()
results=find_centers(X,K,possiblePoints)

# Show results

# Show constraints and clusters
# List point types
pointtypes1=["gx","gD","g*"]

plt.plot(
    np.matrix(possiblePoints).transpose()[0],np.matrix(possiblePoints).transpose()[1],'m.'
    )

for i in list(range(0,len(results[0]))) :
    plt.plot(
        np.matrix(results[0][i]).transpose()[0], np.matrix(results[0][i]).transpose()[1],pointtypes1[i]
        )

pointtypes=["bx","yD","c*"]
# Show all cluster points
for i in list(range(0,len(results[1]))) :
    plt.plot(
        np.matrix(results[1][i]).transpose()[0],np.matrix(results[1][i]).transpose()[1],pointtypes[i]
        )
plt.show()
</code>```

Edited to minimize total distance.

Title: k-means with a centroid constraint

Body:
I would approach this by setting possible points that could be centers, i.e. your coastline.

I think this is close to Nathaniel Saul's first comment.

This way, for each iteration, instead of choosing a mean, a point out of the possible set would be chosen by proximity to the cluster.

I’ve simplified the conditions to only 2 data columns (lon. and lat.) but you should be able to extrapolate the concept. For simplicity, to demonstrate, I based this on code from here.

In this example, the purple dots are places on the coastline. If I understood correctly, the optimal Coastline locations should look something like this:

See code below:

#! /usr/bin/python3.6

# Code based on:
# https://datasciencelab.wordpress.com/2013/12/12/clustering-with-k-means-in-python/

import matplotlib.pyplot as plt
import numpy as np
import random

##### Simulation START #####
# Generate possible points.
def possible_points(n=20):
    y=list(np.linspace( -1, 1, n ))
    x=[-1.2]
    X=[]
    for i in list(range(1,n)):
        x.append(x[i-1]+random.uniform(-2/n,2/n) )
    for a,b in zip(x,y):
        X.append(np.array([a,b]))
    X = np.array(X)
    return X

# Generate sample
def init_board_gauss(N, k):
    n = float(N)/k
    X = []
    for i in range(k):
        c = (random.uniform(-1, 1), random.uniform(-1, 1))
        s = random.uniform(0.05,0.5)
        x = []
        while len(x) < n:
            a, b = np.array([np.random.normal(c[0], s), np.random.normal(c[1], s)])
            # Continue drawing points from the distribution in the range [-1,1]
            if abs(a) < 1 and abs(b) < 1:
                x.append([a,b])
        X.extend(x)
    X = np.array(X)[:N]
    return X
##### Simulation END #####

# Identify points for each center.
def cluster_points(X, mu):
    clusters  = {}
    for x in X:
        bestmukey = min([(i[0], np.linalg.norm(x-mu[i[0]])) \
                    for i in enumerate(mu)], key=lambda t:t[1])[0]
        try:
            clusters[bestmukey].append(x)
        except KeyError:
            clusters[bestmukey] = [x]
    return clusters

# Get closest possible point for each cluster.
def closest_point(cluster,possiblePoints):
    closestPoints=[]
    # Check average distance for each point.
    for possible in possiblePoints:
        distances=[]
        for point in cluster:
            distances.append(np.linalg.norm(possible-point))
            closestPoints.append(np.sum(distances)) # minimize total distance
            # closestPoints.append(np.mean(distances))
    return possiblePoints[closestPoints.index(min(closestPoints))]

# Calculate new centers.
# Here the 'coast constraint' goes.
def reevaluate_centers(clusters,possiblePoints):
    newmu = []
    keys = sorted(clusters.keys())
    for k in keys:
        newmu.append(closest_point(clusters[k],possiblePoints))
    return newmu

# Check whether centers converged.
def has_converged(mu, oldmu):
    return (set([tuple(a) for a in mu]) == set([tuple(a) for a in oldmu]))

# Meta function that runs the steps of the process in sequence.
def find_centers(X, K, possiblePoints):
    # Initialize to K random centers
    oldmu = random.sample(list(possiblePoints), K)
    mu = random.sample(list(possiblePoints), K)
    while not has_converged(mu, oldmu):
        oldmu = mu
        # Assign all points in X to clusters
        clusters = cluster_points(X, mu)
        # Re-evaluate centers
        mu = reevaluate_centers(clusters,possiblePoints)
    return(mu, clusters)

K=3
X = init_board_gauss(30,K)
possiblePoints=possible_points()
results=find_centers(X,K,possiblePoints)

# Show results

# Show constraints and clusters
# List point types
pointtypes1=["gx","gD","g*"]

plt.plot(
    np.matrix(possiblePoints).transpose()[0],np.matrix(possiblePoints).transpose()[1],'m.'
    )

for i in list(range(0,len(results[0]))) :
    plt.plot(
        np.matrix(results[0][i]).transpose()[0], np.matrix(results[0][i]).transpose()[1],pointtypes1[i]
        )

pointtypes=["bx","yD","c*"]
# Show all cluster points
for i in list(range(0,len(results[1]))) :
    plt.plot(
        np.matrix(results[1][i]).transpose()[0],np.matrix(results[1][i]).transpose()[1],pointtypes[i]
        )
plt.show()

Edited to minimize total distance.


问:
Error loading colour scheme in Sublime Text 3
This error appears every time I save file or open a file.

Error loading colour scheme Packages\User\MonokaiGrayDL.tmTheme: Unable to open Packages\User\MonikaiGray.tmTheme

I searched about it but those solutions are for sublime text 2...please help

答:
Copy the source code of the .tmTheme file from Github.

Open your non-working .tmTheme file with Sublime text.

Paste contents, save and restart Sublime text.


问:
Java - How to share objects within different static methods in same class
How would one go about sharing an object between static methods? Is this even possible? Is there a better way?

In my code, I have one frame in one class. I have different static methods to do stuff with this frame in the same class. I call these methods in another class.

Is there a better way of doing this for swing? Essentially I want to create a Frame, in which I can edit the size, and colour, and contents through the methods of other classes (these classes would have Panels which I would use on this frame).

Class calling the static methods:

```<code>import javax.swing.*;

public class Main{

    // Display Login Window
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try
            {
                new loginFrames();
                loginFrames.showFrame("hello", 1200, 800);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        });
    }
}
</code>```

Class with the static methods:

```<code>import javax.swing.*;
import java.awt.*;

public class loginFrames{

    public JFrame appFrame;

    public void createFrame(String frameName, int frameW, int frameH) {

        // Create JFrame with frame name, width, and height
        appFrame = new JFrame(frameName);
        appFrame.setSize(frameW, frameH);

        // Get the content pane and set the background colour black
        Container absFrameContentPane = appFrame.getContentPane();
        absFrameContentPane.setBackground(Color.BLACK);

        // Show the frame
        appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        appFrame.setVisible(true);
    }

    // Callable from Main class
    public static void showFrame(String frameName, int frameW, int frameH) {
        loginFrames applicationFrame = new loginFrames();
        applicationFrame.createFrame(frameName, frameW, frameH);
    }

    // Callable from Main class
    public static void appAddPanel(String frameName, int frameW, int frameH) {
    // How do I call the same object above, here?
    }
}
</code>```

答:
Your code violates various OO principles, first of all information hiding/encapsulation

Your variable  appFrame should be declared private and  accessed only from withing the loginFrames class.

Also: since the variable  appFrame is not declared static so it cannot be accessed from the static methods in that class (directly).

The solution is to remove the static key word from the methods and access them via an object of the class (does that sound weired to use objects in an object oriented language?)

Body:
How would one go about sharing an object between static methods? Is this even possible? Is there a better way?

In my code, I have one frame in one class. I have different static methods to do stuff with this frame in the same class. I call these methods in another class.

Is there a better way of doing this for swing? Essentially I want to create a Frame, in which I can edit the size, and colour, and contents through the methods of other classes (these classes would have Panels which I would use on this frame).

Class calling the static methods:

import javax.swing.*;

public class Main{

    // Display Login Window
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try
            {
                new loginFrames();
                loginFrames.showFrame("hello", 1200, 800);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        });
    }
}

Class with the static methods:

import javax.swing.*;
import java.awt.*;

public class loginFrames{

    public JFrame appFrame;

    public void createFrame(String frameName, int frameW, int frameH) {

        // Create JFrame with frame name, width, and height
        appFrame = new JFrame(frameName);
        appFrame.setSize(frameW, frameH);

        // Get the content pane and set the background colour black
        Container absFrameContentPane = appFrame.getContentPane();
        absFrameContentPane.setBackground(Color.BLACK);

        // Show the frame
        appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        appFrame.setVisible(true);
    }

    // Callable from Main class
    public static void showFrame(String frameName, int frameW, int frameH) {
        loginFrames applicationFrame = new loginFrames();
        applicationFrame.createFrame(frameName, frameW, frameH);
    }

    // Callable from Main class
    public static void appAddPanel(String frameName, int frameW, int frameH) {
    // How do I call the same object above, here?
    }
}


问:
Spring Security login with customized form
My Spring security configurations:

```<code>@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{

        @Autowired
        private ClientDetailsService clientDetailsService;

        @Autowired
        public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
              .withUser("username").password("password")
              .authorities("USER");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and().csrf().disable();
        }

       ....
}
</code>```

My Spring boot controllers:

```<code>@Controller
@RequestMapping("/")
public class IndexController extends BaseController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }
....
}
</code>```

Hi, I am attempting to using Spring security with customized login form.
My problem is:

When I enter the localhost:8080/login The browser doesn't direct to my login.jsp, it just pops out a default form with text boxes to enter username and password.

After I enter "username" as username, "password" as password, it returns an authentication failed.

The traceback:

```<code>Request '/login' matched by universal pattern '/**'
DEBUG - matched
DEBUG - /login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG - /login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG - /login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG - /login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG - Trying to match using Ant [pattern='/logout', GET]
DEBUG - Checking match of request : '/login'; against '/logout'
DEBUG - Trying to match using Ant [pattern='/logout', POST]
DEBUG - Request 'GET /login' doesn't match 'POST /logout
DEBUG - Trying to match using Ant [pattern='/logout', PUT]
DEBUG - Request 'GET /login' doesn't match 'PUT /logout
DEBUG - Trying to match using Ant [pattern='/logout', DELETE]
DEBUG - Request 'GET /login' doesn't match 'DELETE /logout
DEBUG - No matches found
DEBUG - /login at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG - Basic Authentication Authorization header found for user 'username'
DEBUG - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG - User 'username' not found
DEBUG - Returning cached instance of singleton bean 'delegatingApplicationListener'
DEBUG - Authentication request for failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials
</code>```

答:
Looks like the anonymous user has not access to /login

```<code>http
    .authorizeRequests()
        .antMatchers("/login").anonymous()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .loginPage("/login")
        .permitAll()
        .and().csrf().disable();
</code>```

Overmore, looks like you are doing request against your server with the Authorization header for the Basic Authentication.

DEBUG - Basic Authentication Authorization header found for user 'username'

Body:
My Spring security configurations:

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{

        @Autowired
        private ClientDetailsService clientDetailsService;

        @Autowired
        public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
              .withUser("username").password("password")
              .authorities("USER");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and().csrf().disable();
        }

       ....
}

My Spring boot controllers:

@Controller
@RequestMapping("/")
public class IndexController extends BaseController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }
....
}

Hi, I am attempting to using Spring security with customized login form.
My problem is:

When I enter the localhost:8080/login The browser doesn't direct to my login.jsp, it just pops out a default form with text boxes to enter username and password.

After I enter "username" as username, "password" as password, it returns an authentication failed.

The traceback:

Request '/login' matched by universal pattern '/**'
DEBUG - matched
DEBUG - /login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG - /login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG - /login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
DEBUG - /login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG - Trying to match using Ant [pattern='/logout', GET]
DEBUG - Checking match of request : '/login'; against '/logout'
DEBUG - Trying to match using Ant [pattern='/logout', POST]
DEBUG - Request 'GET /login' doesn't match 'POST /logout
DEBUG - Trying to match using Ant [pattern='/logout', PUT]
DEBUG - Request 'GET /login' doesn't match 'PUT /logout
DEBUG - Trying to match using Ant [pattern='/logout', DELETE]
DEBUG - Request 'GET /login' doesn't match 'DELETE /logout
DEBUG - No matches found
DEBUG - /login at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG - Basic Authentication Authorization header found for user 'username'
DEBUG - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG - User 'username' not found
DEBUG - Returning cached instance of singleton bean 'delegatingApplicationListener'
DEBUG - Authentication request for failed: org.springframework.security.authentication.BadCredentialsException: Bad credentials

Body:
Looks like the anonymous user has not access to /login

http
    .authorizeRequests()
        .antMatchers("/login").anonymous()
        .anyRequest().authenticated()
        .and()
    .formLogin()
        .loginPage("/login")
        .permitAll()
        .and().csrf().disable();

Overmore, looks like you are doing request against your server with the Authorization header for the Basic Authentication.

DEBUG - Basic Authentication Authorization header found for user 'username'


问:
Airflow setup for high availability
How to deploy apache airflow (formally known as airbnb's airflow) scheduler in high availability?

I am not asking about the backend DB or RabbitMQ that should obviously be deployed in high availability configuration.

My main focus is the scheduler - is there something special needs to be done?

答:
My personal experience was to follow the instructions I found for some best practices; that is to restart the scheduler every 10 runs ( -N 10 ) and use this software when possible:

https://github.com/teamclairvoyant/airflow-scheduler-failover-controller

I also use a DAG which pings a monitoring system to be sure that the scheduler has not gone away.

Title: Airflow setup for high availability

ContentLicense: CC BY-SA 4.0


问:
Send specific data per node and gather results in MPI-Python
I have trouble executing this program in mpi4py. My objective is to send specific data to a particular node (that is why I am not using scatter). After that, process the data in each node, and finally gather all the results.

Apparently, my program does not understand how to gather the data from different nodes (maybe because gather is designed to work with scatter). I tried to send the date with comm.send() and gather with comm.gather(). When I execute the program, it runs forever, and I don't see any result.

Can you help me to find out how to gather the data from the different nodes? Is there other function to do this? May I need a loop over the nodes?

```<code>from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

if rank == 0:
    data = list(np.arange(size) + 1)
    for i in range(size):
        comm.send(data[i], dest=i)
else:
    data = comm.recv(source=0)
    data += 1

print("rank", rank, "has data", data)

newData = comm.gather(data, root = 0)

if rank == 0:

    print("master collected", newData)
</code>```

答: You need to use Scatter.  It does exactly what you're trying to do.  See here for an illustration: http://mpitutorial.com/tutorials/mpi-scatter-gather-and-allgather/</p>

Body:
I have trouble executing this program in mpi4py. My objective is to send specific data to a particular node (that is why I am not using scatter). After that, process the data in each node, and finally gather all the results.

Apparently, my program does not understand how to gather the data from different nodes (maybe because gather is designed to work with scatter). I tried to send the date with comm.send() and gather with comm.gather(). When I execute the program, it runs forever, and I don't see any result.

Can you help me to find out how to gather the data from the different nodes? Is there other function to do this? May I need a loop over the nodes?

from mpi4py import MPI
import numpy as np

comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()

if rank == 0:
    data = list(np.arange(size) + 1)
    for i in range(size):
        comm.send(data[i], dest=i)
else:
    data = comm.recv(source=0)
    data += 1

print("rank", rank, "has data", data)

newData = comm.gather(data, root = 0)

if rank == 0:

    print("master collected", newData)


问:
Creating SQL users and restricting their permissions
Greetings,

My program creates a SQL database using ADO.NET APIs to connect to a SQL server and manipulate SQL connections/transactions. When the database is created, I'm connecting to the server using 'sa' credentials. This will be the only time I will connect to the database using 'sa' credentials. During this same initial connection, I need to create a couple of logins and users, so that from there on credentials of these users will be used. Now, I know how I can create logins and users, but I cant seem to get restrictions of access right. Specifically, I need to create 1 db login and user that will have access to all stored procedured created for the database - sort of like a db admin, but very restricted (to only stored procs). And the second db login/user will be given access only to a couple of specific stored procs. Any pointers? Thanks!

答:
Here you can find a stored procedure that grants access to all stored procedures to a user :

MS SQL Tips

All you have to do is to call it with the user that needs to have rights to exec all stored procedures as parameter.

From this script you can see the GRANT used to allow access to a stored procedure is :

```<code>GRANT EXEC ON ' + '[' + @OwnerName + ']' + '.' + '[' + @ObjectName + ']' + ' TO ' + @user
</code>```

Edit : paste the stored procedure from the link

```<code>CREATE PROCEDURE spGrantExectoAllStoredProcs @user sysname
AS

/*----------------------------------------------------------------------------
-- Object Name: spGrantExectoAllStoredProcs
-- Author: Edgewood Solutions
-- Development Date: 03.19.2007
-- Called By: TBD
-- Description: Issue GRANT EXEC statement for all stored procedures
-- based on the user name that is passed in to this stored procedure
-- Project: SQL Server Security
-- Database: User defined databases
-- Business Process: SQL Server Security
--
----------------------------------------------------------------------------
-- Num | CRF ID | Date Modified | Developer | Description
----------------------------------------------------------------------------
-- 001 | N\A      | 03.15.2007    | Edgewood | Original code for the GRANT
-- EXEC process
--
--
*/

SET NOCOUNT ON

-- 1 - Variable declarations
DECLARE @CMD1 varchar(8000)
DECLARE @MAXOID int
DECLARE @OwnerName varchar(128)
DECLARE @ObjectName varchar(128)

-- 2 - Create temporary table
CREATE TABLE #StoredProcedures
(OID int IDENTITY (1,1),
StoredProcOwner varchar(128) NOT NULL,
StoredProcName varchar(128) NOT NULL)

-- 3 - Populate temporary table
INSERT INTO #StoredProcedures (StoredProcOwner, StoredProcName)
SELECT ROUTINE_SCHEMA, ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME NOT LIKE 'dt_%'
AND ROUTINE_TYPE = 'PROCEDURE'

-- 4 - Capture the @MAXOID value
SELECT @MAXOID = MAX(OID) FROM #StoredProcedures

-- 5 - WHILE loop
WHILE @MAXOID > 0
BEGIN

-- 6 - Initialize the variables
SELECT @OwnerName = StoredProcOwner,
@ObjectName = StoredProcName
FROM #StoredProcedures
WHERE OID = @MAXOID

-- 7 - Build the string
SELECT @CMD1 = 'GRANT EXEC ON ' + '[' + @OwnerName + ']' + '.' + '[' + @ObjectName + ']' + ' TO ' + @user

-- 8 - Execute the string
-- SELECT @CMD1
EXEC(@CMD1)

-- 9 - Decrement @MAXOID
SET @MAXOID = @MAXOID - 1
END

-- 10 - Drop the temporary table
DROP TABLE #StoredProcedures

SET NOCOUNT OFF
GO
</code>```

Here it is.

All you need is to call this procedure with your sa user ;)

ContentLicense: CC BY-SA 2.5

Body:
Here you can find a stored procedure that grants access to all stored procedures to a user :

MS SQL Tips

All you have to do is to call it with the user that needs to have rights to exec all stored procedures as parameter.

From this script you can see the GRANT used to allow access to a stored procedure is :

GRANT EXEC ON ' + '[' + @OwnerName + ']' + '.' + '[' + @ObjectName + ']' + ' TO ' + @user

Edit : paste the stored procedure from the link

CREATE PROCEDURE spGrantExectoAllStoredProcs @user sysname
AS

/*----------------------------------------------------------------------------
-- Object Name: spGrantExectoAllStoredProcs
-- Author: Edgewood Solutions
-- Development Date: 03.19.2007
-- Called By: TBD
-- Description: Issue GRANT EXEC statement for all stored procedures
-- based on the user name that is passed in to this stored procedure
-- Project: SQL Server Security
-- Database: User defined databases
-- Business Process: SQL Server Security
--
----------------------------------------------------------------------------
-- Num | CRF ID | Date Modified | Developer | Description
----------------------------------------------------------------------------
-- 001 | N\A      | 03.15.2007    | Edgewood | Original code for the GRANT
-- EXEC process
--
--
*/

SET NOCOUNT ON

-- 1 - Variable declarations
DECLARE @CMD1 varchar(8000)
DECLARE @MAXOID int
DECLARE @OwnerName varchar(128)
DECLARE @ObjectName varchar(128)

-- 2 - Create temporary table
CREATE TABLE #StoredProcedures
(OID int IDENTITY (1,1),
StoredProcOwner varchar(128) NOT NULL,
StoredProcName varchar(128) NOT NULL)

-- 3 - Populate temporary table
INSERT INTO #StoredProcedures (StoredProcOwner, StoredProcName)
SELECT ROUTINE_SCHEMA, ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME NOT LIKE 'dt_%'
AND ROUTINE_TYPE = 'PROCEDURE'

-- 4 - Capture the @MAXOID value
SELECT @MAXOID = MAX(OID) FROM #StoredProcedures

-- 5 - WHILE loop
WHILE @MAXOID > 0
BEGIN

-- 6 - Initialize the variables
SELECT @OwnerName = StoredProcOwner,
@ObjectName = StoredProcName
FROM #StoredProcedures
WHERE OID = @MAXOID

-- 7 - Build the string
SELECT @CMD1 = 'GRANT EXEC ON ' + '[' + @OwnerName + ']' + '.' + '[' + @ObjectName + ']' + ' TO ' + @user

-- 8 - Execute the string
-- SELECT @CMD1
EXEC(@CMD1)

-- 9 - Decrement @MAXOID
SET @MAXOID = @MAXOID - 1
END

-- 10 - Drop the temporary table
DROP TABLE #StoredProcedures

SET NOCOUNT OFF
GO

Here it is.

All you need is to call this procedure with your sa user ;)


问:
Can I send special operators in autohotkey?
I want an AHK script which when I press NumPad7 returns {.

Now, in my keyboard { is Ctrl + Alt + ´

But the script

```<code>`NumPad7::
    Send, ^!´
 return`
</code>```

does nothing for some reason.

Update: It does work with regular keys like this:

```<code>p::
Send; ^!´
return
</code>```

Edit 2:
NumLock had to be on, now it works fine.

答:
This script gives you { from 7 on numeric keypad regardless of NumLock state:

```<code>NumPad7::
NumPadHome::
 SendRaw {
 Return
</code>```

Body:
I want an AHK script which when I press NumPad7 returns {.

Now, in my keyboard { is Ctrl + Alt + ´

But the script

`NumPad7::
    Send, ^!´
 return`

does nothing for some reason.

Update: It does work with regular keys like this:

p::
Send; ^!´
return

Edit 2:
NumLock had to be on, now it works fine.

Body:
This script gives you { from 7 on numeric keypad regardless of NumLock state:

NumPad7::
NumPadHome::
 SendRaw {
 Return


问:
the behavior of "const id"
I'm working on the 99 Haskell questions and saw a solution for finding the last element of a list:

```<code>  myLast = foldr1 (const id)
</code>```

the type of const is a -> b -> a but that of const id is b -> a -> a

so what's the magic here?

答:
The only way I finally grasped this was to imagine the sequence of steps Haskell takes in evaluating an expression like const id 1 2. First consider these statements:

In Haskell, all functions are considered curried: That is, all functions in Haskell take just one argument. 1

Functional application though, associates to the left: f x y is really (f x) y. 1

With this in mind, and seeing from above that const takes two arguments and id takes one, we can see these steps:

```<code>const id 1 2   -- Haskell evaluates 'const id' and returns a function (we can call it
               -- 'constId') which accepts one argument and always returns 'id'

constId 1 2    -- Haskell now evaluates 'constId 1', which as expected just returns 'id'

id 2           -- 'id' is now applied to 2, which just returns '2'

2              -- final result
</code>```

Disclaimer: I am new to Haskell.

Title: the behavior of "const id"

Body:
I'm working on the 99 Haskell questions and saw a solution for finding the last element of a list:

  myLast = foldr1 (const id)

the type of const is a -> b -> a but that of const id is b -> a -> a

so what's the magic here?

Body:
The only way I finally grasped this was to imagine the sequence of steps Haskell takes in evaluating an expression like const id 1 2. First consider these statements:

In Haskell, all functions are considered curried: That is, all functions in Haskell take just one argument. 1

Functional application though, associates to the left: f x y is really (f x) y. 1

With this in mind, and seeing from above that const takes two arguments and id takes one, we can see these steps:

const id 1 2   -- Haskell evaluates 'const id' and returns a function (we can call it
               -- 'constId') which accepts one argument and always returns 'id'

constId 1 2    -- Haskell now evaluates 'constId 1', which as expected just returns 'id'

id 2           -- 'id' is now applied to 2, which just returns '2'

2              -- final result

Disclaimer: I am new to Haskell.


问:
Windows popup interaction for downloading using selenium webdriver in python
I am making a programme to automatically download the data using selenium webdriver in python. When i click on "download" button following popup occours

.

with default option "Open with" selected. I want my program to first click on the option "save file" and then click on "OK".
I have used following piece of code to set up Firefox profile

```<code>    profile = webdriver.FirefoxProfile()
    profile.set_preference('browser.download.folderList', 2)
    profile.set_preference('browser.download.manager.showWhenStarting', False)
    profile.set_preference('browser.download.dir', os.getcwd())
    profile.set_preference('browser.helperApps.neverAsk.saveToDisk', "application/xlsx")
</code>```

But it is not working in my case. Then I tried to switch to this window from main window by using following code

```<code>    parent_h = driver.current_window_handle
    handles = driver.window_handles
    handles.remove(parent_h)
    driver.switch_to_window(handles.pop())
</code>```

But now I am not getting how to interact with this window?

答:
After so much findings and research, I get the following code which would be helpful for this type of situation.</p>

```<code>    profile = webdriver.FirefoxProfile()
    profile.set_preference("browser.download.dir",os.getcwd());
    profile.set_preference("browser.download.folderList",2);
    profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/csv,application/excel,application/vnd.msexcel,application/vnd.ms-excel,text/anytext,text/comma-separated-values,text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/octet-stream");
    profile.set_preference("browser.download.manager.showWhenStarting",False);
    profile.set_preference("browser.helperApps.neverAsk.openFile","application/csv,application/excel,application/vnd.msexcel,application/vnd.ms-excel,text/anytext,text/comma-separated-values,text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/octet-stream");
    profile.set_preference("browser.helperApps.alwaysAsk.force", False);
    profile.set_preference("browser.download.manager.useWindow", False);
    profile.set_preference("browser.download.manager.focusWhenStarting", False);
    profile.set_preference("browser.download.manager.alertOnEXEOpen", False);
    profile.set_preference("browser.download.manager.showAlertOnComplete", False);
    profile.set_preference("browser.download.manager.closeWhenDone", True);
    profile.set_preference("pdfjs.disabled", True);
</code>```

Body:
I am making a programme to automatically download the data using selenium webdriver in python. When i click on "download" button following popup occours

.

with default option "Open with" selected. I want my program to first click on the option "save file" and then click on "OK".
I have used following piece of code to set up Firefox profile

    profile = webdriver.FirefoxProfile()
    profile.set_preference('browser.download.folderList', 2)
    profile.set_preference('browser.download.manager.showWhenStarting', False)
    profile.set_preference('browser.download.dir', os.getcwd())
    profile.set_preference('browser.helperApps.neverAsk.saveToDisk', "application/xlsx")

But it is not working in my case. Then I tried to switch to this window from main window by using following code

    parent_h = driver.current_window_handle
    handles = driver.window_handles
    handles.remove(parent_h)
    driver.switch_to_window(handles.pop())

But now I am not getting how to interact with this window?

Body:
After so much findings and research, I get the following code which would be helpful for this type of situation.

    profile = webdriver.FirefoxProfile()
    profile.set_preference("browser.download.dir",os.getcwd());
    profile.set_preference("browser.download.folderList",2);
    profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/csv,application/excel,application/vnd.msexcel,application/vnd.ms-excel,text/anytext,text/comma-separated-values,text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/octet-stream");
    profile.set_preference("browser.download.manager.showWhenStarting",False);
    profile.set_preference("browser.helperApps.neverAsk.openFile","application/csv,application/excel,application/vnd.msexcel,application/vnd.ms-excel,text/anytext,text/comma-separated-values,text/csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/octet-stream");
    profile.set_preference("browser.helperApps.alwaysAsk.force", False);
    profile.set_preference("browser.download.manager.useWindow", False);
    profile.set_preference("browser.download.manager.focusWhenStarting", False);
    profile.set_preference("browser.download.manager.alertOnEXEOpen", False);
    profile.set_preference("browser.download.manager.showAlertOnComplete", False);
    profile.set_preference("browser.download.manager.closeWhenDone", True);
    profile.set_preference("pdfjs.disabled", True);


问:
VBA Select Case runs through without selection
I am really puzzled by this one. Searched the net already but did not find any answer related to my specific case. I have the following code:

```<code>Dim CE_res As Integer

For Index = 1 To 7

Status = ""
CE_res = CInt(Worksheets("werkblad").Range("CEres" & Index).Value)

If CE_res = 0 Then
' Everything ok
    Status = "Pass"

Else

    Select Case CE_res

        Case CE_res < -1500
            Status = "Invalid kV Value"

        Case CE_res < -999
            Status = "No kV Value"

        Case CE_res < -399
            Status = "kV too high"

        Case CE_res = 0
            Status = "kV too low"

        Case CE_res > 500
            Status = "Invalid mAs Value"

        Case CE_res > 49
            Status = "mAs Value missing"

        Case CE_res > 9 And CE_res < 50
            Status = "Adapt Target"

        Case CE_res > 200
            Status = "Adapt Filter"

        Case Else
            Status = "No Selection"

    End Select

End If
</code>```

The CE_res is set to 50. However, always Case Else is selected. Declared CE_res as integer, coverted Worksheets("werkblad").Range("CEres" & Index).Value to an integer, just to be sure.
However, it does not seem to execute the Select Case correctly. Tried it also with other values, even changed the case CE_res > 49 to CE_res = "50" but this also did not work.

Now, I am out of ideas what could be wrong.

答:
You are not using the correct syntax for the Case statements

```<code>Dim CE_res As Integer

For Index = 1 To 7

Status = ""
CE_res = CInt(Worksheets("werkblad").Range("CEres" & Index).Value)

If CE_res = 0 Then
' Everything ok
    Status = "Pass"

Else

    Select Case CE_res

        Case < -1500
            Status = "Invalid kV Value"

        Case < -999
            Status = "No kV Value"

        Case < -399
            Status = "kV too high"

        Case 0  ' or possibly Case < 0 ????
            Status = "kV too low"

        Case > 500
            Status = "Invalid mAs Value"

        Case > 200
            Status = "Adapt Filter"

        Case > 49
            Status = "mAs Value missing"

        Case > 9
            Status = "Adapt Target"

        Case Else
            Status = "No Selection"

    End Select

End If
</code>```

Note that I had to move > 200 prior to > 49, otherwise a value of, for instance, 230 would have matched > 49 and therefore never reached your > 200.

The way you had it, the statement Case CE_res < -1500 would test if CE_res was < -1500.  If it was, that would return a True which was then compared to the object of the case statement (i.e. CE_res) and, if it matched (which it wouldn't) that leg of the Select statement would execute.

Body:
I am really puzzled by this one. Searched the net already but did not find any answer related to my specific case. I have the following code:

Dim CE_res As Integer

For Index = 1 To 7

Status = ""
CE_res = CInt(Worksheets("werkblad").Range("CEres" & Index).Value)

If CE_res = 0 Then
' Everything ok
    Status = "Pass"

Else

    Select Case CE_res

        Case CE_res < -1500
            Status = "Invalid kV Value"

        Case CE_res < -999
            Status = "No kV Value"

        Case CE_res < -399
            Status = "kV too high"

        Case CE_res = 0
            Status = "kV too low"

        Case CE_res > 500
            Status = "Invalid mAs Value"

        Case CE_res > 49
            Status = "mAs Value missing"

        Case CE_res > 9 And CE_res < 50
            Status = "Adapt Target"

        Case CE_res > 200
            Status = "Adapt Filter"

        Case Else
            Status = "No Selection"

    End Select

End If

The CE_res is set to 50. However, always Case Else is selected. Declared CE_res as integer, coverted Worksheets("werkblad").Range("CEres" & Index).Value to an integer, just to be sure.
However, it does not seem to execute the Select Case correctly. Tried it also with other values, even changed the case CE_res > 49 to CE_res = "50" but this also did not work.

Now, I am out of ideas what could be wrong.

Body:
You are not using the correct syntax for the Case statements

Dim CE_res As Integer

For Index = 1 To 7

Status = ""
CE_res = CInt(Worksheets("werkblad").Range("CEres" & Index).Value)

If CE_res = 0 Then
' Everything ok
    Status = "Pass"

Else

    Select Case CE_res

        Case < -1500
            Status = "Invalid kV Value"

        Case < -999
            Status = "No kV Value"

        Case < -399
            Status = "kV too high"

        Case 0  ' or possibly Case < 0 ????
            Status = "kV too low"

        Case > 500
            Status = "Invalid mAs Value"

        Case > 200
            Status = "Adapt Filter"

        Case > 49
            Status = "mAs Value missing"

        Case > 9
            Status = "Adapt Target"

        Case Else
            Status = "No Selection"

    End Select

End If

Note that I had to move > 200 prior to > 49, otherwise a value of, for instance, 230 would have matched > 49 and therefore never reached your > 200.

The way you had it, the statement Case CE_res < -1500 would test if CE_res was < -1500.  If it was, that would return a True which was then compared to the object of the case statement (i.e. CE_res) and, if it matched (which it wouldn't) that leg of the Select statement would execute.


问:
Generating Multiple Thumbnails Swift 3
I am attempting to load multiple thumbnails from a video url into a UIImageView. I can't seem to figure it out; I currently found how to just load a single thumbnail, but can't seem to figure out how to do it for multiple.

Here is the code:

```<code>private func thumbnailForVideoAtURL(url: NSURL) -> UIImage? {

    let asset = AVAsset(URL: url)
    let assetImageGenerator = AVAssetImageGenerator(asset: asset)

    var time = asset.duration
    time.value = min(time.value, 2)

    do {
        let imageRef = try assetImageGenerator.copyCGImageAtTime(time, actualTime: nil)
        return UIImage(CGImage: imageRef)
    } catch {
        print("error")
        return nil
    }
}
</code>```

&& within my viewDidLoad:

```<code>imageView.frame = CGRect(x:0, y: self.view.frame.height / 2, width: self.view.frame.width, height: 100)
        imageView.image = thumbnailForVideoAtURL(url: url!)
        view.addSubview(imageView)
</code>```

答:
You should use generateCGImagesAsynchronously(forTimes:completionHandler:) method instead of copyCGImage(at:actualTime:)

AVAssetImageGenerator uses the default enabled video track(s) to generate images. Generating a single image in isolation can require the decoding of a large number of video frames with complex interdependencies. If you require a series of images, you can achieve far greater efficiency using the asynchronous method, generateCGImagesAsynchronously(forTimes:completionHandler:), which employs decoding efficiencies similar to those used during playback.

Title: Generating Multiple Thumbnails Swift 3

Body:
I am attempting to load multiple thumbnails from a video url into a UIImageView. I can't seem to figure it out; I currently found how to just load a single thumbnail, but can't seem to figure out how to do it for multiple.

Here is the code:

private func thumbnailForVideoAtURL(url: NSURL) -> UIImage? {

    let asset = AVAsset(URL: url)
    let assetImageGenerator = AVAssetImageGenerator(asset: asset)

    var time = asset.duration
    time.value = min(time.value, 2)

    do {
        let imageRef = try assetImageGenerator.copyCGImageAtTime(time, actualTime: nil)
        return UIImage(CGImage: imageRef)
    } catch {
        print("error")
        return nil
    }
}

&& within my viewDidLoad:

imageView.frame = CGRect(x:0, y: self.view.frame.height / 2, width: self.view.frame.width, height: 100)
        imageView.image = thumbnailForVideoAtURL(url: url!)
        view.addSubview(imageView)


问:
Multitasking latency and throughput
I have been doing some experimentation around multi-threading and multi-tasking and I have a few questions.

1) Consider a machine with just one CPU core/processor. Running multiple threads parallely is achieved by time slicing (each thread is given a few milliseconds to run on the CPU) and if one thread is blocked on I/O, the others can run, thus giving an impression of doing multiple things concurrently.

Consider the same single processor CPU and say there are two threads, both of which is CPU intensive and does no I/O.
Each takes 5 seconds to complete its operation. Running it sequentially will take obviously 10 secs.

Will running it parallely (using executor service) also take 10 seconds since the threads are CPU intensive only? (given that there is only one CPU core)

2) On a machine with four cores, I have a task that will take 5 seconds to complete when run independently. I wanted to run a couple of them in parallel as separate processes using Java's ProcessBuilder (I don't want to run as parallel threads as the object that they share is not thread safe and cost of synchronization is too much).
I expected it to complete around 5 seconds.

Starting two parallel process did not yield much improvement as they still took around 9 seconds to complete. Why is that? (the task is both CPU intensive and consumes significant memory).
  Note: As I start three or four processes, the latency is more and more affected (worse or equivalent to running them in sequence).

EDIT

My intention/ question is more around why the performance is not improved when using processes rather than whether I should use multiple threads/process for my second question.
For question 2, (for the sake of discussion) you can simple imagine the task like this: (Although the numbers mentioned in the question above is not from the below snippet)

```<code>String s;
for (int i = 0; i < 50000; i++) {
 s += i; //consumes a lot of memory
}

long result = 0;
for(int j = 0; j < 3; j++) {
  for (double i = 0; i < 500000000; i++) { //Lot of CPU
    result += i;
   }
}
</code>```

答:
Will running it parallely (using executor service) also take 10
  seconds since the threads are CPU intensive only? (given that there is
  only one CPU core)

In principle, no.  By running them in parallel, you're bound to waste some time in context-switching, so theoretically, they'll take more than 10s.  In practice, the difference will hardly be detectable, because the additional load from your two processes (or threads) may not turn up contention for CPU enough for any noticeable increase of losses in switching.

Starting two parallel process did not yield much improvement as they
  still took around 9 seconds to complete. Why is that? (the task is
  both CPU intensive and consumes significant memory). Note: As I start
  three or four processes, the latency is more and more affected (worse
  or equivalent to running them in sequence).

Your experiment is contaminated by the overhead of starting two or more processes instead of just one, so it's practically useless to try and draw any conclusions here (unless you took special care to measure exactly the calculation portion of the task.)

Title: Multitasking latency and throughput

Body:
I have been doing some experimentation around multi-threading and multi-tasking and I have a few questions.

1) Consider a machine with just one CPU core/processor. Running multiple threads parallely is achieved by time slicing (each thread is given a few milliseconds to run on the CPU) and if one thread is blocked on I/O, the others can run, thus giving an impression of doing multiple things concurrently.

Consider the same single processor CPU and say there are two threads, both of which is CPU intensive and does no I/O.
Each takes 5 seconds to complete its operation. Running it sequentially will take obviously 10 secs.

Will running it parallely (using executor service) also take 10 seconds since the threads are CPU intensive only? (given that there is only one CPU core)

2) On a machine with four cores, I have a task that will take 5 seconds to complete when run independently. I wanted to run a couple of them in parallel as separate processes using Java's ProcessBuilder (I don't want to run as parallel threads as the object that they share is not thread safe and cost of synchronization is too much).
I expected it to complete around 5 seconds.

Starting two parallel process did not yield much improvement as they still took around 9 seconds to complete. Why is that? (the task is both CPU intensive and consumes significant memory).
  Note: As I start three or four processes, the latency is more and more affected (worse or equivalent to running them in sequence).

EDIT

My intention/ question is more around why the performance is not improved when using processes rather than whether I should use multiple threads/process for my second question.
For question 2, (for the sake of discussion) you can simple imagine the task like this: (Although the numbers mentioned in the question above is not from the below snippet)

String s;
for (int i = 0; i < 50000; i++) {
 s += i; //consumes a lot of memory
}

long result = 0;
for(int j = 0; j < 3; j++) {
  for (double i = 0; i < 500000000; i++) { //Lot of CPU
    result += i;
   }
}


问:
OneDrive API (rest) . Folders and Files on Drives
I try to make integration with OneDrive, using the API https://dev.onedrive.com/getting-started.htm

I make auth work and i can get list of drives in the account .
When i execute the API call /me/drives i am getting the list of drives fine.

But i can not find how to get list of folders on a drive, subfolders of a folder etc.

From the docs i can see there are some API for this, but it doesn't work for me.
https://dev.onedrive.com/items/list.htm

I have to execute on of.

```<code>GET /drive/items/{item-id}/children
GET /drive/root:/{item-path}:/children
</code>```

But it doesn't work. I have a Drive ID from a list of drives. When i execute
GET /drive/items/DRIVEID/children
i have error "Access denied. You do not have permission to perform this action or access this resource."

How to do this operation? should i use a drive ID or name? maybe the url is wrong, what must be the correct url if i have  a drive name, ID ?

答:
I have found how to do this. To understand i had to install some other tool where OneDrive API is used and debugged traffic with a https sniffer.

So, if endpoint is https://graph.microsoft.com/v1.0/me/
then paths are

```<code>/drives/DRIVEID/root/children
</code>```

for root of drive

```<code>/drives/DRIVEID/root:myfolder/subfolder:/children
</code>```

for a folder myfolder/subfolder

Final url is like

```<code>https://graph.microsoft.com/v1.0/me/drives/DRIVEID/root:myfolder/subfolder:/children
</code>```

Body:
I try to make integration with OneDrive, using the API https://dev.onedrive.com/getting-started.htm

I make auth work and i can get list of drives in the account .
When i execute the API call /me/drives i am getting the list of drives fine.

But i can not find how to get list of folders on a drive, subfolders of a folder etc.

From the docs i can see there are some API for this, but it doesn't work for me.
https://dev.onedrive.com/items/list.htm

I have to execute on of.

GET /drive/items/{item-id}/children
GET /drive/root:/{item-path}:/children

But it doesn't work. I have a Drive ID from a list of drives. When i execute
GET /drive/items/DRIVEID/children
i have error "Access denied. You do not have permission to perform this action or access this resource."

How to do this operation? should i use a drive ID or name? maybe the url is wrong, what must be the correct url if i have  a drive name, ID ?

Body:
I have found how to do this. To understand i had to install some other tool where OneDrive API is used and debugged traffic with a https sniffer.

So, if endpoint is https://graph.microsoft.com/v1.0/me/
then paths are

/drives/DRIVEID/root/children

for root of drive

/drives/DRIVEID/root:myfolder/subfolder:/children

for a folder myfolder/subfolder

Final url is like

https://graph.microsoft.com/v1.0/me/drives/DRIVEID/root:myfolder/subfolder:/children


答: For me, I prefer using a external file for your JFrame option. FileReader for getting the value from the file, loop and assign them either on array or variables. And PrintWriter for changing the option. Hope this help</p>

Title: Java - How to share objects within different static methods in same class

Body:
How would one go about sharing an object between static methods? Is this even possible? Is there a better way?

In my code, I have one frame in one class. I have different static methods to do stuff with this frame in the same class. I call these methods in another class.

Is there a better way of doing this for swing? Essentially I want to create a Frame, in which I can edit the size, and colour, and contents through the methods of other classes (these classes would have Panels which I would use on this frame).

Class calling the static methods:

import javax.swing.*;

public class Main{

    // Display Login Window
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try
            {
                new loginFrames();
                loginFrames.showFrame("hello", 1200, 800);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        });
    }
}

Class with the static methods:

import javax.swing.*;
import java.awt.*;

public class loginFrames{

    public JFrame appFrame;

    public void createFrame(String frameName, int frameW, int frameH) {

        // Create JFrame with frame name, width, and height
        appFrame = new JFrame(frameName);
        appFrame.setSize(frameW, frameH);

        // Get the content pane and set the background colour black
        Container absFrameContentPane = appFrame.getContentPane();
        absFrameContentPane.setBackground(Color.BLACK);

        // Show the frame
        appFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        appFrame.setVisible(true);
    }

    // Callable from Main class
    public static void showFrame(String frameName, int frameW, int frameH) {
        loginFrames applicationFrame = new loginFrames();
        applicationFrame.createFrame(frameName, frameW, frameH);
    }

    // Callable from Main class
    public static void appAddPanel(String frameName, int frameW, int frameH) {
    // How do I call the same object above, here?
    }
}


问:
how to limit number of comments by query
I want to limit the number of comments to show in wordpress template-page.php
I didnt get any reasult in google searching.
I want to use jquery for this problem but what i know is wordpress. Not full of php.</p>

答:
I think you can use the WP_Comment_Query Class

Try the following. (this is a basic one though and you can customize this to your needs.)

Open your functions.php file and add the following function

```<code>function get_custom_comments(){

    $args = array(
   'number' => '1', // number of comments you want to show
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
if ( $comments ) {
    foreach ( $comments as $comment ) {
        echo '<p>' . $comment->comment_content . '</p>';
    }
} else {
    echo 'No comments found.';
}
</code>```

Now in your single.php file, replace any comment template you have with the following

```<code>get_custom_comments();
</code>```

PS: Add some CSS classes to make it look your original comment template.

Body:
I think you can use the WP_Comment_Query Class

Try the following. (this is a basic one though and you can customize this to your needs.)

Open your functions.php file and add the following function

function get_custom_comments(){

    $args = array(
   'number' => '1', // number of comments you want to show
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
if ( $comments ) {
    foreach ( $comments as $comment ) {
        echo '<p>' . $comment->comment_content . '</p>';
    }
} else {
    echo 'No comments found.';
}

Now in your single.php file, replace any comment template you have with the following

get_custom_comments();

PS: Add some CSS classes to make it look your original comment template.


问:
System.IO.FileNotFoundException: Could not load file or assembly when using resources in 2 C# projects
I am currently working with 2 C# projects inside one VS 2017 solution. One project contains all the business logic and the other simply the UI. The UI, of course, references the Core project.

The Core solution uses RestSharp package on it's code, so I installed it using NuGet. When I run the solution and I reach the part of the code where RestSharp is used, the following exception is thrown: "System.IO.FileNotFoundException: Could not load file or assembly 'RestSharp'".

The problem gets solved if I also install 'RestSharp' package inside the UI project. But, I am trying to avoid that as the UI does not need to use that package.

Is there a way to avoid that? Regards

答: Check if Copy Local is set to true for the RestSharp reference. When it is set the RestSharp dll will be copied along with the Core dll.


问:
Logout button to unset and destroy the SESSION variables not working
I have a PHP page in which I have the button for login and register. But the problem in my page is that when I log out the button is not redirected to the php page of logout to unset and destroy the session variables.

I am providing here the code of that page so that someone can help me rectify the error.

```<code><div class="wrapper row1">
<header id="header" class="clear">
    <!-- THE BANNER -->
    <div id="logo" class="fl_left">
        <a href="index.php"> <img src="images\logo.jpg"></a>
    </div>
    <div class="fl_right">
        <ul class="inline">
            <li><i class="fa fa-phone"></i> +91 1234567890 </li>
            <li><i class="fa fa-envelope"></i> info@hoteldaffodils.com </li>
            <?php   if(isset($_SESSION['email']))
            {
            ?>
            <li>
            <?php
                echo $_SESSION['email'];
            ?>
            </li>
            <li><h1> | </h1></li>
            <li><h1><i class="fa fa-sign-out"></i> <style="float:right"> <a href="logout.php"> LOG OUT </a></h1></li>
            <?php
            }
            else
            {
            ?>
            <li><h1><i class="fa fa-sign-in"></i> <style="float:right" onclick="document.getElementById('id01').style.display='block'"> LOG IN </h1></li>
            <li><h1> | </h1></li>
            <li><h1><i class="fa fa-user"></i> <style="float:right" onclick="document.getElementById('id02').style.display='block'"> REGISTER </h1></li>
            <?php
            }
            ?>
        </ul>
    </div>
    </div>
</header>
</code>```

the contents of logout.php is as given below

```<code><?php
session_unset();
session_destroy();
header('Location:index.php');
</code>```

?>

答:
Just add a line to your logout.php file:

```<code><?php
session_start();
session_destroy();
header('Location:index.php');
?>
</code>```

Destroying the session will delete all session data so the session_unset() line is unnecessary.

Body:
I have a PHP page in which I have the button for login and register. But the problem in my page is that when I log out the button is not redirected to the php page of logout to unset and destroy the session variables.

I am providing here the code of that page so that someone can help me rectify the error.

 +91 1234567890

 info@hoteldaffodils.com

            <?php   if(isset($_SESSION['email']))
            {
            ?>

            <?php
                echo $_SESSION['email'];
            ?>

 |

Body:
Just add a line to your logout.php file:

<?php
session_start();
session_destroy();
header('Location:index.php');
?>

Destroying the session will delete all session data so the session_unset() line is unnecessary.


问:
pulling a random item from multiple arrays
I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

```<code>var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}
</code>```

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.

答:
```<code>var sm1 = [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12].map(function (arr) {
    return arr[Math.floor((Math.random() * arr.length))];
});
</code>```

I'd vote using 2-d array instead of named 12 single arrays though.

Body:
I have 12 arrays named f1 to f12 each with five items. I want to randomly pull one item from each array and push these into the new array sm1.

var sm1 = [];

for (var i=1; i<=12; i++) {
    randomPrompt = Math.floor((Math.random() * 5));
    sm1.push("f"+i[randomPrompt]);
}

However, this returns a random index of "f"+i instead of it indexing f1, f2, f3, f4, etc.

Body:
var sm1 = [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12].map(function (arr) {
    return arr[Math.floor((Math.random() * arr.length))];
});

I'd vote using 2-d array instead of named 12 single arrays though.


问:
Which has better performance HMAC SHA-2 or KMAC SHA-3
I am attempting to implement either HMAC SHA-2 or KMAC SHA-3 on a Raspberry Pi 3 (and possibly a Raspberry Pi 0). Which would have better performance? Any suggestions are very helpful.</p>

答:
I am attempting to implement either HMAC SHA-2 or KMAC SHA-3 on a Raspberry Pi 3 (and possibly a Raspberry Pi 0). Which would have better performance?

RPI-3's are AMRv8. ARMv8 has CRC and optionally Crypto extensions. The Crypto extensions include Carryless Multiplies, AES, SHA-1 and SHA-2 acceleration. Since there is potentially acceleration for SHA-2 but not SHA-3, SHA-2 will be faster on devices with the crypto extensions.

You can find the source code for SHA using ARMv8 intrinsics at GitHub | SHA-Intrinsics.

If there is no hardware acceleration, then you need to find an implementation that provides the best cycles-per-byte throughput. That's your job to find.


问:
How to read specific special character
I have a string like

```<code>Str s1 = abd,jh
Str2 = aa$$ab
</code>```

I want to read string which have only a,b and $.

```<code>Str1 return false
Str2 return true.
</code>```

My Code

```<code>public static boolean containsOtherCharacter(String str) {
        String[] st = str.split("");
        for(int x = 0; x < st.length; x++)
            if (st[x].compareTo("A") != 0 && st[x].compareTo("B") != 0 && st[x].compareTo("$") != 0)
                return true;
        return false;
    }
</code>```

Any help how to read that. Any other value other then this should be ignored.

答:
Here's another way to solve this:</p>

```<code>public static boolean containsOtherCharacter(String str) {
           boolean The_answer=false;
           int count0 = StringUtils.countMatches(str, "a");
           int count1 = StringUtils.countMatches(str, "b");
           int count2 = StringUtils.countMatches(str, "$");
           int ans=count0+count1+count2;

           if(ans==str.length())The_anser=true;

           return The_answer;
   }
</code>```

Title: How to read specific special character

Body:
I have a string like

Str s1 = abd,jh
Str2 = aa$$ab

I want to read string which have only a,b and $.

Str1 return false
Str2 return true.

My Code

public static boolean containsOtherCharacter(String str) {
        String[] st = str.split("");
        for(int x = 0; x < st.length; x++)
            if (st[x].compareTo("A") != 0 && st[x].compareTo("B") != 0 && st[x].compareTo("$") != 0)
                return true;
        return false;
    }

Any help how to read that. Any other value other then this should be ignored.

Body:
Here's another way to solve this:

public static boolean containsOtherCharacter(String str) {
           boolean The_answer=false;
           int count0 = StringUtils.countMatches(str, "a");
           int count1 = StringUtils.countMatches(str, "b");
           int count2 = StringUtils.countMatches(str, "$");
           int ans=count0+count1+count2;

           if(ans==str.length())The_anser=true;

           return The_answer;
   }


问:
Creating a new column to a data frame using a formula from another variable
I want to create a new column to a data frame using a formula from another variable.

Example:

I have a data set "aa" is;

```<code>x    y
2    3
4    5
6    7
</code>```

My R code is;

```<code>>bb <- "x+y-2"
>attach(aa)
>aa$z<- bb
>detach(aa)
</code>```

the result is;

```<code>x  y  z
2  3  x+y-2
4  5  x+y-2
6  7  x+y-2
</code>```

but I want like this;

```<code>x  y  z
2  3  3
4  5  7
6  7  11
</code>```

Could you please help me..

答:
you can use mutate from the package dplyr

```<code>library(dplyr)
aa <- aa %>% mutate(z = x+y-2)
</code>```

Hope it helps.

Body:
I want to create a new column to a data frame using a formula from another variable.

Example:

I have a data set "aa" is;

x    y
2    3
4    5
6    7

My R code is;

>bb <- "x+y-2"
>attach(aa)
>aa$z<- bb
>detach(aa)

the result is;

x  y  z
2  3  x+y-2
4  5  x+y-2
6  7  x+y-2

but I want like this;

x  y  z
2  3  3
4  5  7
6  7  11

Could you please help me..

Body:
you can use mutate from the package dplyr

library(dplyr)
aa <- aa %>% mutate(z = x+y-2)

Hope it helps.


问:
How to parse float with two decimal places in javascript?
I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.</p>

```<code>price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
</code>```

答:
You can use toFixed() to do that</p>

```<code>var twoPlacedFloat = parseFloat(yourString).toFixed(2)
</code>```

Body:
I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.

price_result = parseFloat(test_var.split('$')[1].slice(0,-1));

Body:
You can use toFixed() to do that

var twoPlacedFloat = parseFloat(yourString).toFixed(2)


问:
open an subform based on the selection in list box in Access
so basicly i have a problem with opening an subform. I have a Main form that contains 2 list boxes. Selection on the first list box cause change in the displayed records in the second list box. And selection on the second list box should fill my subform with data. My problem is that i cant get second list box to affect the data on the subform.

For example: 1st listbox is a supplier list, 2nd listbox is goods received. Depends on the selected supplier i receive diffrent goods on the 2nd list. And after selection of the specific goods on the list i want to receive a table of all received boxes of selected goods of selected supplier in my subform. (Right now selection on the first list cause my subform to show me all goods from selected supplier, while selection on second list dosen't do anyting with the subform)

答: Use Master Child relation. Select the subform and in Data tab select the Master and Child relation and then the subform will be filtered based on the selection.</p>


问:
openShot installation Error-archLinux
I wanna install openShot video editor for my arch-Linux but getting following error. Please, someone, help me out.

pastebinLink: https://pastebin.com/sDEEVJNk

```

答:
I got it. I removed /usr/lib/python3.6/site-packages/zmq/ folder. After that, I have installed openShot successfully.

After that, I installed zmq.

```<code>$ sudo pip install zmq
</code>```

Title: openShot installation Error-archLinux

Body:
I got it. I removed /usr/lib/python3.6/site-packages/zmq/ folder. After that, I have installed openShot successfully.

After that, I installed zmq.

$ sudo pip install zmq


问:
How to use $http.then response in another method which is called from view in angularjs?
I have view which has a function inside a table td to check whether the td has data stored in database. If td has data, it will red colored:

```<code><tr ng-repeat="row in rows">
            <td ng-repeat="column in columns" style="width: 100px; cursor: pointer"
                ng-style="{background: getWeight(row, column) ? 'red' :  '' }"
                ng-click="onCellselect(row, column)">
                @{{row}}@{{column}}
            </td>
        </tr>
</code>```

JS:

```<code>  $http.get("api/getYardGraphDetails")

    .then(function (r) {
        console.log(r.data)

        $scope.weights =r.data

    })

$scope.getWeight = function (row, column) {
    console.log($scope.weights)

        // See if there's a record with the row and column.
        var record = _.find($scope.weights, {
            row: row,
            column: column
        });

        // Was a record found with the row and column?
        if (record) {
            // If so return its weight.
            return record.weight;
        }

};
</code>```

in $scope.getWeight() function $scope.weights comes from an $http.get response. But console.log($scope.weights) inside $scope.getWeight()  returns undefined

How can i get $scope.weights from $http.get for $scope.getWeight() ?

I think i should call $scope.getWeight() after $http.getreturns data from database. As $http.get is async it doesn't wait for response and that's my $scope.weights doesn't has value in $scope.getWeight().

答:
the thing is getWeight is called before the $http.get has returned.
what I would have done is inside the then function create $scope.weights as and array, somthing like this

```<code>$http.get("api/getYardGraphDetails")

.then(function (r) {
    console.log(r.data)

    $scope.weights =[]
    for(var weight in r.data){
        $scope.weights[weight.row + "-" + weight.column] = _.find($scope.weights, {
        row: weight.row,
        column: weight.column
    });
    }
})
</code>```

then use it like this

```<code>ng-style="{background: weights[row + '-' + col]  ? 'red' :  '' }"
</code>```

Body:
I have view which has a function inside a table td to check whether the td has data stored in database. If td has data, it will red colored:

                @{{row}}@{{column}}

JS:

  $http.get("api/getYardGraphDetails")

    .then(function (r) {
        console.log(r.data)

        $scope.weights =r.data

    })

$scope.getWeight = function (row, column) {
    console.log($scope.weights)

        // See if there's a record with the row and column.
        var record = _.find($scope.weights, {
            row: row,
            column: column
        });

        // Was a record found with the row and column?
        if (record) {
            // If so return its weight.
            return record.weight;
        }

};

in $scope.getWeight() function $scope.weights comes from an $http.get response. But console.log($scope.weights) inside $scope.getWeight()  returns undefined

How can i get $scope.weights from $http.get for $scope.getWeight() ?

I think i should call $scope.getWeight() after $http.getreturns data from database. As $http.get is async it doesn't wait for response and that's my $scope.weights doesn't has value in $scope.getWeight().

Body:
the thing is getWeight is called before the $http.get has returned.
what I would have done is inside the then function create $scope.weights as and array, somthing like this

$http.get("api/getYardGraphDetails")

.then(function (r) {
    console.log(r.data)

    $scope.weights =[]
    for(var weight in r.data){
        $scope.weights[weight.row + "-" + weight.column] = _.find($scope.weights, {
        row: weight.row,
        column: weight.column
    });
    }
})

then use it like this

ng-style="{background: weights[row + '-' + col]  ? 'red' :  '' }"


问:
unique_ptr trouble? (VS 2015)
I’ve just copied some code from here http://en.cppreference.com/w/cpp/language/pimpl, added <memory> and main.cpp, corrected std::experimental::propagate_const<std::unique_ptr<impl>>. Visual Studio 2015.

```<code>// widget.h
#include <memory>

class widget
{
    // public members
private:
    struct impl;
    std::unique_ptr<impl> pImpl;
};
</code>```

.

```<code>// widget.cpp
#include "widget.h"

struct widget::impl {
    // implementation details
};
</code>```

widget.cpp is compiled fine, but main.cpp is not.

```<code>#include "widget.h"

int main()
{
    widget w;
}
</code>```

Error messages.

```<code>1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1193): error C2027: use of undefined type 'widget::impl'
1>  e:\***\***\***\widget.h(8): note: see declaration of 'widget::impl'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1192): note: while compiling class template member function 'void std::default_delete<_Ty>::operator ()(_Ty *) noexcept const'
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1397): note: see reference to function template instantiation 'void std::default_delete<_Ty>::operator ()(_Ty *) noexcept const' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1227): note: see reference to class template instantiation 'std::default_delete<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1236): note: see reference to class template instantiation 'std::_Get_deleter_pointer_type<_Ty,std::default_delete<_Ty>>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1279): note: see reference to class template instantiation 'std::_Unique_ptr_base<_Ty,_Dx>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl,
1>              _Dx=std::default_delete<widget::impl>
1>          ]
1>  e:\***\***\***\***.h(10): note: see reference to class template instantiation 'std::unique_ptr<widget::impl,std::default_delete<_Ty>>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1194): error C2338: can't delete an incomplete type
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1195): warning C4150: deletion of pointer to incomplete type 'widget::impl'; no destructor called
1>  e:\***\***\***\widget.h(8): note: see declaration of 'widget::impl'
</code>```

答: Define the destructor of Widget empty in a separate cpp. Include the definition of impl in that cpp. The destructor of impl is called in that cpp because you included the definition.</p>

Title: unique_ptr trouble? (VS 2015)

Body:
I’ve just copied some code from here http://en.cppreference.com/w/cpp/language/pimpl, added <memory> and main.cpp, corrected std::experimental::propagate_const<std::unique_ptr<impl>>. Visual Studio 2015.

// widget.h
#include <memory>

class widget
{
    // public members
private:
    struct impl;
    std::unique_ptr<impl> pImpl;
};

.

// widget.cpp
#include "widget.h"

struct widget::impl {
    // implementation details
};

widget.cpp is compiled fine, but main.cpp is not.

#include "widget.h"

int main()
{
    widget w;
}

Error messages.

1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1193): error C2027: use of undefined type 'widget::impl'
1>  e:\***\***\***\widget.h(8): note: see declaration of 'widget::impl'
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1192): note: while compiling class template member function 'void std::default_delete<_Ty>::operator ()(_Ty *) noexcept const'
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1397): note: see reference to function template instantiation 'void std::default_delete<_Ty>::operator ()(_Ty *) noexcept const' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1227): note: see reference to class template instantiation 'std::default_delete<_Ty>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1236): note: see reference to class template instantiation 'std::_Get_deleter_pointer_type<_Ty,std::default_delete<_Ty>>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>  c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1279): note: see reference to class template instantiation 'std::_Unique_ptr_base<_Ty,_Dx>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl,
1>              _Dx=std::default_delete<widget::impl>
1>          ]
1>  e:\***\***\***\***.h(10): note: see reference to class template instantiation 'std::unique_ptr<widget::impl,std::default_delete<_Ty>>' being compiled
1>          with
1>          [
1>              _Ty=widget::impl
1>          ]
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1194): error C2338: can't delete an incomplete type
1>c:\program files (x86)\microsoft visual studio 14.0\vc\include\memory(1195): warning C4150: deletion of pointer to incomplete type 'widget::impl'; no destructor called
1>  e:\***\***\***\widget.h(8): note: see declaration of 'widget::impl'


问:
Swift 3 UITableView not updating after deleting from Firebase
I'm trying to delete items from a Firebase database when user swipes to delete on the UITableView.

I'm also using the nifty showActivityIndicator and hideActivityIndicator functions from https://github.com/erangaeb/dev-notes/blob/master/swift/ViewControllerUtils.swift in order to easily show and hide the activity indicator.

I can see both the database record as well as the JPG file properly deleted from Firebase when the following code is run.

But the problem is that the activity indicator never disappears from the screen, and the UITableView does not refresh.

In fact, the

```<code>print("Stopping activity indicator")
</code>```

and

```<code>print("Reloading table view")
</code>```

do not even run.

What am I doing wrong?

```<code>func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let alert = UIAlertController(title: "Delete Task", message: "Do you want to delete this task?", preferredStyle: .alert)
            let confirmAction = UIAlertAction(title:"OK", style: .default) { action in
                // Show activity indicator
                ViewControllerUtils().showActivityIndicator(uiView: self.view)

                // Retrieve Firebase reference to delete
                let repairItem = self.repairItems[indexPath.row]
                let storage = Storage.storage()
                let storageRef = storage.reference()
                let imageRef = storageRef.child(repairItem.imageRef)

                // Delete the item from Firebase
                repairItem.ref?.removeValue(completionBlock: {(error, ref) in
                    if let error = error {
                        print("Problem deleting item")
                    } else {
                        print("Item deleted successfully")
                    }
                })

                // Delete the photo
                imageRef.delete { error in
                    if let error = error {
                        print("Problem deleting photo")
                    } else {
                        print("Photo deleted successfully")
                    }
                }

                print("Stopping activity indicator")
                // Stop the activity indicator
                ViewControllerUtils().hideActivityIndicator(uiView: self.view)

                print("Reloading table view")
                // Reloading table view
                self.tableView.reloadData()
            }

            let cancelAction = UIAlertAction(title: "Cancel", style: .default)

            alert.addAction(confirmAction)
            alert.addAction(cancelAction)

            present(alert, animated: true, completion: nil)
        }
    }
</code>```

答:
Still not sure why the code below the Firebase removeValue and delete functions aren't running, but I managed to figure out a workaround.

Turns out that the code doesn't work only when I'm deleting the last remaining record on the table, after which the entire Firebase node is removed.

So I've added an observer to forcefully reload the table when this happens.

Under viewDidLoad(), I added the following lines:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // ... other preceding lines of code

    // Forcefully trigger a TableView refresh in case the Firebase node is empty
    refItems.observe(.value, with: { snapshot in
        if snapshot.exists() {
            print("Found the Firebase node")
        } else {
            print("Firebase node doesn't exist")
            self.tableView.reloadData()
        }
    })

    // ...other following lines of code
}
</code>```

Body:
I'm trying to delete items from a Firebase database when user swipes to delete on the UITableView.

I'm also using the nifty showActivityIndicator and hideActivityIndicator functions from https://github.com/erangaeb/dev-notes/blob/master/swift/ViewControllerUtils.swift in order to easily show and hide the activity indicator.

I can see both the database record as well as the JPG file properly deleted from Firebase when the following code is run.

But the problem is that the activity indicator never disappears from the screen, and the UITableView does not refresh.

In fact, the

print("Stopping activity indicator")

and

print("Reloading table view")

do not even run.

What am I doing wrong?

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let alert = UIAlertController(title: "Delete Task", message: "Do you want to delete this task?", preferredStyle: .alert)
            let confirmAction = UIAlertAction(title:"OK", style: .default) { action in
                // Show activity indicator
                ViewControllerUtils().showActivityIndicator(uiView: self.view)

                // Retrieve Firebase reference to delete
                let repairItem = self.repairItems[indexPath.row]
                let storage = Storage.storage()
                let storageRef = storage.reference()
                let imageRef = storageRef.child(repairItem.imageRef)

                // Delete the item from Firebase
                repairItem.ref?.removeValue(completionBlock: {(error, ref) in
                    if let error = error {
                        print("Problem deleting item")
                    } else {
                        print("Item deleted successfully")
                    }
                })

                // Delete the photo
                imageRef.delete { error in
                    if let error = error {
                        print("Problem deleting photo")
                    } else {
                        print("Photo deleted successfully")
                    }
                }

                print("Stopping activity indicator")
                // Stop the activity indicator
                ViewControllerUtils().hideActivityIndicator(uiView: self.view)

                print("Reloading table view")
                // Reloading table view
                self.tableView.reloadData()
            }

            let cancelAction = UIAlertAction(title: "Cancel", style: .default)

            alert.addAction(confirmAction)
            alert.addAction(cancelAction)

            present(alert, animated: true, completion: nil)
        }
    }

Body:
Still not sure why the code below the Firebase removeValue and delete functions aren't running, but I managed to figure out a workaround.

Turns out that the code doesn't work only when I'm deleting the last remaining record on the table, after which the entire Firebase node is removed.

So I've added an observer to forcefully reload the table when this happens.

Under viewDidLoad(), I added the following lines:

override func viewDidLoad() {
    super.viewDidLoad()

    // ... other preceding lines of code

    // Forcefully trigger a TableView refresh in case the Firebase node is empty
    refItems.observe(.value, with: { snapshot in
        if snapshot.exists() {
            print("Found the Firebase node")
        } else {
            print("Firebase node doesn't exist")
            self.tableView.reloadData()
        }
    })

    // ...other following lines of code
}


问:
Random select value on array factory Laravel
I had user migration:

```<code>$table->enum('type',['seller','buyer'])->default('seller');
</code>```

I want when using ModelFactory how to get random value seller or buyer?

```<code>$factory->define(App\User::class, function (Faker\Generator $faker) {

    static $password;

    return [
        'firstName' => $faker->name,
        'lastName' => $faker->name,
        'username' => $faker->unique()->username,
        'email' => $faker->unique()->safeEmail,
        'password' => md5('user123'),
        'bio' => $faker->sentence(3, true),
        'type' => ???,
    ];
});
</code>```

答:
Make use of randomElement method

```<code>'type' => $faker->randomElement(['seller', 'buyer']),
</code>```

Body:
I had user migration:

$table->enum('type',['seller','buyer'])->default('seller');

I want when using ModelFactory how to get random value seller or buyer?

$factory->define(App\User::class, function (Faker\Generator $faker) {

    static $password;

    return [
        'firstName' => $faker->name,
        'lastName' => $faker->name,
        'username' => $faker->unique()->username,
        'email' => $faker->unique()->safeEmail,
        'password' => md5('user123'),
        'bio' => $faker->sentence(3, true),
        'type' => ???,
    ];
});

Body:
Make use of randomElement method

'type' => $faker->randomElement(['seller', 'buyer']),