text:
Q: Process data, calculate and create a new hash I need to convert the intermediate_hash to required_hash given below.
Reference Array
ref_arr = [{"ver"=>"3.2", "start"=>"2014/2/12", "end"=>"2014/2/20", "id"=>"345"}, {"ver"=>"3.3", "start"=>"2014/3/19", "end"=>"2014/4/3", "id"=>"233"}]

Intermediate Hash
intermediate_hash = {
   "ver": {
      "abc-xxxx": {
         "'Process Start Date'":  "2014/1/10",
         "'Ready Start Date'": "2014/1/12",
         "'Product'": "Lumia-720",
       },
      "adc-xxxx": {
         "'Process Start Date'":  "2014/2/15",
         "'Ready Start Date'": "2014/2/17",
         "'Product'": "iphone5",
       },
      "efg-xxxx": {
         "'Process Start Date'":  "2013/12/10",
         "'Ready Start Date'": "2013/12/12",
         "'Product'": "htc",
       },
      "ghi-xxxx": {
         "'Process Start Date'":  "2013/10/3",
         "'Ready Start Date'": "2013/10/7",
         "'Product'": "iphone5",
       },
      "jkl-xxxx": {
         "'Process Start Date'":  "2013/10/23",
         "'Ready Start Date'": "2013/10/24",
         "'Product'": "Lumia-720",
       },
      "mno-xxxx": {
         "'Process Start Date'":  "2013/11/3",
         "'Ready Start Date'": "2013/11/4",
         "'Product'": "iphone5",
       },
    ...
   }
}

Required Hash
result = {
"3.2": {
    "lumia-720": {
        "'Before process QA'": 2
        "'After process'": 0,
    },
   "iphone5": {
        "'Before process QA'": 2,
        "'After process'": 1,
    },
    "htc": {
        "'Before process QA'": 1
        "'After process'": 0,
    },
  },
"3.3":..
}

Rules for comparing
Before process: reference_hash[:start]<=intermediate_hash[:process_start_date]
After process: reference_hash[:start]>intermediate_hash[:process_start_date]
My approach till now:
First Step: I tried to group_by by product by using this code.
hash = JSON.parse(File.read('details.json'))
summary = {}
hash.map do |x|
 summary[x[0]] = {}
 summary[x[0]] = x[1].group_by{|x| x[1]['Product']}.each{|_, v| v.map!{|h| h[1]}}
end

So, i'm getting the final response as grouped by product. But i'm not able to understand how to effectively produce the intermediate_hash to required_hash.? As my attempt is going to multilevel iteration. Can someone please help me in this. ?
Thanks in advance


text:
Q: Unable to crate a Firestore Bean, BeanCreationException. java.lang.NoClassDefFoundError: com/google/api/gax/rpc/TransportChannelProvider I am working with Spring Boot and Spring Security, but is my first time using Google cloud firebase Firestore, I am connecting to my database via Firebase Admin SDK. I have a configuration class that looks like this.
@Configuration
public class FirestoreUserConfig {
    @Bean
    public Firestore getDB() {
        return FirestoreClient.getFirestore();
    }
}

I have  BeanCreationException, my stack trace, in summary, looks like this.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getDB' defined in class path resource [com/d1gaming/user/firebaseconfig/FirestoreUserConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.google.cloud.firestore.Firestore]: Factory method 'getDB' threw exception; nested exception is java.lang.NoClassDefFoundError: com/google/api/gax/rpc/TransportChannelProvider
Caused by: java.lang.ClassNotFoundException: com.google.api.gax.rpc.TransportChannelProvider
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_271]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418) ~[na:1.8.0_271]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355) ~[na:1.8.0_271]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351) ~[na:1.8.0_271]
    ... 105 common frames omitted

The weird thing is I followed Google's documentation on Initializing firebase Admin SDK, I added the corresponding dependencies to my pom.xml file but it does not seem to work anyway. This is my Admin SDK dependency.
<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>7.0.1</version>
</dependency>

I imagine Maven is not able to find this TransportChannelProvider class, Im not sure. I also tried adding all of gcp core dependencies in case provided Admin SDK dependency didn't have the class but I had the same result. I am also making use of a Service and a RESTController for my back end application, I don't know if it is relevant to include it here but I am going to include it just in case.
@Service
public class UserService {

    public final String USERS_COLLECTION = "users";

    @Autowired
    private PasswordEncoder passwordEncoder;

    private Firestore firestore;

    //get users collcetion from Firestore.
    private CollectionReference getUsersCollection() {
        return firestore.collection(this.USERS_COLLECTION);
    }

    //Post a user onto the user collection. documentID is auto-generated by firestore.
    public String saveUser(User user) throws InterruptedException, ExecutionException {
        Query query = getUsersCollection().whereEqualTo("userName", user.getUserName());
        QuerySnapshot querySnapshot = query.get().get();
        //Query to validate if userName is already in use.
        if(querySnapshot.isEmpty()) {
            ApiFuture<DocumentReference> document = getUsersCollection().add(user);
            DocumentReference reference = document.get();
            String userId = document.get().getId();
            //Assign auto-generated Id to userId field for ease of querying.
            WriteBatch batch = FirestoreClient.getFirestore().batch();
            batch.update(reference, "userId",userId);
            //ENCODE USER PASSWORD!
            batch.update(reference, "userPassword",passwordEncoder.encode(reference.get().get().toObject(User.class).getUserPassword()));
            List<WriteResult> results = batch.commit().get();
            results.forEach(result -> {
                System.out.println("Update Time: " + result.getUpdateTime());
            });
            return "Created user with ID: " + "'" + userId + "'";
        }
        return "Username is already in use";
    }

    //Get User by given its email.
    public Optional<User> getUserByEmail(String userEmail) throws InterruptedException, ExecutionException{
        Query query = getUsersCollection().whereEqualTo("userEmail", userEmail);
        QuerySnapshot snapshot = query.get().get();
        //if user with provided Email exists in collection.
        if(!snapshot.isEmpty()) {
            List<User> userLs = snapshot.toObjects(User.class);
            //Since there is a unique email for each document,
            //There will only be on User object on list, we will retrieve the first one.
            for(User currUser: userLs) {
                return Optional.of(currUser);
            }
        }
        return null;
    }

    //Query for user by given userName.
    public Optional<User> getUserByUserName(String userName) throws InterruptedException, ExecutionException{
        //Perform a query based on a user's Name.
        Query query = getUsersCollection().whereEqualTo("userName", userName);
        QuerySnapshot snapshot = query.get().get();
        if(!snapshot.isEmpty()) {
            List<User> userList = snapshot.toObjects(User.class);
            //Since there is a unique userName for each document,
            //there will only be one User object on the list, we will retrieve the first one.
            for(User currUser: userList) {
                return Optional.of(currUser);
            }
        }
        return null;
    }

    //Query for user by given userName.
    public User getUserByName(String userName) throws InterruptedException, ExecutionException {
        //Perform a query based on a user's Name.
        Query query = getUsersCollection().whereEqualTo("userName", userName);
        QuerySnapshot snapshot = query.get().get();
        if(!snapshot.isEmpty()) {
            List<User> userList = snapshot.toObjects(User.class);
            //Since there is a unique userName for each document,
            //there will only be one User object on the list, we will retrieve the first one.
            for(User currUser : userList) {
                return currUser;
            }
        }
        return null;
    }

    //Get User by its auto-generated ID.
    public User getUserById(String userId) throws InterruptedException, ExecutionException {
        DocumentReference reference = getUsersCollection().document(userId);
        if(reference.get().get().exists()) {
            DocumentSnapshot snapshot = reference.get().get();
            User user = snapshot.toObject(User.class);
            return user;
        }
        return null;
    }

    //Get DocumentReference on a User.
    public DocumentReference getUserReference(String userId) throws InterruptedException, ExecutionException {
        DocumentReference reference = getUsersCollection().document(userId);
        //Evaluate if documentExists in users collection.
        if(reference.get().get().exists()) {
            return reference;
        }
        return null;
    }

    //return a list of objects located in the users collection.
    public List<User> getAllUsers() throws InterruptedException, ExecutionException {
        //asynchronously retrieve all documents
        ApiFuture<QuerySnapshot> future = getUsersCollection().get();
        List<QueryDocumentSnapshot> objects = future.get().getDocuments();
        //If there is no documents, return null.
        if(!objects.isEmpty()) {
            List<User> ls = new ArrayList<>();
            objects.forEach((obj) -> {
                User currUser = obj.toObject(User.class);
                ls.add(currUser);
            });
            return ls;
        }
        return null;
    }

    //delete a User from users collection by a given id.
    //In reality delete method just changes UserStatus from active to inactive or banned.
    public String deleteUserById(String userId) throws InterruptedException, ExecutionException {
        Firestore db = FirestoreClient.getFirestore();
        DocumentReference reference = db.collection(USERS_COLLECTION).document(userId);
        User user = reference.get().get().toObject(User.class);
        if(user == null) {
            return "User not found.";
        }
        WriteBatch batch = db.batch();
        batch.update(reference, "userStatusCode",UserStatus.INACTIVE);
        ApiFuture<List<WriteResult>> result = batch.commit();
        List<WriteResult> results = result.get();
        results.forEach(response -> {
            System.out.println("Update Time:" + response.getUpdateTime());
        });
        //Check if user did actually change status.
        if(reference.get().get().toObject(User.class).getStatusCode().equals(UserStatus.ACTIVE)) {
            return "User with ID: " + "'" +  userId + "'" + " was deleted.";
        }
        return "User could not be deleted";
    }

    //Delete a User's certain field value.
    public String deleteUserField(String userId, String userField) throws InterruptedException, ExecutionException {
        Firestore firestore = FirestoreClient.getFirestore();
        DocumentReference reference = getUsersCollection().document(userId);
        if(!reference.get().get().exists()) {
            return "User not found.";
        }
        Map<String,Object> map = new HashMap<>();
        map.put(userField, FieldValue.delete());
        WriteBatch batch = firestore.batch();
        batch.update(reference, map);
        List<WriteResult> results = batch.commit().get();
        results.forEach(response -> System.out.println("Update Time: " + response.getUpdateTime()));
        return "Field deleted Successfully";
    }

    //Change UserStatus to BANNED
    public String banUserById(String userId) throws InterruptedException, ExecutionException {
        Firestore db = FirestoreClient.getFirestore();
        final DocumentReference reference = db.collection(this.USERS_COLLECTION).document(userId);
        WriteBatch batch = db.batch().update(reference,"userStatusCode",UserStatus.BANNED);
        List<WriteResult> results = batch.commit().get();
        results.forEach(response -> System.out.println("Update Time: " + response.getUpdateTime()));
        if(reference.get().get().toObject(User.class).getStatusCode().equals(UserStatus.BANNED)) {
            return "User with ID: " + "'" + userId + "'"  + " was BANNED.";
        }
        return "User could not be BANNED.";
    }

    //Set a user with all new fields.
    public String updateUser(User user) throws InterruptedException, ExecutionException {
        Firestore firestore = FirestoreClient.getFirestore();
        final DocumentReference reference = getUsersCollection().document(user.getUserId());
        DocumentSnapshot snapshot = reference.get().get();
        if(snapshot.exists()) {
            WriteBatch batch = firestore.batch();
            batch.set(reference, user);
            List<WriteResult> results = batch.commit().get();
            results.forEach(response -> System.out.println("Update time: " + response.getUpdateTime()));
            return "User updated successfully";
        }
        return "User not found.";
    }

    // Update a specific field on a given document by another given value. In case userId is field to be changed, one integer will be subtracted from userTokens field.
    public String updateUserField(String userId,String objectField, String replaceValue) throws InterruptedException, ExecutionException {
        Firestore db = FirestoreClient.getFirestore();
        final DocumentReference reference = getUsersCollection().document(userId);
        if(!reference.get().get().exists()) {
            return "User not found.";
        }
        WriteBatch batch = db.batch();
        List<WriteResult> results = new ArrayList<>();
        //These fields cannot be updated.
        if(!objectField.equals("userName") && !objectField.equals("userCash") && !objectField.equals("userTokens") && !objectField.equals("userId")) {
            batch.update(reference, objectField, replaceValue);
            results = batch.commit().get();
            results.forEach(response ->{
                System.out.println("Update time: " + response.getUpdateTime());
            });
        }
        else if(objectField.equals("userName")) {
            String response = updateUserName(userId, replaceValue);
            return response;
        }
        else {
            return "This field canntot be updated.";
        }
        return "User field could not be updated.";
    }

    //Update a user's userName depending of availability and token adquisition capacity. i.e. if user has enough tokens to pay fee.
    public String updateUserName(String userId, String newUserName) throws InterruptedException, ExecutionException {
        Firestore db = FirestoreClient.getFirestore();
        final DocumentReference reference = getUsersCollection().document(userId);
        DocumentSnapshot snapshot = reference.get().get();
        if(!snapshot.exists()) {
            return "User not found.";
        }
        Query query = getUsersCollection().whereEqualTo("userName", newUserName);
        QuerySnapshot querySnapshot = query.get().get();
        //Evaluate if userName is already in use.
        String response = "Username is already taken";
        if(querySnapshot.isEmpty()) {
                //Transaction to get() tokens and update() tokens.
                ApiFuture<String> futureTransact = db.runTransaction(transaction -> {
                    DocumentSnapshot doc = transaction.get(reference).get();
                    double tokens = doc.getDouble("userTokens");
                    //evaluate if user holds more than one token
                    if(tokens >= 1) {
                        transaction.update(reference, "userTokens", tokens - 1);
                        transaction.update(reference, "userName", newUserName);
                        return "Username updated to: '"+ newUserName +"'";
                    }
                    else {
                        throw new Exception("Not enough Tokens");
                    }
                });
                response = futureTransact.get();
        }
        return response;
    }

    //update user Currency field.
    public String updateUserCash(String userId, double cashQuantity) throws InterruptedException, ExecutionException {
        Firestore firestore = FirestoreClient.getFirestore();
        final DocumentReference reference = getUsersCollection().document(userId);
        DocumentSnapshot snapshot = reference.get().get();
        String response = "User not found.";
        //evaluate if document exists
        if(snapshot.exists()) {
            ApiFuture<String> futureTransaction = firestore.runTransaction(transaction -> {
                Map<String,Object> map = new HashMap<>();
                map.put("userCash", FieldValue.increment(cashQuantity));
                transaction.update(reference, map);
                return "Updated userCash";
            });
            response = futureTransaction.get();
            return response;
        }
        return response;
    }

    //Update user Token field.
    public String updateUserTokens(String userId, double tokenQuantity) throws InterruptedException, ExecutionException {
        Firestore firestore = FirestoreClient.getFirestore();
        final DocumentReference reference = getUsersCollection().document(userId);
        String response = "User not found.";
        //evaluate if user exists on collection.
        if(reference.get().get().exists()) {
            ApiFuture<String> futureTransaction = firestore.runTransaction(transaction -> {
                Map<String,Object> map = new HashMap<>();
                map.put("userTokens",tokenQuantity);
                transaction.update(reference, map);
                return "Updated userTokens";
            });
            response = futureTransaction.get();
            return response;
        }
        return response;
    }

    //evaluate if given documentId exists on given collection.
    public static boolean isPresent(String userId,String collectionName) throws InterruptedException, ExecutionException {
        Firestore db = FirestoreClient.getFirestore();
        DocumentReference reference = db.collection(collectionName).document(userId);
        ApiFuture<DocumentSnapshot> snapshot = reference.get();
        DocumentSnapshot document = snapshot.get();
        if(!document.exists()) {
            return false;
        }
        return true;
    }

    //Evaluate if given document's status corresponds to active.
    public static boolean isActive(String userId, String collectionName) throws InterruptedException, ExecutionException {
        Firestore db = FirestoreClient.getFirestore();
        DocumentReference reference = db.collection(collectionName).document(userId);
        ApiFuture<DocumentSnapshot> snapshot = reference.get();
        DocumentSnapshot result = snapshot.get();
        User user = result.toObject(User.class);
        if(user.getStatusCode().equals(UserStatus.ACTIVE)) {
            return true;
        }
        return false;
    }

}

My Controller class:
@RestController
@RequestMapping("/userapi")
@CrossOrigin(origins = "http://localhost:4200")
public class UserController {

    @Autowired
    UserService userServ;

    @GetMapping(value = "/users/search",params="userName")
    @PreAuthorize("hasRole('PLAYER')")
    public ResponseEntity<Object> getUserByName(@RequestParam(value = "userName", required = true)final String userName) throws InterruptedException, ExecutionException{
        if(userName == null) {
            return new ResponseEntity<>("Invalid Input",HttpStatus.BAD_REQUEST);
        }
        User user = userServ.getUserByName(userName);
        if(user == null) {
            return new ResponseEntity<>("User Not Found", HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(user,HttpStatus.OK);
    }

    @GetMapping("/users")
    @PreAuthorize("hasRole('PLAYER')")
    public ResponseEntity<List<User>> getAllUsers() throws InterruptedException, ExecutionException{
        List<User> ls = userServ.getAllUsers();
        if(ls.isEmpty()) {
            return new ResponseEntity<List<User>>(ls, HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<User>>(ls, HttpStatus.OK);
    }

    @DeleteMapping(value = "/users/delete",params="userId")
    @PreAuthorize("hasRole('ADMINISTRATOR')")
    public ResponseEntity<Object> deleteUserById(@RequestParam(value="userId", required = true)String userId, @RequestParam(required = false, value="userField") String userField) throws InterruptedException, ExecutionException{
        if(userField != null) {
            String response = userServ.deleteUserField(userId, userField);
            if(response.equals("User not found.")) {
                return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity<>(response, HttpStatus.OK);
        }
        String response = userServ.deleteUserById(userId);
        if(response.equals("User not found.")) {
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    @PutMapping(value = "/users/update")
    @PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('PLAYER')")
    public ResponseEntity<Object> updateUser(@RequestBody User user) throws InterruptedException, ExecutionException{
        String response = userServ.updateUser(user);
        if(response.equals("User not found.")) {
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    @PutMapping(value = "/users/update",params="userId")
    @PreAuthorize("hasRole('ADMINISTRATOR') or hasRole('PLAYER')")
    public ResponseEntity<Object> updateUserField(@RequestParam(required = true, value="userId")String userId, @RequestParam(required = true)String userField, @RequestParam(required = true)String replaceValue) throws InterruptedException, ExecutionException{
        String response = userServ.updateUserField(userId, userField, replaceValue);
        if(response.equals("User not found.")) {
            return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
        }
        else if(response.equals("This field cannot be updated.")) {
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>(response, HttpStatus.OK);
    }
}

I didn't find ANY documentation on this particular problem and that is why I am here, I would be glad if anyone could help me solving this problem. Am I missing something? Anyways thank you for your time, happy coding.

A: as you said, you are missing the TransportChannelProvider interface and it's implementations. it's not provided in the dependency you added.
try to add this dependency to your POM:
<dependency>
    <groupId>com.google.api</groupId>
    <artifactId>gax</artifactId>
    <version>1.57.0</version>
</dependency>

the interface included there.

A: After checking my pom.xml and my dependency hierarchies(On Eclipse, found on the toolbar above the console when the pom.xml file is being viewed.), I found I had another dependency on another Spring Boot project that was overriding the one I had on my project, make sure to check all dependencies on different projects as well. The dependency version I had on my other project did not include the classes Spring needed to create a a bean.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Error: Forbidden" http console trigger doesn't work even though I am the project owner I deployed a Cloud Function but when I manually click on the Trigger URL in the console trigger I get this error:

Error: Forbidden Your client does not have permission to get URL /entry-point from this server.

I don't understand why am I getting this because I am the project owner and I even added the cloudfunctions.invoker role to my user account. A comment from this post confirms that it should work.
Does anyone has an idea on how to fix this issue?

A: So apparently, the cause of the issue is that I didn't allow unauthenticated, and this is the only way to use the control trigger.
This link shows how to change this setting.


text:
Q: Inference can be the goal of an unsupervised learning method or a semi-supervised learning method or even more of a reinforcement learning method? I am new to machine learning, and I am reading a pair of machine learning books. These references talk about 2 different learning approaches: Prediction and inference, I understand the difference between both of them in supervised learning. Nevertheless, I do not know if inference can be the goal of unsupervised learning algorithms. Whether the answer is yes or not, can you please explain me a bit more about the answer and give me examples?
Many thanks for your time and considerations.

A: I will say, the inference is the de facto goal of a clustering method. Reason being, clustering essentially means grouping the features based on a certain characteristic or pattern. Since the target label is absent in a clustering problem, it is the inference that helps the analyst decide or determine the possible label for the clustered group. This label thereafter can be used for any prediction task.


text:
Q: How to prove that a function is left continuous I cannot work out this problem even though it seems not that difficult. Could anyone kindly give me any hint? Thanks!
If $f(x)$ is measurable on $E \subset \mathbb R$, then
$$
\varphi (t)=m\big(\{x \in E : f(x) \lt t\}\big)
$$
is a left continuous function on $\mathbb R$.
I first picked a sequence $\{t_n\}$ converging to $t$.
But I cannot prove that
$$
\lim_{t_n \nearrow t} \,m\big(\{x \in E : f(x) \lt t_n\}\big)=m\big(\{x \in E : f(x) \lt t\}\big).
$$

A: For any $t$, let $S_t:=\{x\in E|f(x)<t\}$, and note that whenever $(t_n)_{n=1}^\infty$ is an increasing sequence that converges to $t$ we have $S_t=\bigcup_nS_{t_n}$, thus $$m(S_t)=m\left(\bigcup_nS_{t_n}\right)=\lim_{n\to\infty}m(S_{t_n}),$$and left continuity follows.

A: $g$ is left continuous at $t_0$ means: If $t_n\to t_0$ and $t_n<t_0$, then $g(t_n)\to g(t_0)$. In fact, we can assume that $\{t_n\}$ is strictly increasing.
In our case,
$$
\{x\in E: f(x)<t_0\}=\{x\in E: f(x)<t_1\}\cup\{x\in E: t_1\le f(x)<t_2\}\cup\cdots\cup
\{x\in E: t_n\le f(x)<t_{n+1}\}\cup\cdots=\{x\in E: f(x)<t_1\}\cup\bigcup_{n=1}^\infty
\{x\in E: t_n\le f(x)<t_{n+1}\}
$$
and all the sets
$$
\{x\in E: f(x)<t_1\},\,
\{x\in E: t_n\le f(x)<t_{n+1}\}, \quad n\in\mathbb N,
$$
are measurable and disjoint. Thus
$$
g(t_0)=m\left(\{x\in E: f(x)<t_0\}\right)=m\left(\{x\in E: f(x)<t_1\}\right)
+\sum_{n=1}^\infty m\left(\{x\in E: t_n \le f(x)<t_{n+1}\}\right) \\
=m\left(\{x\in E: f(x)<t_1\}\right)
+\lim_{n\to\infty}\sum_{k=1}^n m\left(\{x\in E: t_k\le f(x)<t_{k+1}\}\right)=\lim_{n\to\infty}
m\left(\{x\in E: f(x)<t_{n+1}\}\right)=\lim_{n\in\infty} g(t_{n+1}).
$$


text:
Q: select four item per category mysql My schema has the following tables
 product table

productid name

category table

categoryid name parentid

category_product table

categoryid productid

I want to retrieve four record from top categories i.e. immediate child of root category.
I had run following  query but it returns all product.
select
    `pp`.`productid`, count(`pp`.`productid`)
from
    `product` `pp`
        join
    `category_product` `pc` ON `pp`.`productid` = `pc`.`poduct_id`
        join
    `category` `cp` ON `pc`.`category_id` = `cp`.`categoryid`
where
    `cp`.`parent_id` = 1
group by `pp`.`productid`
having count(`pp`.`productid`) < 4 ;


text:
Q: Angle arising from circle rolling along an ellipse
In this problem the ellipse and circle are fixed. The ellipse has center $E$ on the origin, its semi-minor axis $r$ is on the $y$-axis, and its semi-major axis $R$ is on the $x$-axis. The circle has center $O$ and radius $c$. The circle and the ellipse intersect at point $P$.
Given $E, O, R, r$, and $c$, is it possible to determine $\angle z=\angle EOP$?
When $P$ lies on the $x$ or $y$-axis, the angle is $0$. But when it lies anywhere else, as in the picture, I'm stumped as to how to easily calculate $z$.
Thank you.

A: The problem posed is algebraically intractable.
If instead of O you know $P$, then you can find the angle after extending line OP to meet the major axis at $F$.
Label the intersection on the right of the ellipse with its major axis $G$.  Let
$\angle GFO$ be $\alpha$ and $\angle GEO$ be $\beta$; then if we can determine $\alpha$ and $\beta$,  $\angle z = \alpha - \beta$.
But if the projections of $EP$ along the major and minor axes are $(x,y)$ respectively, then
$$
\tan \alpha = \frac{yR^2}{xr^2}
$$
and
$$
\tan \beta = \frac{y+c\sin\alpha}{x+c \cos \alpha}
$$
Take the respective arctangents and subtract.
For the problem posed, you have $O$ so $\beta$ is trivially $\tan^{-1}\frac{y_0}{x_0}$, but to get $\alpha$ you would need to solve for $x, y, \alpha$ in
the equations
$$
\left\{
\begin{array}{c}
\tan \alpha = \frac{yR^2}{xr^2} \\
x + c \cos \alpha = x_0 \\
y + c \sin \alpha = y_0
\end{array}
\right.
$$
You can use trig identities to eliminate $\alpha$ and solve the last equation for $y$ in terms of $x$, but the remaining equation involves square roots of two expressions, one of which has $(x-x_0)^2$ in a denominator, and when you group and square twice you end out with an 8-th degree equation which is much too tough to solve.

A: Given the data, can you not determine P as the point of intersection of the circle and the ellipse? Then, you can use the method by @MarkFischler.


text:
Q: Caption within a figure? I have an image

where as x are 3 diagrams. As there is empty space on the left, I was wondering if it is possible to put the caption of the image within the picture.

A: This is a solution which does not assume any package besides graphicx for including the images. The $ around the last figure is to ensure the vertical centering of the caption.
\documentclass{article}
\usepackage{graphicx}
\usepackage{mwe}
\def\image{\includegraphics[width=0.45\textwidth]{example-image-a}}

\begin{document}
\begin{figure}
\image\hfill\image\par
\vskip 5mm
\begin{minipage}[c]{0.45\textwidth}
\caption{This is the caption, it may be long}
\end{minipage}\hfill%
$\vcenter{\hbox{\image}}$\par
\end{figure}
\end{document}


text:
Q: Makefile: add flags after -o I am trying to compile Indri 5.9 (downloaded from http://sourceforge.net/projects/lemur/) on Ubuntu 14.04 LTS using VirtualBox, but after "env CPP=/usr/bin/cpp CXX=/usr/bin/g++ ./configure" and when I "make", I got a problem: ator.cpp:216:undefined reference to 'gzopen'. I already installed zlib1g0dev by "sudo apt-get install zlib1g-dev", and according to Compilation problems with ZLIB it seems I have to add "-lz" at the end of "-o". However, this is my Makefile:
-include MakeDefns

INSTALLDIRS = $(bindir) $(includedir) $(pkgincludedir) $(includedir)/lemur $(libdir) $(pkgdatadir) $(pkgdatadir)/doc

.PHONY: all dist clean install $(INSTALLDIRS) site-search

all:
    $(MAKE) -C contrib
    $(MAKE) -C obj -f ../src/Makefile
ifeq ($(WITH_SWIG), 1)
    $(MAKE) -C swig/src
endif
    $(MAKE) -C buildindex
    $(MAKE) -C runquery
    $(MAKE) -C indrid
    $(MAKE) -C dumpindex
    $(MAKE) -C harvestlinks
    $(MAKE) -C pagerank
    $(MAKE) -C rmodel
    $(MAKE) -C makeprior
    $(MAKE) -C site-search
    $(MAKE) -C modifyfields
    $(MAKE) -C clarity
    $(MAKE) -C reformulate

$(INSTALLDIRS):
    $(INSTALL_DIR) $@

clean:
    $(MAKE) clean -C contrib
    $(MAKE) clean -C obj -f ../src/Makefile
ifeq ($(WITH_SWIG), 1)
    $(MAKE) clean -C swig/src
endif
    $(MAKE) clean -C buildindex
    $(MAKE) clean -C runquery
    $(MAKE) clean -C indrid
    $(MAKE) clean -C dumpindex
    $(MAKE) clean -C harvestlinks
    $(MAKE) clean -C pagerank
    $(MAKE) clean -C rmodel
    $(MAKE) clean -C makeprior
    $(MAKE) -C site-search clean
    $(MAKE) -C modifyfields clean
    $(MAKE) -C clarity clean
    $(MAKE) -C reformulate clean
    rm -f depend/*

distclean: clean
    rm -rf autom4te.cache MakeDefns Makefile.app config.log config.status indri.ncb indri.suo
dist: distclean
    $(MAKE) stamp -C obj -f ../src/Makefile
    cd ..; tar zcvf indri-`date +%Y%m%d-%H%M`.tar.gz indri

install: $(INSTALLDIRS)
    rm -f $(libdir)/$(INDRILIB)
    $(MAKE) install -C contrib
    $(MAKE) install -C obj -f ../src/Makefile
ifeq ($(WITH_SWIG), 1)
    $(MAKE) install -C swig/src
endif
    $(MAKE) install -C buildindex
    $(MAKE) install -C runquery
    $(MAKE) install -C indrid
    $(MAKE) install -C dumpindex
    $(MAKE) install -C harvestlinks
    $(MAKE) install -C pagerank
    $(MAKE) install -C rmodel
    $(MAKE) install -C makeprior
    $(MAKE) install -C modifyfields
    $(MAKE) install -C clarity
    $(MAKE) install -C reformulate
    $(MAKE) install -C doc
    $(MAKE) -C site-search install
    $(INSTALL_DATA) Makefile.app $(pkgdatadir)

test:

And this is MakeDefns:
SHELL = /bin/bash
host_os = linux-gnu
srcdir = .
top_srcdir = .

prefix = /usr/local
exec_prefix = ${prefix}
bindir = ${exec_prefix}/bin
sbindir = ${exec_prefix}/sbin
libexecdir = ${exec_prefix}/libexec
datadir = ${datarootdir}
sysconfdir = ${prefix}/etc
sharedstatedir = ${prefix}/com
localstatedir = ${prefix}/var
libdir = ${exec_prefix}/lib
infodir = ${datarootdir}/info
mandir = ${datarootdir}/man
includedir = ${prefix}/include
datarootdir = ${prefix}/share
oldincludedir = /usr/include
pkgdatadir = $(datadir)/indri
pkglibdir = $(libdir)/indri
pkgincludedir = $(includedir)/indri
top_builddir = .

AR = /usr/bin/ar
CC = gcc
GCC_33 = 0
CXX = /usr/bin/g++
LEX = :
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_DIR = ${INSTALL} -m 755 -d
JAVAC =
JAR =
JAVAINC =
JAVADOC =
JAVAHOME =
NEED_ANTLR = 1
SWIG =
PHP_SHARED = -shared
JAVA_SHARED = -shared
CSHARP_SHARED = -shared
PHP_SO = .so
JAVA_SO = .so
CSHARP_SO = .so
PHPINCLUDE =
MCS=

DEPENDENCIES = lemur xpdf
ifeq ($(NEED_ANTLR), 1)
  DEPENDENCIES += antlr
endif

PACKAGE = indri
VERSION = 5.8
distdir = $(PACKAGE)-$(VERSION)
top_distdir = $(distdir)

INDRI_STANDALONE = 1
INDRILIB = lib$(PACKAGE).a

WITH_SWIG = 0
WITH_JAVA = 0
WITH_PHP = 0
WITH_CSHARP = 0

# C++ source files
CPPSRC1 = $(notdir $(wildcard ../src/*.cpp))
CPPSRC2 = $(notdir $(wildcard ../src/*.cc))
CPPSRC3 = $(notdir $(wildcard ../src/*.C))
# C source files
CSRC =  $(notdir $(wildcard ../src/*.c))
# flex source files
FSRC =  $(notdir $(wildcard ../src/*.l))
# Flex objects
FCPP = $(filter-out $(CPPSRC1), $(FSRC:.l=.cpp))
CPPSRC = $(CPPSRC1) $(CPPSRC3) $(CPPSRC3) $(FCPP)
.SECONDARY: $($(wildcard ../src/*.l).l=.cpp)
# All header files
ALLHEADER = $(wildcard ../include/indri/*.h*)
# Include path
INCPATH = -I../include $(patsubst %, -I../contrib/%/include, $(DEPENDENCIES))
ALLINCPATH = $(INCPATH)

# C++ objects
CPPOBJ = $(CPPSRC:.cpp=.o) $(CPPSRC2:.cc=.o) $(CPPSRC3:.C=.o)

# C objects
COBJ = $(CSRC:.c=.o)
# all objects
OBJ = $(CPPOBJ) $(COBJ)

# application makefiles should set SHARED=
# (see buildindex/Makefile
SHARED = -shared -fPIC

# C compiler and compiling options
# C++ compiler and compiling/linking options
CFLAGS = -DPACKAGE_NAME=\"Indri\" -DPACKAGE_TARNAME=\"indri\" -DPACKAGE_VERSION=\"5.8\" -DPACKAGE_STRING=\"Indri\ 5.8\" -DPACKAGE_BUGREPORT=\"project@lemurproject.org\" -DINDRI_STANDALONE=1 -DHAVE_LIBM=1 -DHAVE_LIBPTHREAD=1 -DHAVE_NAMESPACES=/\*\*/ -DISNAN_IN_NAMESPACE_STD=/\*\*/ -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_FSEEKO=1 -DHAVE_EXT_ATOMICITY_H=1 -DP_NEEDS_GNU_CXX_NAMESPACE=1 -DHAVE_MKSTEMP=1 -DHAVE_MKSTEMPS=1 -DNDEBUG=1  -g -O3 $(INCPATH) $(SHARED)
CXXFLAGS    = -DPACKAGE_NAME=\"Indri\" -DPACKAGE_TARNAME=\"indri\" -DPACKAGE_VERSION=\"5.8\" -DPACKAGE_STRING=\"Indri\ 5.8\" -DPACKAGE_BUGREPORT=\"project@lemurproject.org\" -DINDRI_STANDALONE=1 -DHAVE_LIBM=1 -DHAVE_LIBPTHREAD=1 -DHAVE_NAMESPACES=/\*\*/ -DISNAN_IN_NAMESPACE_STD=/\*\*/ -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_FSEEKO=1 -DHAVE_EXT_ATOMICITY_H=1 -DP_NEEDS_GNU_CXX_NAMESPACE=1 -DHAVE_MKSTEMP=1 -DHAVE_MKSTEMPS=1 -DNDEBUG=1  -g -O3 $(INCPATH) $(SHARED)
CXXFLAGS_NOOPT    = -DPACKAGE_NAME=\"Indri\" -DPACKAGE_TARNAME=\"indri\" -DPACKAGE_VERSION=\"5.8\" -DPACKAGE_STRING=\"Indri\ 5.8\" -DPACKAGE_BUGREPORT=\"project@lemurproject.org\" -DINDRI_STANDALONE=1 -DHAVE_LIBM=1 -DHAVE_LIBPTHREAD=1 -DHAVE_NAMESPACES=/\*\*/ -DISNAN_IN_NAMESPACE_STD=/\*\*/ -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_FSEEKO=1 -DHAVE_EXT_ATOMICITY_H=1 -DP_NEEDS_GNU_CXX_NAMESPACE=1 -DHAVE_MKSTEMP=1 -DHAVE_MKSTEMPS=1 -DNDEBUG=1  -g $(INCPATH) $(SHARED)
CPPLDFLAGS  =  -lpthread -lm

ifeq ($(STYLE),release)
     CFLAGS = -DPACKAGE_NAME=\"Indri\" -DPACKAGE_TARNAME=\"indri\" -DPACKAGE_VERSION=\"5.8\" -DPACKAGE_STRING=\"Indri\ 5.8\" -DPACKAGE_BUGREPORT=\"project@lemurproject.org\" -DINDRI_STANDALONE=1 -DHAVE_LIBM=1 -DHAVE_LIBPTHREAD=1 -DHAVE_NAMESPACES=/\*\*/ -DISNAN_IN_NAMESPACE_STD=/\*\*/ -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_FSEEKO=1 -DHAVE_EXT_ATOMICITY_H=1 -DP_NEEDS_GNU_CXX_NAMESPACE=1 -DHAVE_MKSTEMP=1 -DHAVE_MKSTEMPS=1 -DNDEBUG=1 -DNDEBUG  -g -O3 $(INCPATH) $(SHARED)
     CXXFLAGS    = -DPACKAGE_NAME=\"Indri\" -DPACKAGE_TARNAME=\"indri\" -DPACKAGE_VERSION=\"5.8\" -DPACKAGE_STRING=\"Indri\ 5.8\" -DPACKAGE_BUGREPORT=\"project@lemurproject.org\" -DINDRI_STANDALONE=1 -DHAVE_LIBM=1 -DHAVE_LIBPTHREAD=1 -DHAVE_NAMESPACES=/\*\*/ -DISNAN_IN_NAMESPACE_STD=/\*\*/ -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_FSEEKO=1 -DHAVE_EXT_ATOMICITY_H=1 -DP_NEEDS_GNU_CXX_NAMESPACE=1 -DHAVE_MKSTEMP=1 -DHAVE_MKSTEMPS=1 -DNDEBUG=1 -DNDEBUG  -g -O3 $(INCPATH) $(SHARED)
     CPPLDFLAGS  =  -lpthread -lm
endif

ifeq ($(STYLE),profile)
    CFLAGS=-g -pg  $(INCPATH)
    CXXFLAGS=-g -pg  $(INCPATH)
endif

# generating C++ with flex
../src/%.cpp: ../src/%.l
    $(LEX) -8 -Cf -o$@ $<

I am new to Makefile, so could anyone help me on how to add "-lz" to it? Or any other suggestions for compiling Indri 5.9. Thanks a lot!


text:
Q: How do I add a transformed variable to a Dataframe with other variables in Python? I'm new to pandas and sometimes things can be confusing to me. so I have a column in a Dataframe(df) column name is 'Black or African American' that I converted from string percent to float but now I want to add the converted variable back to a Dataframe or create a new Dataframe that has those variables from before.how do I go about that? please help out this is error message ':1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead'
black = race_df['Black or African American'].str.rstrip('%').astype(float) / 100
black.head(5)

0    0.264
1    0.031
2    0.041
3    0.153
4    0.055
Name: Black or African American, dtype: float64

race_df['Black or African American'] = race_df['Black or African  American'].str.rstrip('%').astype(float) / 100

I've tried the above code and I'm still getting errors


text:
Q: How to add or insert ' (single quotes) for every string in a list in which strings are separated by commas using Java I have a list as below
[url1,url2,url3,url4]

This list will be based on multiple selection from drop down list of HTML. So list size i.e., list elements change dynamically. My problem is I am unable to get the logic for getting single quotes to the strings.
I want the above string list to be displayed as
'url1','url2','url3','url4'

That is single quotes (') for each string and commas (,) should not be eliminated. Please help me how to achieve this using Java.

A: *

*Iterate the list (for/while).

*For each element in the list append <element-of-list>. Hint: use append() on StringBuilder.

*Truncate/substring the list to remove the last element added. Hint: use substring on String class.

A: Most fast and efficient way to do this
Ex.
ArrayList<String> a=[url1,url2,url3,url4];

String s  ="'"+a.toString().replace("[","").replace("]", "").replace(" ","").replace(",","','")+"'";

A: Have one Util.java file or if you already have all common util stuff then just add these static methods

for single quote

public static String singleQuote(String str) {
        return (str != null ? "'" + str + "'" : null);
}

for double quotes

public static String doubleQuotes(String str) {
        return (str != null ? "\"" + str + "\"" : null);
}

A: for list  you can convert this by Java 8
 list.stream().collect(Collectors.joining("','", "'", "'"));

A: If you have your elements in an array, you can do something like this:
import java.util.ArrayList;

class Test1{
    public static void main(String[] args) {
        String[] s = {"url1","url2","url3","url4"};

        ArrayList<String> sl = new ArrayList<String>();
        for (int i = 0; i < s.length; i++) {
            sl.add("'" + s[i] + "'");
        }
    }
}

A: import org.apache.commons.lang.StringUtils;
...
...
String arr[] = new String[4];
arr[0] = "my";
arr[1] = "name";
arr[2] = "is";
arr[3] = "baybora";

String join = "'" + StringUtils.join(arr,"','") + "'";

Result:
'my','name','is','baybora'

A: You can use Java 8 utility class java.util.StringJoiner.
This class specifically introduced to format list of string values.
For example:
StringJoiner joiner = new StringJoiner("','", "'", "'");
        joiner.add("url1");
        joiner.add("url2");
        joiner.add("url3");
        joiner.add("url4");
        System.out.println(joiner);

Output
'url1','url2','url3','url4'

Note that, in constructor of StringJoiner,
StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

we are passing single quote as prefix and suffix to satisfy your specific requirement.

A: Using Java 8 Streams:
String[] array = {"url1", "url2", "url3", "url4"}

Stream.of(array).collect(Collectors.joining("','", "'", "'"));

A: Try this
    String[] str = {"url1","url2","url3","url4"};
    ArrayList<String> strList = new ArrayList<String>();
    for (String k:str)
        strList.add("'" +k+ "'");
    System.out.println("Printing the list");
    for(String k:strList)
        System.out.println(k);

A: Also you can use Java8 built-in features for String concatenation and third-party libraries for wrapping each string in quotes.
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

@RunWith(MockitoJUnitRunner.class)
public class StringJoinerTest {
    @Test
    public void testStringJoiner() {

        //init test data
        String s1 = "team1";
        String s2 = "team2";
        List<String> teams = new ArrayList<>(2);
        teams.add(s1);
        teams.add(s2);

        //configure StringJoiner
        //when some values will be added to joiner it will return string started with prefix "(" an finished with suffix ")"
        //between prefix and suffix values will be separated with delimiter ", "
        StringJoiner teamNames = new StringJoiner(", ", "(", ")");
        //if nothing has been added to the joiner it will return  this value ('')
        teamNames.setEmptyValue("(\'\')");

        //fill joiner with data
        for (String currentString : teams) {
            //if you need to wrap each string in single quotes you can do this via org.apache.commons.lang3.StringUtils#wrap
            // or org.springframework.util.StringUtils#quote
            teamNames.add(StringUtils.quote(currentString));
        }

        System.out.println(teamNames.toString());
    }
}


text:
Q: Как протестировать метод с имитацией ввода пользователем? import java.util.Scanner;

public class Input {
    private Scanner scanner;

    public Input(Scanner scanner) {
        this.scanner = scanner;
    }

    public int IputData(){
        int res = scanner.nextInt();
        return res*2;
    }
}

пробовал протестовать с помощью Mockito но выдает ошибку

import org.junit.Test;

import java.util.Scanner;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class InputTest {

    @Test
    public void iputData() {
        Scanner mock = mock(Scanner.class);
        when(mock.nextInt()).thenReturn(1);
        Input input = new Input(mock);
        assertEquals(2,input.IputData());
    }
}

A: Проще было бы не мокать Scanner, а создать его экземпляр, используя строку или строки, имитирующую ввод пользователя:
@Test
public void inputData() {
    Scanner notMock = new Scanner("2");
    Input input = new Input(notMock);

    assertEquals(2, input.IputData());
}

В Junit 5 есть возможность задать массив строк для параметризованного теста:
@ParameterizedTest
@ValueSource(strings = {"   2   ", "2", "\t2"})
public void inputData(String userInput) {
    Scanner notMock = new Scanner(userInput);
    Input input = new Input(notMock);

    assertEquals(2, input.IputData());
}

A: Можно запустить одну программу при помощи другой программы, для этого подойдет Process:
Process p = Runtime.getRuntime().exec(Команда_запуска_String);

Затем используйте это для ввода/вывода:
PrintWriter writer = new PrintWriter(p.getOutputStream()); // Через этот writer можно ввоздить значения
Scanner errScanner = new Scanner(p.getErrorStream()); // Сканер потока ошибок (То что в Java System.err.println())
Scanner outScanner = new Scanner(p.getInputStream()); // Сканер потока ошибок (То что в Java System.out.println())

// Ввод строки
writer.println(input);
writer.flush();

Если вы используйте Eclipse, то команду запуска можно посмотреть так:
Run >> Run Configurations... >> см картинку

Пример:
MyRunner.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

...

        Process p = Runtime.getRuntime().exec("путь_до_javaw.exe -Dfile.encoding=Cp1251 -classpath \"ПУТЬ\\eclipse-stackoverflow\\1350994\\bin\" Main");
        PrintWriter writer = new PrintWriter(p.getOutputStream()); // Через этот writer можно ввоздить значения
        Scanner errScanner = new Scanner(p.getErrorStream()); // Сканер потока ошибок (То что в Java System.err.println())
        Scanner outScanner = new Scanner(p.getInputStream()); // Сканер потока ошибок (То что в Java System.out.println())

        writer.println(10); // вводим число 10
        writer.flush();

        new Thread(() -> {
            while (true) {
                if(errScanner.hasNextLine()) {
                    System.err.println(errScanner.nextLine());
                }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                if(outScanner.hasNextLine()) {
                    System.out.println(outScanner.nextLine());
                }
            }
        }).start();

Main .java

public class Main {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int i = s.nextInt();
        System.out.println("Result:");
        System.out.println(i * i);
        System.err.println("0 Errors");
        s.close();
    }
}


text:
Q: Laravel input field number_format() I'm struggling with my users about big numbers in the input fields for better reading. Is there an easy way to have formatted numbers in input fields like 1'450'000.00 and how to save the value as number?
in the moment I handle it like this:
<input id="wbw" type="numeric" class="form-control @error('wbw') is-invalid @enderror" name="wbw" value="{{number_format( old('wbw', $bw->wbw), 2, '.', '')}}" autofocus>
but I like to have something like this as number_format:
value="{{number_format( old('wbw', $bw->wbw), 2, '.', '´')}}"
But then I have the problem while saving, because it's not a number anymore. Do I have to handle it in the save-function in the controller or is there an elegant way in the blade?
Thanks for help!

A: Since the formatting of number is only needed in client side (shown to user in browser), then it's better to just use javascript library instead of server-side php.
Example with AutoNumeric.js:

window.myinput = new AutoNumeric('#myinput', 1450000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/autonumeric@4.1.0"></script>
<input type="text" id="myinput">
<button onclick="alert(window.myinput.rawValue)">see value</button>

Example with cleave.js

window.cleave = new Cleave('.input-element', {
    numeral: true,
    numeralThousandsGroupStyle: 'thousand'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cleave.js/1.6.0/cleave.min.js"></script>
<input type="text" class="input-element" value="1450000">
<button onclick="alert(window.cleave.getRawValue())">see value</button>

But you must also add before submit js event handler so that the POST-ed value in form is the input's raw value instead of the formatted value
Disclaimer: I'm not associated with author of those library above

A: When you will use the number_format function this will result in a string. So to save this string you need to change the database column type to varchar or any other string type.


text:
Q: ActiveRecord Collections and custom methods I'm trying to create a factory_build class method for creating Redirect objects within an ActiveRecord collection (see below).
For example @website.redirects.factory_build(:code => 301) would return a new instance of a PermenantRedirect object. However, even though I am able to invoke the factory_build class method I can't get access to the primary_key for @website. Is there a way to access @website.id from inside a collection or am i forced to pass it into the method call? Any other suggestions would also be welcome, maybe I'm not going about this in the right approach. thanks.
class Website < ActiveRecord::Base
  has_many :redirects
  has_many :permenant_redirects
  has_many :temporary_redirects
end

# Redirect is an abstract class it uses Rails Single Table Inheritance
class Redirect < ActiveRecord::Base
  def self.factory_build(attributes)
    status_code = attributes.delete(:code)
    case status_code
      when 301
        Website.find( ... ).permenant_redirects.new(attributes)
      when 302
        Website.find( ... ).temporary_redirects.new(attributes)
      else
        raise InvalidStatusCodeError
    end
  end
end

class TemporaryRedirect < Redirect
  def status
    302
  end
end

class PermenantRedirect < Redirect
  def status
    301
  end
end

A: You need to access the scope for this relationship in order to be able to properly construct these objects. This is available to a class method:
class Redirect < ActiveRecord::Base
  def self.factory_build(attributes)
    redirect_type =
      case (status_code = attributes.delete(:code))
      when 301
        PermanentRedirect
      when 302
        TemporaryRedirect
      else
        Redirect
      end

    redirect_type.new(attributes.merge(scoped.scope_for_create))
  end
end

I've taken the liberty of DRYing up your creation code because you had a lot of duplication in there. Also note that calling find only to exercise a relationship is a waste of resources. If you know the ID of the record, simply pass that along as an attribute unless you have a very good reason for retrieving it first.
The scoped.scope_for_create call returns attributes defined by your current scope or scopes. These are usually in the form of something like { 'website_id' => 101 } and can be passed through to your create call.


text:
Q: VNC Job scheduling Does anyone have any experience with synchronizing files across multiple machines at set times through VNC? Is there any software that can do this, looks like tightVNC is not capable of scheduling jobs ahead of time.

A: No.  This is not an appropriate task for VNC.  As Aaron stated you should use an appropriate tool for this.  rsync and scp are commonly used and easy to schedule.  If your are synchronizing configuration you should look at tools like puppy or cfengine.


text:
Q: Error in reputation points from Stack Exchange and main site account deleted A few months ago I deleted my main Stack Overflow en español (SO.es) account with around 4.5K reputation.
I have created an account again and when I see my reputation in SO.es I have 250 points.

And in I SO.es.../repu... see:
total votes: 56
 3    383755 (0)
 2    383755 (10)
-- 2020-08-21 rep +10   = 11
 2    383755 (10)
 2    383755 (10)
 2    383755 (10)
 3    383755 (-2)
-- 2020-08-24 rep +28   = 39
 2    383755 (10)
-- 2020-08-26 rep +10   = 49
 2    383755 (10)
-- 2020-08-29 rep +10   = 59
 2    383755 (10)
-- 2021-01-04 rep +10   = 69
 2    383755 (10)
-- 2021-01-22 rep +10   = 79
 2    383755 (10)
-- 2021-01-25 rep +10   = 89
-- 2021-06-12 rep 0     = 89
 2    383755 (10)
-- 2021-11-16 rep +10   = 99
 3    383755 (-2)
-- 2022-04-05 rep -2    = 97
-- bonuses   (100)
-- 2022-12-15 rep +100  = 197
 3    576068 (-1)
 3    576070 (-1)
 2    576020 (10)
 2    576020 (10)
 16   576106 (2)
 16   576066 (2)
-- 2022-12-29 rep +22   = 219
-- 2023-01-03 rep 0     = 219
 3    576793 (-1)
 1    576916 (15)
 2    576916 (10)
 3    576923 (-1)
-- 2023-01-04 rep +23   = 242
 3    576020 (-2)
 2    576231 (10)
-- 2023-01-05 rep +8    = 250
-- 2023-01-07 rep 0     = 250

** rep today: 0
** rep this week (2023-01-08 - 2023-01-14): 0
** rep this month (2023-01-01 - 2023-01-31): 31
** rep this quarter (2023-01-01 - 2023-03-31): 31
** rep this year (2023-01-01 - 2023-12-31): 31
** rep from bonuses: 100
** total rep 250 :)

days represented 16
rep cap was reached via rep from upvotes *only* on 0 days
earned at least 200 reputation on 0 days
earned 4 reputation from suggested edits

This all looks good and is correct, but when I go to my profile on the Stack Exchange network I see this:

I don't know if this is a bug; but it seems even after months of deleting the main account with data linked to the network account:

*

*is this normal behavior?

*If there is still data linked, would it be possible to recover those reputation points that are reflected?


text:
Q: UIPageViewController не работает скролинг страниц Начал недавно изучать swift, работаю над приложение где с помощью PageViewСontroller можно перелистывать один View Controller. Помогите пожалуйста разобраться с UIPageViewController, почему-то не работает скролинг страниц, также реализовал перелистывание с помощью кнопок, чтобы хоть как-то листалось, но хотелось бы чтобы нормально скролилось.
class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate{

    var pageDescriptions = ["1","2","3","4","5"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.dataSource = dataSource
        self.delegate = delegate

        if let startTableVC = self.viewControllerAtIndex(index: 0) {
            setViewControllers([startTableVC], direction: .forward, animated: true, completion: nil)
        }
    }

    func nextPageWithIndex(index: Int)
    {
        if let nextTableVC = self.viewControllerAtIndex(index: index + 1) {
            setViewControllers([nextTableVC], direction: .forward, animated: true, completion: nil)
        }
    }

    func previousPageWithIndex(index: Int)
    {
        if let previousTableVC = self.viewControllerAtIndex(index: index - 1) {
            setViewControllers([previousTableVC], direction: .reverse, animated: true, completion: nil)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func viewControllerAtIndex(index: Int) -> TableViewController?
    {
         //Create a new view controller and pass suitable data.
        if index == NSNotFound || index = self.pageDescriptions.count {
            return nil
        }

        if let tableViewController = storyboard?.instantiateViewController(withIdentifier: "TableCell") as? TableViewController {
            tableViewController.date = pageDescriptions[index]
            tableViewController.index = index

            return tableViewController
        }
        return nil
    }

    //
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController?{
        var index = (viewController as! TableViewController).index
        index -= 1
        return self.viewControllerAtIndex(index: index)

    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController?{
        var index = (viewController as! TableViewController).index
        index += 1
        return self.viewControllerAtIndex(index: index)

    }

    func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int
    {
        return self.pageDescriptions.count
    }

    func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int
    {
        return 0
    }
}


text:
Q: UserControl: How to add MouseWheel Listener? I'm creating an UserControl that should react if the mouse is over the control and MouseWheel gets rotated.
Currently i'm doing this as shown here:
    public MyUserControl()
    {
        this.MouseWheel += new MouseEventHandler(MouseWheelHandler);
    }

    private void MouseWheelHandler(object sender, System.Windows.Forms.MouseEventArgs e)
    {
        if (e.Delta > 0)
            incIndex();

        if (e.Delta < 0)
            decIndex();
    }

    protected override void OnMouseEnter(EventArgs e)
    {
        this.Focus();

        base.OnMouseEnter(e);
    }

In fact this works fine, but the problem is the part with the "this.Focus();" as it destroys my forms / applications behaviour.
Is there a better way to achive this?

A: having the same problem, I finally implemented a mix of both solution by @Paul_Westcott and @nr1. This is a local solution like solution of @Paul_Westcott (only applies to the winforms control that subscribes to). It is multiple monitor safe and MDI safe (overlapping by other windows within the application)
public static class MouseWheelHandlerForWinformsControl
{
    private class MouseWheelMessageFilter : IMessageFilter
    {
        [DllImport("user32.dll")]
        private static extern IntPtr WindowFromPoint(Point pt);

        private readonly Control mCtrl;
        private readonly Action<MouseEventArgs> mOnMouseWheel;

        public MouseWheelMessageFilter(Control ctrl, Action<MouseEventArgs> onMouseWheel)
        {
            mCtrl = ctrl;
            mOnMouseWheel = onMouseWheel;
        }

        public bool PreFilterMessage(ref Message m)
        {
            // handle only mouse wheel messages
            if (m.Msg != 0x20a)
                return false;

            Point mouseAbsolutePosition = new Point(m.LParam.ToInt32());
            Point mouseRelativePosition = mCtrl.PointToClient(mouseAbsolutePosition);

            IntPtr hControlUnderMouse = WindowFromPoint(mouseAbsolutePosition);
            Control controlUnderMouse = Control.FromHandle(hControlUnderMouse);

            if (controlUnderMouse != mCtrl)
                return false;

            MouseButtons buttons = GetMouseButtons(m.WParam.ToInt32());
            int delta = m.WParam.ToInt32() >> 16;

            var e = new MouseEventArgs(buttons, 0, mouseRelativePosition.X, mouseRelativePosition.Y, delta);

            mOnMouseWheel(e);

            return true;
        }

        private static MouseButtons GetMouseButtons(int wParam)
        {
            MouseButtons buttons = MouseButtons.None;

            if(HasFlag(wParam, 0x0001)) buttons |= MouseButtons.Left;
            if(HasFlag(wParam, 0x0010)) buttons |= MouseButtons.Middle;
            if(HasFlag(wParam, 0x0002)) buttons |= MouseButtons.Right;
            if(HasFlag(wParam, 0x0020)) buttons |= MouseButtons.XButton1;
            if(HasFlag(wParam, 0x0040)) buttons |= MouseButtons.XButton2;

            return buttons;
        }

        private static bool HasFlag(int input, int flag)
        {
            return (input & flag) == flag;
        }
    }

    public static void MemorySafeAdd(Control ctrl, Action<MouseEventArgs> onMouseWheel)
    {
        if (ctrl == null || onMouseWheel == null)
            throw new ArgumentNullException();

        var filter = new MouseWheelMessageFilter(ctrl, onMouseWheel);
        Application.AddMessageFilter(filter);
        ctrl.Disposed += (s, e) => Application.RemoveMessageFilter(filter);
    }
}

Once you have added this helper class into your solution, you subscribe a control myControl to the mouse-wheel, in one line, as following:
public void Init() {
    MouseWheelHandlerForWinformsControl.MemorySafeAdd(myControl, OnMouseWheelEvent);
}

void OnMouseWheelEvent(MouseEventArgs args) {
    // do what you need here
}

A: Copy pasted from http://social.msdn.microsoft.com/forums/en-US/winforms/thread/eb922ed2-1036-41ca-bd15-49daed7b637c/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsApplication1 {
  public partial class Form1 : Form, IMessageFilter {
    public Form1() {
      InitializeComponent();
      Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m) {
      if (m.Msg == 0x20a) {
        // WM_MOUSEWHEEL, find the control at screen position m.LParam
        Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
        IntPtr hWnd = WindowFromPoint(pos);
        if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null) {
          SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
          return true;
        }
      }
      return false;
    }

    // P/Invoke declarations
    [DllImport("user32.dll")]
    private static extern IntPtr WindowFromPoint(Point pt);
    [DllImport("user32.dll")]
    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
  }
}

this works great, thx Hans Passant

A: Just a slight variation on the solution that has already been published, in order to not have to use P/Invoke.
public static class MouseWheelHandler
{
    public static void Add(Control ctrl, Action<MouseEventArgs> onMouseWheel)
    {
        if (ctrl == null || onMouseWheel == null)
            throw new ArgumentNullException();

        var filter = new MouseWheelMessageFilter(ctrl, onMouseWheel);
        Application.AddMessageFilter(filter);
        ctrl.Disposed += (s, e) => Application.RemoveMessageFilter(filter);
    }

    class MouseWheelMessageFilter
        : IMessageFilter
    {
        private readonly Control _ctrl;
        private readonly Action<MouseEventArgs> _onMouseWheel;

        public MouseWheelMessageFilter(Control ctrl, Action<MouseEventArgs> onMouseWheel)
        {
            _ctrl = ctrl;
            _onMouseWheel = onMouseWheel;
        }

        public bool PreFilterMessage(ref Message m)
        {
            var parent = _ctrl.Parent;
            if (parent != null && m.Msg == 0x20a) // WM_MOUSEWHEEL, find the control at screen position m.LParam
            {
                var pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);

                var clientPos = _ctrl.PointToClient(pos);

                if (_ctrl.ClientRectangle.Contains(clientPos)
                 && ReferenceEquals(_ctrl, parent.GetChildAtPoint(parent.PointToClient(pos))))
                {
                    var wParam = m.WParam.ToInt32();
                    Func<int, MouseButtons, MouseButtons> getButton =
                        (flag, button) => ((wParam & flag) == flag) ? button : MouseButtons.None;

                    var buttons = getButton(wParam & 0x0001, MouseButtons.Left)
                                | getButton(wParam & 0x0010, MouseButtons.Middle)
                                | getButton(wParam & 0x0002, MouseButtons.Right)
                                | getButton(wParam & 0x0020, MouseButtons.XButton1)
                                | getButton(wParam & 0x0040, MouseButtons.XButton2)
                                ; // Not matching for these /*MK_SHIFT=0x0004;MK_CONTROL=0x0008*/

                    var delta = wParam >> 16;
                    var e = new MouseEventArgs(buttons, 0, clientPos.X, clientPos.Y, delta);
                    _onMouseWheel(e);

                    return true;
                }
            }
            return false;
        }
    }
}

And then this can used from individual controls like
class MyControl
    : Control
{
    public MyControl()
    {
        ...
        MouseWheelHandler.Add(this, MyOnMouseWheel);
    }

    void MyOnMouseWheel(MouseEventArgs e)
    {
        ...
    }
}

A: Paul Westcott's answer works great when using a FlowLayoutPanel.  My implementation of MyOnMouseWheel event is:
void MyOnMouseWheel(MouseEventArgs e)
{
    int ChangeIncrement = (this.panel1.VerticalScroll.SmallChange * 4); //Change the 4 to any positive number to scroll more or less one each scroll event.
    if (e.Delta < 0)
    {
        int NewValue = this.panel1.VerticalScroll.Value + ChangeIncrement;
        if (NewValue > this.panel1.VerticalScroll.Maximum)
        {
            this.panel1.VerticalScroll.Value = this.panel1.VerticalScroll.Maximum;
        }
        else
        {
            this.panel1.VerticalScroll.Value = NewValue;
        }
    }
    else if (e.Delta > 0)
    {
        int NewValue = this.panel1.VerticalScroll.Value - ChangeIncrement;
        if (NewValue < this.panel1.VerticalScroll.Minimum)
        {
            this.panel1.VerticalScroll.Value = this.panel1.VerticalScroll.Minimum;
        }
        else
        {
            this.panel1.VerticalScroll.Value = NewValue;
        }
    }
    this.panel1.PerformLayout();
}


text:
Q: Convergence of a series, what is wrong with my solution? I have just attempted the following question

Show that if $ (b_n) _{n \in \mathbb N }$ is a bounded sequence in $\mathbb R $, then the series $\sum_{n=1}^{\infty }b_n2^{-n}$ is convergent.

This is my solution.

If $(b_n)$ is bounded then $\exists M \in \mathbb R$ such that  $\lvert b_n \rvert \le M$ $\forall n \in \mathbb N$. Then, by taking every term in the following series to be
$M$ and the fact $\sum_{n=1}^{\infty} 2^{-n}$ converges to 1, we deduce that
$$
\sum_{n=1}^{\infty } b_n2^{-n} \le \sum_{n=1}^{\infty } M2^{-n} = M
$$
Therefore, by the comparison test $\sum_{n=1}^{\infty } b_n2^{-n}$ converges.

However, the official solution uses Cauchy sequences and partial sums. Is there a major flaw in my solution?

A: $b_n$ may be negative, so you cannot use the comparison test, which works for series with non-negative terms. So you may take absolute value to conclude that the series $\sum|b_n|2^{-n}$ converges by comparison test, and the original series converges since it converges absolutely.


text:
Q: Using one IPython for multiple environments Is it possible to install IPython in base environment and use it in a different environment, maybe by installing ipykernel in there and somehow linking to base IPython? I am thinking something like Spyder, where you only need to install spyder-kernels in that environment and link its python executable to the python interpreter in base Spyder (heard similar things with Jupyter too). Otherwise I'll have to install IPython for every environment. I'm using Windows 10 and latest miniconda.

A: Yes, you can install ipython just to your base python env. Then when you create a virtualenv as a copy of that base python distribution, specify incremental dependencies on a per project basis using a requirements.txt file. You can read more about using virtualenv and pip to accomplish what you want on this brief article in the hitchhiker's guide.


text:
Q: i am trying to make a clear button. when user click on the clear button then all list should be clear permanently i am trying to make a clear button. when user click on the clear button then all list should be clear permanently. list will appear when the user will input something in input field and save that by SAVE IT button and then list will appear below the save button.

let mySearch = []
    let inputEl = document.getElementById("input-el")
    let saveEl = document.getElementById("save-el")
    let ulEl = document.getElementById("ul-el")
    let clearEl = document.getElementById("clear-el")

    saveEl.addEventListener("click", function () {
        mySearch.push(inputEl.value)
        inputEl.value = " "
        render()
    })

    function render() {
        let listitems = ""
        for (let i =0; i < mySearch.length; i++) {
            listitems += "
" + mySearch[i] + "
"

           // alternative
          /*const list = document.createElement("li")
           list.textContent += mySearch[i]
           ulEl.append(list) */
    }
     ulEl.innerHTML = listitems
    }

    when this clear button click all list which saved by "SAVE IT" button from input field should clear the list
    clearEl.addEventListener("click", function() {
         ulEl.textcontent = " "
    })

                 <input type="text" id="input-el" class="input" placeholder="Search..">

                 <button id="save-el" class="savebut">SAVE IT</button>
                 <button type="reset"  id="clear-el" class="clearbut">clear list</button>

A: this should solve your problem. first you need to remove all the children of the ul element.
    while(ulEl.firstChild){
        ulEl.removeChild(ulEl.firstChild);
    }

and you need to empty the array.
mySearch = []

Full code:
    let mySearch = []
    let inputEl = document.getElementById("input-el")
    let saveEl = document.getElementById("save-el")
    let ulEl = document.getElementById("ul-el")
    let clearEl = document.getElementById("clear-el")
    let save = document.getElementsByClassName("save")[0]

    saveEl.addEventListener("click", function () {
        mySearch.push(inputEl.value)
        inputEl.value = " "
        render()
    })

    function render() {
        let listitems = ""
        for (let i =0; i < mySearch.length; i++) {
            listitems += "
" + mySearch[i] + "
"
    }
     ulEl.innerHTML = listitems
    }

    clearEl.addEventListener("click", function() {
    while(ulEl.firstChild){
        ulEl.removeChild(ulEl.firstChild);
    }
        mySearch = []
    })


text:
Q: (numberf) What does it mean
Possible Duplicate:
"f" after number/float in Objective-C/C

I searched in internet, but i found nothing. So, what does mean whet near number is f character, like 3.0f or 4.6f . And what's the difference beetween normal number like 3.0 and [f] (:D) number like 3.0f . Thank you very much!


text:
Q: Is it possible to pass my value in node and express js by clicking a button In this problem, I want to pass my values in express js so that it will written down in node js.
I am clicking a button which will be the demo here
<form action="/measure" method="POST">
    <button type="button" name="Add" > Add </button>
    <button type="button" name="Substract" > Subtract </button>
    <input type="submit">
</form>

I did something like this in express js
const homePage = fs.readFileSync('./index.html')

app.get('/',(req,res) => {
    res.writeHead(200,{'content-type':'text/html'})
    res.write(homePage)
    res.end()
})

var counter = 0;

app.post('/measure',(req,res) => {

    res.writeHead(200,{'content-type':'text/html'})
    const {Add,Subtract,result} = req.body
    if (Add) {
        counter += 1;
    } else if (Subtract) {
        counter -= 1
    }
    res.write(homePage + `<h1>${counter}</h1>`)
    res.end()

})

But this doesn't do anything, based on my thought, the wrong about here is the button in index html which it doesn't pass anything...Have you guys any idea how I can pass the value in the express js? I've been searching since last night about it but couldn't find the right information, All I get is this link which is not my prefer since I am not focusing yet in database LINK

A: A single button in a form can be represented as a <button> element. But if you want several buttons in a form, represent them all as <input type="submit">:
<form action="/measure" method="POST">
  <input type="submit" name="Add" value="Add"/>
  <input type="submit" name="Subtract" value="Subtract"/>
  <input type="submit"/>
</form>

Depending on which button you press, you will get req.body as

*

*{"Add": "Add"} or

*{"Subtract": "Subtract"} or

*{}


text:
Q: Convert methods to a generic method in DAO layer Currently I'm having some methods in my DAO layer with multiple select queries. What I was thinking is to have a generic method for all these three methods so that it can be used for further also. Here are my methods.
public List<Customer> findAll(){

    String sql = "SELECT * FROM CUSTOMER";

    List<Customer> customers  = getJdbcTemplate().query(sql,
        new BeanPropertyRowMapper(Customer.class));

    return customers;
}

For finding phone numbers of a customer.
public List<Phone> findPhoneNumbers(int custId){

    String sql = "SELECT * FROM PHONE WHERE CUST_ID="+custId;

    List<Phone> phoneNumbers  = getJdbcTemplate().query(sql,
        new BeanPropertyRowMapper(Phone.class));

    return phoneNumbers;
}

and so on.
Can these methods can be converted in a single generic method, so that it can be called from my service layer. Any suggestions or ideas would be greatly appreciated.

A: You can use a generic method and let the caller specify the class.
It's easy for findAll
public <T> List<T> findAll(Class<T> entityClass, String tableName){

    String sql = "SELECT * FROM " + tableName;

    return getJdbcTemplate().query(sql,
        new BeanPropertyRowMapper(entityClass));

    return phoneNumbers;
}

You can further improve this by using class metadata, such as specifying an annotations:
@Target(ElementType.Type)
public @interface MappedTable {
    String tableName();
}

//apply the annotation to bean classes:
@MappedTable(tableName="CUSTOMERS")
public class Customer {}

Which will allow your findAll method to look like:
public <T> List<T> findAll(Class<T> entityClass){

    String sql = "SELECT * FROM " + entityClass
      .getAnnotation(MappedTable.class).tableName();

    return getJdbcTemplate().query(sql,
        new BeanPropertyRowMapper(entityClass));

    return phoneNumbers;
}

Implementing findByXyZ will be trickier, but you can use a similar approach that either takes the full query from the caller or that uses additional annotation-based metadata.
Note that the complexity of this kind of code grows very fast. That's why it's a good idea to consider using ORM tools instead of reinventing them (the above is just an idea for simple cases as the one in the question).

A: public <T> List<T> findAll(String sql, Class<T> clazz) {
   return getJdbcTemplate().query(sql, new BeanPropertyRowMapper(clazz));
}

Then you call
String sql = "SELECT * FROM CUSTOMER";
List<Customer> customers = findAll(sql, Customer.class);

Or
String sql = "SELECT * FROM PHONE WHERE CUST_ID="+custId;
List<Phone> phoneNumbers = findAll(sql, Phone.class);

The problem is that you have to construct sql statement before calling the method.
Maybe you want an android sqldatabase-like interface and construct sql statement in the method.
public <T> List<T> findAll(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy,  Class<T> clazz) {
    String sql = // construct sql statement
    return getJdbcTemplate().query(sql, new BeanPropertyRowMapper(clazz));
}

I'm not familiar with sql statement, you may find something in the Android SDK SQLiteQueryBuilder.buildQueryString(...).
If you really want to return a single item not a list with one item, you need another method.
public <T> T findOne(String sql, Class<T> clazz) {
    // your sql statement should contains something like "limit 1"
    List<T> result = findAll(sql, clazz);
    return result.isEmpty() ? null : result.get(0);
}

If you need one method but you require to return List<T> for multiple data and T for single data. Try this:
public <T> Object findAll(String sql, Class<T> clazz, bool one) {
    List<T> all = getJdbcTemplate().query(sql, new BeanPropertyRowMapper(clazz));
    return one ? all.get(0) : all;
}

But I don't really suggest this approach. I don't think it is necessary to return a single item rather than a list with a single item.

A: You can use inheritance to achieve this
1) class Customer
2)class PhoneNumber extends Customer
3) class Address extends Customer
4) Declaring methods as
public List<T> findPhoneNumbers(Customer customer){
if(customer instanceOf PhoneNumber) {sql ="get phone number query ...."}
else if(customer instanceOf Address) {sql ="get address query ...."}
else {sql = get customer query}
}

Now in the calling method(ServiceLayer), you can pass appropriate object to choose query and get result


text:
Q: Как взять стили при помощи jQuery $('.block').outerWeight(); - это конструкцией jquery берёт стили из файла css, но когда я перезадаю блоку ширину jquery прописывает стили в HTML. Как получить стили из HTML или самые актуальные стили?

A: Для вашего случая есть несколько вариантов:
$('.block').width();

либо
$('.block').css('width');

A: jQuery и так берет стили из существующих на данный момент на странице.
outerHeight() и outerWidth() возвращает не значение свойства CSS width / height, а высоту / ширину содержимого элемента плюс отступы (border, padding, margin). Используйте методы width(), height(), или css().


text:
Q: Virtual PC - How to convert .nrg file to .vhd I have a live cd of linux. named Knoppix.
I want to run it as a virtual OS on my windows. I have installed windows xp on my PC.
And I am using "Microsoft Virtual PC" for using Virtual OS.
What My aim is "Run Knoppix live cd" as a virtual os on my windows.
Is it possible ? How ?
I have converted that CD in Nero .nrg file. But "Microsoft virtual PC" requires a .vhd file for it. I am confused here.
What should I do to convert .nrg file to .vhd file ?
Or which is the better way ?
Thanks in advance for sharing your knowledge
Sugar.

A: A VHD file is a virtual hard drive.  Since Knoppix runs off a cd, you can't convert the CD into a VHD.  However, you can easily run Knoppix on Virtual PC.
Firat you should download a Knoppix ISO from here, as I don't think Virtual PC can use an NRG file.  Create a new virtual machine in Virtual PC.  During this step, it will ask you if you want to create a new VHD file.  Go ahead and create one, though you will probably not need to use it unless you want to save files onto it between sessions.
Once the virtual machine is created, start it up.  Immediately go to the CD menu and choose "Capture ISO Image".  Select the downloaded Knoppix ISO.  Knoppix should then load up.

A: I think we have a minor misconception to clear up. While there are image formats that can be of any media (.img), there's some CD specific ones (nrg and iso for example) and hard drive ones such as VHD. You can boot VPC off a iso (in lieu of a cd) or a vhd (instead of a hard drive) but in general you cannot convert a iso image to a vhd image.
I'd also note knoppix is a live cd distro so booting it off the iso as dsolimano suggested is valid, and probably the right answer.


text:
Q: Magento 2: disable system warning messages in Admin Panel for some user
Is there a way to disable system warning messages popups for some specific user (or for all users also) in Magento 2?

A: Login to your Admin
Navigate to:
Stores > Configuration > Advanced > Advanced

Disable Admin Notifications by
Disable Modules Output > Magento_AdminNotification > Set to Disable

A: Create a new role here if you have not created already System->User Roles->Role Resources
If you have already created it then do the following
System->User Roles->Role Resources (tab) from Resource Access drop down under system folder tree find the Other Settings now you can see Notifications you may enable/disablehere save the role and assign this role for specific users.

A: You can use user-role specific handles from this module https://github.com/TheFrankman/magento2-customhandles (very handy anyway)
and then remove the block via layout:
<referenceBlock name="notification.messages" remove="true"></referenceBlock>

A: Until a proper fix can be rolled out, I created a userscript to fix this problem using Tampermonkey. For those that do not know what Tampermonkey is, it is a userscript manager browser extension, that allows users to install scripts that make on-the-fly changes to web page content after or before the page is loaded in the browser.
Here is the script
https://github.com/EnochDataSystems/gists/blob/master/magento2-system_messages-fix.js
The script will reduce the width of the systemMessageBlock and move it to the top left corner. When the systemMessageBlock is loaded, it will hover over any text or elements in that corner, but after 5 seconds it will fade away.
This is an easy quick fix and doesn't involve touching the Magento code.

A: I am using magento2 (2.4.1-p1 version).
I have disabled the module output for my backend with this command:
php bin/magento module:disable Magento_AdminNotification


text:
Q: AdapterContextMenuInfo is always null I tried doing this by the book from android dev docs:
// this didn't create a menu, i don't know why
//registerForContextMenu(getListView());

setListAdapter(new ArrayAdapter<Note>(this, R.layout.selectset_listitem) {
    @Override

    protected View getView(...) {
        ... custom layout ...

        // this creates a menu, but...
        registerForContextMenu(convertView);

        return convertView;
    }
}

And the onCreateContextMenu and onContextItemSelected almost exactly as in http://developer.android.com/guide/topics/ui/menus.html#context-menu.
here is how it looks in the docs (and my code):
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenuInfo menuInfo) {
  super.onCreateContextMenu(menu, v, menuInfo);
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.context_menu, menu);
}

but this part always gives me a null info:
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    ...
}

The only thing that is really unique is that i've got a custom layout for list items (i.e. a couple of text fields and an image). Is there something i need to do to be able to get the index of the list item that the context menu was built for?

A: You need to call the registerForContextMenu() in the activity on the ListView, and not on the view items in the adapter.

A: getMenuInfo() will work on ListAdapter, not on views.
But, You can pass additional data with the tag of the view.
in
getView: vi.setTag(position) activity.registerForContextMenu(vi);

declare in Activity private int id;

onCreateContextMenu: id = (int) v.getTag();

onContextItemSelected:

you can use the id


text:
Q: Why my select value has changed but still displayed the old value? I am learning Vue with Element-UI these days, and I met a problem today early.
I saw my select's value has been changed already on the console, but on the page, it still displayed the old value. Why?
Here's my select tag's code:
<el-select v-model="ruleForm.emp" filterable placeholder="please select" @change="empChange">
  <el-option v-for="item in emps" :key="item.id" :label="item.name" :value="item">
  </el-option>
</el-select>

Here's the ruleForm's code:
ruleForm: {
     emp: {
         id: 1,
         name: '',
         address: ''
     },
     startDate: '',
     position: '',
     positionDetails: ''
}

Here's the empChange method:
empChange(emp){
    this.ruleForm.emp = emp;
}

If you need something more to help you to figure out, please let me know and I'll update at once.
Any help will be appreciated!
Update: Vue's and Element-UI's version
"element-ui": "^2.4.5",
"vue": "^2.5.2"

Update: one emp of the data emps:
emp: {
id: 1723
name: "test"
address: "address_test"
}

A: At empChange method, change:
empChange(emp){
   this.$set(this.ruleForm, 'emp', emp);
}

See reactivity


text:
Q: How to bound $ax^2+2bxy+cy^2$ by multiples of $x^2+y^2$ Let $(x,y)\in[0,1)\times[0,1)$ cum $x^2+y^2<1$. Are there any $\mu\geq\lambda>0$ such that
$$\lambda\xi_1^2+\lambda\xi_2^2\leq(1-x^2)\xi_1^2+2xy\xi_1\xi_2+(1-y^2)\xi_2^2\leq\mu\xi_1^2+\mu\xi_2^2$$
$\forall\xi=(\xi_1,\xi_2)^T\in\mathbb R^2$ ?

A: Let $A = \begin{bmatrix} 1-x^2 & xy \\ xy & 1-y^2\end{bmatrix}$. Then $(1-x^2)\xi_1^2+2xy\xi_1\xi_2+(1-y^2)\xi_2^2 = \langle \xi, A\xi \rangle$.
Choose $x = y = \frac{3}{4}$. Then $A = \frac{1}{16}\begin{bmatrix} 7 & 9 \\ 9 & 7\end{bmatrix}$, and choose $\xi = (1,-1)^T$. Then $\langle \xi,A \xi \rangle = -\frac{1}{4}$. So the answer to part of your question is no.
The other side is easier, since $\langle \xi,A \xi \rangle \leq (1-x^2)\xi_1^2+2xy(\xi_1^2+\xi_2^2)+(1-y^2)\xi_2^2 \leq (2-(x-y)^2) (\xi_1^2+\xi_2^2) \leq 2(\xi_1^2+\xi_2^2)$.
Answer to the modified question:
Again choose $\xi = (1,-1)^T$. Now choose $y = x$, and note that we can choose any $|x|<\frac{1}{\sqrt{2}}$. Then we have $\langle \xi,A \xi \rangle = 2(1-2 x^2)$. However, since $\inf_{|x|<\frac{1}{\sqrt{2}}} 2(1-2 x^2) = 0$, no $\lambda>0$ can exist satifying the lower bound $\langle \xi,A \xi \rangle \geq \lambda ||\xi||^2$.

A: Let $(x,y)\equiv (\cos\phi_0,\sin\phi_0)  \;\; $  and  $\; (\xi_1,\xi_2)\equiv \rho (\cos\phi,\sin\phi) \;\;$. Then the condition simplifies a lot $(\lambda < \cos^2(\phi-\phi_0)<\mu \;\;)$. It hints that $\lambda=0 \;$ and $\mu=1$. Cheers!

A: One asks that $\lambda\|\xi\|^2\leqslant\|\xi\|^2-\langle z,\xi\rangle^2\leqslant\mu\|\xi\|^2$ for every $\xi$, where $\|\ \|$ and $\langle\ ,\ \rangle$ are the usual Euclidean norm and the Euclidean scalar product, and $z=(x,y)$.
Since $\langle z,\xi\rangle^2\leqslant\|\xi\|^2\cdot\|z\|^2$ by Cauchy-Schwarz inequality, the first inequality holds with $\lambda=1-\|z\|^2=1-x^2-y^2$ hence $0\lt\lambda\leqslant1$. The second inequality holds with $\mu=1$.
One can check that these values are optimal, $\lambda$ when $\xi$ and $z$ are colinear and $\mu$ when $\xi$ and $z$ are orthogonal.


text:
Q: Django Weird behavior while extracting last element from a list at views.py I have created a blog with Django, I want my last published post appears at the first page. Here is my views.py code:
   def index(request):
       messages = get_list_or_404(Message.objects.order_by('publication_date'))
       last = messages[-1]
       return render_to_response('posts/index.html', {
          'last_message' : last,
          'posts_list'   : messages,
       })

But I don't understand why, while pressing F5 on this page, it prints the last post (as expected) or the first one (without any obvious reason) randomly (sometime the last post, sometime the first one).
This behavior occurs with apache2 running with mod_wsgi and not with django development server (which displays always the last post).
Does anyone have any clue?
Many thanks
Edit: Here is the code I use in my index.html template:
{% if last_message %}

{{ last_message.title }}

Published on {{ last_message.publication_date }}

{{ last_message.text }}

{% else %}

No post available

{% endif %}

A: I'd do it this way to ensure you're only pulling back one object instead of all the messages each time:
messages = Message.objects.order_by('-publication_date')[:1]
if not messages:
    raise Http404
last = message[0]

Alternatively you could do:
try:
    last = Message.objects.order_by('-publication_date')[0]
except IndexError:
    raise Http404

A: Oki, guys, the problem came from apache server which needed to be reloaded (there is no need to do so with PHP, that's why I haven't thought of it).
I also have replaced
    messages = get_list_or_404(Message.objects.order_by('publication_date'))
by
    last = get_list_or_404(Message).latest('publication_date')
Which is more concise.
Thanks for your help and answers!


text:
Q: Is it safe to compare floats strictly, given we do no operations on them? Normally, when we want to test fractional numbers for equality, we do so with some amount of uncertainty, because of approximate nature of IEEE754.
if (fabs(one_float - other_float) < SUFFICIENTLY_SMALL) {
    consider them equal;
}

Other approach might be to cast the floats to integers of specific magnitude, and compare resulting integers instead.
if ((uint)one_float == (uint)other_float) {
    consider them equal;
}

But consider the situation where our floats never undergo any arithmetics, and the only thing we do with them is assignment.
//  Might be called at any moment
void resize(float new_width, float new_height)
{
    if (current_width == new_width && current_height == new_height) {
        return;
    }

    accomodate framebuffers;
    update uniforms;
    do stuff;

    current_width = new_width;
    current_height = new_height;
}

In the example above, we have an event handler that may fire up spontaneously, and we want to reallocate resources only if real resize occurred. We might take the usual path with approximate comparison, but that seems like a waste, because that handler will fire up pretty often. As far as I know, floats are assigned just as everything else, using memory move; and equality operator performs just the memory comparison. So it looks like we are in a safe harbour. When checked on x86 and ARM, this assumption holds, but I just wanted to be sure. Maybe it's backed by some specs?
So, is there something that might change floats when only assigning them? Is the described approach viable?

A: A mass of "should"s follows.
I don't think there's anything that says an assignment from float to float (current_width = new_width) couldn't alter the value, but I would be surprised if such a thing existed. There should be no reason to make assignment between variables of the same type anything else than a direct copy.
If the incoming new_width and new_height keep their values until they change, then this comparison should not have any issues. But if they are calculated before every call they might change their value, depending on how the calculation is done. So it's not only this function that needs to be checked.
The C 2011 standard says that calculations may use bigger precision than the format you assign to, but nothing specific about assigning a variable to another. So the only imprecision should be in the calculation stage. The "simple assignment" part (6.5.16.1) says:

In simple  assignment (=),  the  value  of  the  right  operand  is  converted  to  the  type  of  the assignment  expression  and  replaces  the  value  stored  in  the  object  designated  by  the  left operand.

So if the types already match, there should be no need for conversion.
So, simply put: if you don't recalculate the incoming value on every call the comparison for equality should hold true. But is there really a case where your framebuffers are sized as floats and not integers?

A: In the case you mentioned it is safe to use == to compare because of the following lines at the end of the function:
current_width = new_width;
current_height = new_height;

any change to new_width or new_height will fail the if statement and you get the behavior you wanted.
abs() function usually is used when there is one variable float which is assigned dynamically in the program and one constant float which you want to use as a reference. Something like:
bool isEqual(float first, float second)
{
   if(fabs(first-second)<0.0001)
      return true;
   return false;
}

int main()
{
   float x = (float) 1 / 3;
   if(isEqual(x,0.3333))
      printf("It is equal\n");
   else
      printf("It is not equal\n");
}

A: Have a look here for how to compare two floats.
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
Find the test with "ULP, he said nervously". You can compare the floats as ints but have a look at how it's been done in the article ie (I hope I'm not breaching any licensing here, if so please delete the code that follows it's not mine)
bool AlmostEqualUlps(float A, float B, int maxUlpsDiff){
    Float_t uA(A);
    Float_t uB(B);
    // Different signs means they do not match.
    if (uA.Negative() != uB.Negative()) {
        // Check for equality to make sure +0==-0
        if (A == B) {
            return true;
        }
        return false;
    }

    // Find the difference in ULPs.
    int ulpsDiff = abs(uA.i - uB.i);
    if (ulpsDiff <= maxUlpsDiff) {
        return true;
    }
    return false;
}

Please read the rest of that  article, it's really good.


text:
Q: Can someone please explain the > in a simple way for me I am looking at code containing:
public virtual ICollection<T> GetPk(string pk)
{
    Expression<Func<T, bool>> predicate = c => c.PartitionKey == pk;
    return this.GetAll(predicate);
}

Can someone explain the syntax of <Func<T, bool>> ?

A: Simply Func<T, bool> is the anonymous method signature. The first type T is the input parameter type and the second type is the return type. This is more like a method when you consider your representation:
bool AnonMethod(T arg0)
{
   return arg0.PartitionKey == pk;
}

A: One of the best explanation can be found at MSDN

You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have one parameter that is passed to it by value, and that it must return a value.

As for argument in your example T is the type of input parameter and bool is the return type of exacted method.

A: A Func<T, bool> represents a function that takes an object of type T and returns a bool. It's commonly referred to as a "predicate", and is used to verify a condition on an object.
An Expression<Func<T, bool>> represents the abstract syntax tree of the function, i.e. its syntactic structure. It can be used to analyse the code of the function for various purposes, such as transforming it to SQL to be executed against a database.

A: For some background; prior to Func<T, TResult> (and the rest of this family) being part of the framework, you either had to explicitly define delegates or use anonymous methods.
Func and Action were added as part of the addition of lambda expressions to the language. They are the framework-defined delegates which lambda expressions are typed as, but which you as a developer can also use in place of your own custom delegate definitions.
You can get a nice history here;
http://blogs.msdn.com/b/ericwhite/archive/2006/10/03/lambda-expressions.aspx

A: I always find MSDN to be worth checking on things like this first,
http://msdn.microsoft.com/en-us/library/bb549151.aspx
Beaten by Maheep, didn't see the post message pop-in.
Basically, you're declaring a method that matches a signature, that can then be passed in to the call to get the data.

A: It is confusing at first but Func<T, bool> describes a function that returns a bool and accepts a parameter as type T.
In this case, T is an object that has a PartitionKey property and this GetPk method is using the Func<T, bool> to match all the T items in the instance object which have a PartitionKey that matches the string pk.

A: It's additional syntax so you know what goes in and out of the function.
Func<T, bool> means:
function has 1 input T and 1 output that's bool.
This is other variations of the function


text:
Q: Logstash-forwarder says certificate signed by unknown authority when using a self-signed certificate with SubjectAltName I'm trying to connect to logstash with logstash-forwarder. Their communication base on ssl so I generate a self-signed certificate follows this. Then I got this error message on logstash-forwarder side:

Failed to tls handshake with 9.21.61.19 x509: certificate signed by unknown authority (possibly because of "x509: invalid signature: parent certificate cannot sign this kind of certificate" while trying to verify candidate authority certificate "*.*.*.*.*")

If I generate the certificate without subject alt name, it will work.
The worked certificate can be generated by:

openssl req -x509  -batch -nodes -newkey rsa:2048 -keyout lumberjack.key -out lumberjack.crt -subj /CN=*.*.*.*.*

But what I'm hoping to do is to generate a certificate which can be used in different kinds of host. To do that I want to generate a ssl certificate whose CN=*.*.*.*.*, then alt names include *, *.*, *.*.* etc.
Is there any suggestion on how can I overcome this ssl error? Or a better way to make logstash-forwarder can work in a variety of environments?

A: Turns out, when I removed the

keyUsage = digitalSignature, keyEncipherment

in [ v3_ca ], which is asked in the guide, the generated certificate do works for a variety of host names.
This may not be a right scenario for SSL. But for the logstash/logstash-forwarder case, it do helps.

A: Have you mentioned the pem file in "ssl ca" the logstash-forwarder.conf ? You have to mention the pem file which is used to sign the certificate in conf.


text:
Q: The first checkbox on the page checks itself on and off whenever I click somewhere on the page As the title suggests, I have an issue concerning checkboxes, I create multiple checkboxes to the site using a foreach loop that looks like this:
foreach ($order->get_items() as $i => $item ){
    $quant = $item->get_quantity();
    $unitprice = $item->get_total() / $item->get_quantity();
    echo "<input type='checkbox' name='productinfo[]' value='" . " " . // wrapped
    $item->get_name() . " | " . $item->get_total() ."; $i'>";

and when I attempt to select one, if I don't click directly inside the box, or I change a numerical value created by this:
if($item->get_quantity() > 1) {
    echo "Määrä: " . "<input type='number' name='numberqty[" . $i . "]' value='" // wrapped
                . $quant . "'max='" . $quant . "' min='1' > " . "
";
}

the html side before the loop

Valitse kaikki tuotteet

   Tilauksessa tulleet tuotteet:

inside the same foreach, it always selects or deselects the very first checkbox printed to the site, it also selects/deselects the first checkbox if I click anywhere on the page after the first checkbox has been created, be it just text of a number selector. How do I fix this issue and what actually causes such problems so I can avoid them in the future?

A: Remove the label from

Valitse kaikki tuotteet

Tilauksessa tulleet tuotteet:

That should do the trick!