text:
Q: How many `malloc` calls is too many? If any? I'm implementing a system in C, implemented partially as a library. The library does most of the memory management itself, with the application layer just having to call *_destroy functions on the top-level objects.
While checking for memory leaks, I noticed that the number of calls to malloc seemed quite high, relative to the size of the application code. The performance of the code seems fine, but I've been bitten by "fast enough" code before when trying to scale.
The number of allocations roughly matches the number of objects created, including child objects of the top-level ones. So creating a single top-level object might trigger 7 malloc calls, since it needs one for itself and then a couple for it's children that may also need a few children.
Unfortunately, I'm relatively new to C programming, though generally experienced as a programmer, and have no idea whether or these numbers are normal or not.
So what would a good rule-of-thumb be for number of allocations? I know that less would generally be better, but changing the code to allow it would introduce complexity that I'm not willing to add without a significant increase in performance.
Also, should I worry about the performance of malloc/free or is that the realm of real-time performance (games etc.)?

A: The usual answer for this thing is to wait until you can measure if there's a problem.
My experience has been that malloc() is rarely an issue, but perhaps I also do more CPU-intensive work than you do, so malloc() isn't in the critical path.
Definitely some people are constrained by the malloc performance. See, for example, https://github.com/blog/1422-tcmalloc-and-mysql , where github switched to using TCMalloc for MySQL and got a 30% performance improvement. There's more discussion at http://www.reddit.com/r/programming/comments/18zija/github_got_30_better_performance_using_tcmalloc/ .
TCMalloc is one of several malloc replacements. Another is jemalloc, and a third is nedmalloc.
So, if you think it's a problem (eg, because profiling shows that you're stuck in malloc/free often) then try one of those out and see if it improves things.
If it's a concern now, then perhaps you can think about how your code is structured. The biggest improvement is to realize that you don't need to think of "one structure = one malloc."
For example, I once wrote a parser for a tab-separated document. While I could have turned each row and field into its own string, it was faster to scan the document, count the number of rows and columns, and do a single malloc for the row/field pointers. Then in the second step, scan the document again, assign the correct pointers to the head of each field, and replace the tabs and newlines with a NUL to get proper NUL-terminated strings for the field.
This meant that my parser now "owned" the document string, which was acceptable. And it reduced the complexity of the code, even if the malloc performance wasn't critical.

A: It's not always the malloc and free performance that is an issue.  You can run into problems with cache locality (or rather a lack of cache locality), and that can really hit performance if you are doing a lot of processing on the data.
If you are worried you could switch to a memory-pooled scheme for all, most, or some parts of your API.  I'm sure there are plenty of tools out there to do this in a generic way, but more often than not the pooling requirements of an application are so basic that it's trivial to implement yourself.
Unfortunately, you are the best judge of whether pooling will benefit your application, and whether it is worth the effort and increased complexity.  Just remember, a pool can be as simple as a large char buffer.
Just watch out for memory alignment issues (like don't start objects at non-aligned memory addresses).
A classic argument I like to give for memory pools is a 2D array...
So often, you see people allocate a chunk for the row pointers, and then loop through allocating each row...  You have to do more error handling, the 'delete' function is a pain, and at the end of it you get a matrix whose row index and individual rows could be fragmented across your address space.
Yet, all you really needed to do was allocate one block of memory with enough space for a bunch of pointers and the 2D data segment, then index it.  It's not technically a pool, but it is smarter use of memory.

A:

How many malloc calls is too many? If any?

To me it's too many when you actually see malloc and free calls occupying the top hotspots in your profiler, or more subtly, you don't see such calls but your tightest and most critical loops dereferencing pointers are showing up as huge hotspots with the profiler showing cache misses all over the place. Unfortunately that discovery could be made too late if fixing those hotspots suggests costly design changes.

So what would a good rule-of-thumb be for number of allocations? I know that less would generally be better, but changing the code to allow it would introduce complexity that I'm not willing to add without a significant increase in performance.

The most useful rule of thumb I've started to apply for myself doesn't concern myself with such questions. It just seeks out simple designs that don't even make these issues a design-level concern in the first place. And for lack of a better term I'll call this a "collection-centric" or "data structure-centric" design mindset.
Collection-Centric Design Mindset
What I mean by this is take an API like this:
EXPORT Unit* unit_create(...);
EXPORT void unit_destroy(Unit* unit);

That's not a "collection" or "data structure"-centric design mindset. It's working at the granular level of allocating/creating and freeing/destroying one individual game unit at a time. And the unit_create function is giving you back a pointer to a unit that resides in "outer space": just some element residing somewhere in the memory space which the caller must now explicitly free/destroy themselves with a call to this unit_destroy function.
And sometimes you need this level of explicit memory control over an individual instance of an object. But often if you zoom out and look at the broader design requirements, especially in like a game, and for the most performance-critical parts of it (usually implying that you'll want to be creating a boatload of such instances), you'll often find these things want to belong to some central container/data structure, like a game Scene, or Map, or Board, and that it makes no sense for these Units to live anywhere else or be "owned" by anything else*.

*

*There might be some auxiliary data structures in-game which want to reference/index/point to such units, like a spatial index used to accelerate collision detection, but those structures don't "own" the elements. They refer to them, but there is still one central "owning" collection.

If that fits conceptually, then your APIs don't need to take on the form of mallocing/creating and freeing/destroying individual instances of such objects. They can take on the form of inserting and removing such objects, with the memory management being an implementation detail of the container.
EXPORT UnitHandle units_insert(Units* units, ...);
EXPORT void units_remove(Units* units, UnitHandle unit);

Furthermore you have less error-prone code when it comes to memory leaks, because the units collection can be responsible for freeing all remaining elements when the collection is destroyed, e.g.
And the implementation of this container might store all these units in a contiguous dynamic array which is only reallocated (realloc) when the number of units reaches the array capacity, only to double in size (similar to std::vector in C++). Or it might allocate blocks that store 64 elements at a time, freeing those blocks when they become empty and allocating new blocks only when all the existing blocks are full with a free list sort of approach. You can play with that to your hearts' content without breaking anything in the outside world in response to whatever hotspots you encounter because now your callers no longer depend on the idea that they allocate and free individual instances themselves. They merely request to insert and remove things to/from this container type.
That's what I recommend these days when applicable, and when applicable, it'll tend to simplify optimizations, reduce the amount of manual memory management code (and also the likelihood of human error), provide more breathing room to change implementations without changing interface designs, mitigate the temptation to get too knee-deep in gory details fiddling around with custom allocators (you consolidate the goal of efficient allocation with the data structure/collection itself, not tackle it as two disparate concerns which can get quite messy and gory if you tackle these allocators at such a generalized level, independent of any specific data structure/use case, that you're concerning yourself with alignment and thread safety and so forth), etc.
Coupling
Just a quick mention but naturally this proposed solution couples and fuses your element with its central container (or if "container" seems too high-level for your needs, you can just think of it as a "memory pool" or even "instance storage" or whatever), making the two indivisible. But I'd say it's a practical thing to do that has a lot of benefits at little practical cost.
Because what sort of practical flexibility is there to, say, decouple a pixel from the image that owns it, and allows pixels to be allocated and destroyed individually? And similarly for particles of a particle system? Because I see little, if any, but there is almost certainly a tremendous cost to such decoupling in this particular context.
So I'd say don't worry about it. If your design conceptually calls for some central container, or at least has a strong enough performance-critical need that it could benefit from an organized memory allocation/pooling strategy, then tailor your design around this idea of "insertion/removal" over "creation/destruction" or "allocating/freeing", and reap the benefits -- of which first and foremost is the elimination of the need to worry about your designs encouraging too many malloc/free calls.


text:
Q: A limit which is related to a series? How to compute the following limit which is related to a series?
$$ \lim_{N\rightarrow\infty}N^2\sum^{N-1}_{k=1}\left(\frac{k}{N}\right)^{N\ln N}$$

A: $$\lim_{N\rightarrow \infty }N^{2}\sum_{k=1}^{N-1}\left( \frac{k}{N}
\right) ^{N\ln N}=\lim_{N\rightarrow \infty }\sum_{k=1}^{N-1}N^{2}\left(
\frac{k}{N}\right) ^{N\ln N}$$
All the terms from $k=1$ to $k=N-3$ tend to $0$. The $k=N-2$ term  tends to $1$ and the $k=N-1$ term tends to infinity. So the limit doesn't exist.
$$\begin{eqnarray*}
&&\lim_{N\rightarrow \infty }N^{2}\left( \frac{k}{N}\right) ^{N\ln
N}=0,\qquad 1\le k\le N-3, \\&& \lim_{N\rightarrow \infty }N^{2}\left( \frac{N-2}{N}\right) ^{N\ln N}=1\\&&\lim_{N\rightarrow \infty }N^{2}\left( \frac{N-1}{N}\right)^{N\ln N}=+\infty  .
\end{eqnarray*}
$$
Detailed computation. Since for $p\le N$
$$\begin{equation*}
\lim_{N\rightarrow \infty }\left( 1-\frac{p}{N}\right) ^{N}=e^{-p}
\end{equation*}$$
we have
$$\begin{eqnarray*}
\lim_{N\rightarrow \infty }N^{2}\left( \frac{N-p}{N}\right) ^{N\ln N}
&=&\lim_{N\rightarrow \infty }N^{2}\left( \left( 1-\frac{p}{N}\right)
^{N}\right) ^{\ln N} \\
&=&\lim_{N\rightarrow \infty }N^{2}e^{-p\ln N} \\
&=&\lim_{N\rightarrow \infty }N^{2}N^{-p},\qquad N=e^{\ln N} \\
&=&\lim_{N\rightarrow \infty }N^{2-p}
\end{eqnarray*}$$
and
$$\lim_{N\rightarrow \infty }N^{2-p} =\begin{cases}
0,  & \text{if $p>2$ } \\
1, & \text{if $p=2$ }  \\
+\infty, & \text{if $p<2.$ }  \\
\end{cases}$$

A: The last term in the sum is $\left(1-\frac{1}{N}\right)^{N\log N}$. Since $(1-1/N)^N$ is roughly $1/e$, the last term is roughly of size $1/N$. Multiply by $N^2$.
More precisely, $\lim_{N\to\infty}(1-1/N)^N=e^{-1}$. Thus if $N$ is large enough, then $(1-1/N)^N\gt e^{-1.1}$, and therefore $(1-1/N)^{N\log N}\gt N^{-1.1}$. So the $N$-th term of our sequence is $\gt N^{0.9}$. Thus, depending on taste, the limit doesn't exist or is $+\infty$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PCRE is compiled with utf-8 support but doesn't support it While the result of pcretest -C in my server says that pcre supports utf8, but the following code always returns false even if I enter a matching pattern, and seems that it doesn't recognize utf-8 characters:
   $pattern = '/^\x{06F0}?\x{06F9}\d{9}$/u';
   if (!preg_match($pattern, $value)) { // $value is a function parameter
      return false;
   }
   return true;

Output of pcretest -C:
PCRE version 7.8 2008-09-05
Compiled with
  UTF-8 support
  Unicode properties support
  Newline sequence is LF
  \R matches all Unicode newlines
  Internal link size = 2
  POSIX malloc threshold = 10
  Default match limit = 10000000
  Default recursion depth limit = 10000000
  Match recursion uses stack

PHP version: 5.3.2
This code works as expected in my localhost.
Any suggestion?

A: Works here (note html_entity_decode's charset default changed to UTF-8 in PHP 5.4):
$ cat a.php
<?php
$pattern = '/^\x{06F0}?\x{06F9}\d{9}$/u';
var_dump(preg_match($pattern, html_entity_decode('۹123456789')));
$ php a.php
int(1)

Note that PHP, by default, doesn't use the system PCRE library (though many distros, for obvious reasons, use the system PCRE library). Type php -i and look for the PCRE section to get more information about the version your binaries use.


text:
Q: Quiz Game with multiple choice in java GUI My project is about Quiz Game but I don't know how to go to one screen to another without creating another frame. Can someone teach me or tell me on how to do it?
Here's my Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Project {

  public static void main(String[] args) {
     JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Who wants to be a Millionaire!");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setLayout(null);
    frame.setVisible(true);

    ImageIcon image = new ImageIcon("image1.png");
    JButton b1=new JButton(image);
    frame.add(b1);

    ImageIcon bg = new ImageIcon("image2.png");
    JLabel b2=new JLabel(bg);
    frame.add(b2);

    frame.setSize(1280, 800);
    b1.setBounds(400,650,414,60);
    b2.setBounds(1,1,1280,800);

    b1.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {

         frame.dispose();
         JFrame popup = new JFrame("Who wants to be a Millionaire!");
         ImageIcon q1 = new ImageIcon("question1.png");
         ImageIcon c1 = new ImageIcon("choice1.png");
         ImageIcon c2 = new ImageIcon("choice2.png");
         popup.setLayout(null);
         popup.setVisible(true);
         popup.setSize(1280, 800);

         JButton qC1=new JButton(c1);
         popup.add(qC1);
         JButton qC2=new JButton(c2);
         popup.add(qC2);
         JLabel qL1=new JLabel(q1);
         popup.add(qL1);

         qL1.setBounds(1,1,1280,800);
         qC1.setBounds(80,580,526,82);
         qC2.setBounds(650,580,526,82);

         qC1.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        JFrame correct = new JFrame("Who wants to be a Millionaire!");
        ImageIcon correct1 = new ImageIcon("correct.png");
        correct.setLayout(null);
        correct.setVisible(true);
        correct.setSize(420, 230);
        JLabel correct2=new JLabel(correct1);
        correct.add(correct2);
        correct2.setBounds(1,1,420,230);

      }});
      }
    });
  }
}

A: This is pretty ugly, but you should get the idea on how to use JFrame#get/setContentPane to switch your displayed control(s) at runtime:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public final class MainFrame extends JFrame {
    public static MainFrame instance;
    public static final Container startPage = createStartPage();
    public static final Container question1Page = createQuestion1Page();
    public static final Container correctPage = createCorrectPage();

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        instance = new MainFrame();
        instance.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        instance.setTitle("Who wants to be a Millionaire!");
        instance.setVisible(true);
        navigateTo(startPage);
    }

    static void navigateTo(Container page) {
        instance.setContentPane(page);
        instance.setSize(page.getSize());
    }

    static Container createStartPage() {
        JPanel result = new JPanel(null);
        result.setSize(1280, 800);

        //b1
        ImageIcon image = new ImageIcon("image1.png");
        JButton b1 = new JButton(image);
        b1.setBounds(400, 650, 414, 60);
        b1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                navigateTo(question1Page);
            }
        });
        result.add(b1);

        //b2
        ImageIcon bg = new ImageIcon("image2.png");
        JLabel b2 = new JLabel(bg);
        b2.setBounds(1, 1, 1280, 800);
        result.add(b2);
        return result;
    }

    static Container createQuestion1Page() {
        JPanel result = new JPanel(null);
        result.setSize(1280, 800);

        //qC1
        ImageIcon c1 = new ImageIcon("choice1.png");
        JButton qC1 = new JButton(c1);
        qC1.setBounds(80, 580, 526, 82);
        qC1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                navigateTo(correctPage);
            }
        });
        result.add(qC1);

        //qC2
        ImageIcon c2 = new ImageIcon("choice2.png");
        JButton qC2 = new JButton(c2);
        qC2.setBounds(650, 580, 526, 82);
        result.add(qC2);

        //qL1
        ImageIcon q1 = new ImageIcon("question1.png");
        JLabel qL1 = new JLabel(q1);
        qL1.setBounds(1, 1, 1280, 800);
        result.add(qL1);
        return result;
    }

    static Container createCorrectPage() {
        JPanel result = new JPanel(null);
        result.setSize(420, 230);

        //correct2
        ImageIcon correct1 = new ImageIcon("correct.png");
        JLabel correct2 = new JLabel(correct1);
        correct2.setBounds(1, 1, 420, 230);
        result.add(correct2);
        return result;
    }
}


text:
Q: Handling selection and deselection of objects in a user interface I'm writing a small audio application (in Silverlight, but that's not really relevant I suppose), and I'm a struggling with a problem I've faced before and never solved properly. This time I want to get it right.
In the application there is one Arrangement control, which contains several Track controls, and every Track can contain AudioObject controls (these are all custom user controls). The user needs to be able to select audio objects, and when these objects are selected they are rendered differently. I can make this happen by hooking into the MouseDown event of the AudioObject control and setting state accordingly. So far so good, but when an audio object is selected, all other audio objects need to be deselected (well, unless the user holds the shift key). Audio objects don't know about other audio objects though, so they have no way to tell the rest to deselect themselves.
Now if I would approach this problem like I did the last time I would pass a reference to the Arrangement control in the constructor of the AudioObject control and give the Arrangement control a DeselectAll() method or something like that, which would tell all Track controls to deselect all their AudioObject controls. This feels wrong, and if I apply this strategy to similar issues I'm afraid I will soon end up with every object having a reference to every other object, creating one big tightly coupled mess. It feels like opening the floodgates for poorly designed code.
Is there a better way to handle this?

A: One way to maintain some degree of loose coupling would be to implement the selection notification through an event.  As you say, the AudioObject controls could accept an Arrangement control in their constructors (or better yet, an IArrangement interface, so you could have multiple implementations for slightly better decoupling), and the IArrangement interface could have a RaiseItemSelected() method, which in turn raised the ItemSelected event.  All AudioObject controls would know to listen to that event, and would deselect themselves if they're not the object being selected.

A: Why not handle selection through the arrangement control? Hook up the mousedown event on each AudioObject (or just handle it entirely at the arrangement level by hittesting the click location) to the same handler in the arrangement.  Then you can just set the selection visuals off for every AudioObject and then turn it on for the one sent into the handler.  Doing it like this also makes it easier for you to maintain stuff like SelectedAudio property or a SelectionChanged event off of the arrangement control for use up the tree.
EDIT: I reread the question more closely to pick out what is going on with the arrangement vs track vs audioobject controls a little better.  Seeing the 3 layers, I would definitely handle all selection from the arrangement (unless the track control must also perform selection related activities).  I would handle the click event for the arrangement control, and when it comes in I would do a hit test on the click location and check to see if an AudioObject is in the stack.  If one is, I would just manipulate a selection collection kept at the arrangement level to have the correct data (based on key modifier or whatever).  I would have also set up an event handler on collectionchanged for that selection collection that loops through the AudioObjects in each track control, and sets their visuals depending on whether or not they are contained in the selection collection.  Set up like this, I could then also just manually manipulate the selection in code (for whatever reasons I may need) by adding/removing from the selection collection.


text:
Q: How can I apply Group Policy object (GPO)user settings in GPO only if connecting to specific users? I'm using Windows Server 2008 Enterprise Edition. How can I apply Group Policy object (GPO) user settings in GPO only if connecting to specific users?
Or to put it in another way: I want to apply a GPO to a specific user.

A: In the Security Filtering section of the GPO (on the Scope tab) remove Authenticated Users and add the user or group in question. This will make the GPO apply to only that user or group.
Take note that the GPO has to be in the Scope of Management (SOM) of the user, meaning it has to be linked to the OU or container (domain or site) where the user object exists.


text:
Q: Check if Foreign Key is used; if not -> delete I have a Model:
class Author(models.Model):
    name = models.CharField(max_length=4000)

class Book(models.Model):
    book_name = models.CharField(max_length=4000)
    author = models.ForeignKey(Author, on_delete=models.SET_DEFAULT, default=1,related_name="Author")

now, if i want to delete an author i need the system check if that pk is not used as FK in another model.
def delete_author(request, pk)
    auth = get_object_or_404(Author, pk=pk)
    ### here must check if is erasable before delete
    auth.delete()
    return render(request, '...')

For example I have 2 Author: John and Mike and 1 book: Simple_book writed by John
Author Mike can be erasable, John no
Can someone help me?


text:
Q: Matrices similarity in a bigger field $K$ Implies matrices similarity in the smaller field $F$. I have a Linear Algebra exercise and I have trouble solving a part of it.  The follwing question shows us that if $K \subseteq L$ is a field extension such that both $L,K$ are infinite ($L,K$ are fields) and $A,B \in M_n(K)$ such that $A,B$ are similar in the field $L$ (or: there exists an invertible matrix $P \in M_n(L)$ such that $PA=BP$) then $A,B$ are already similar in the field $K$ (or: there exists an invertible matrix $P \in M_n(K)$ such that $PA=BP$). I need to prove that this way:
(1). Show that every non-zero polynomial $f \in K[x_1,...,x_n]$ there exists $\lambda_1,...,\lambda_n \in K$ such that $f(\lambda_1,...,\lambda_n)\neq 0$. Do that using induction and show that this is necessary that $K$ is infinite (find a counter example for finite $K$)
(2). Suppose $f \in K[x_1,...,x_n]$ is a polynomial such that there are $\lambda_1,...,\lambda_n \in L$ such that $f(\lambda_1,...,\lambda_n) \neq 0$.  Show that there are $\mu_1,...,\mu_n \in K $ such that $f(\mu_1,...,\mu_k) \neq 0$.

(3) Assume that there exists invertible $P \in M_n(L)$ such that $PA=BP$.  Show that there exists scalars $a_1,...,a_r \in L$ and matrices $P_1,...,P_r \in M_n(K)$ such that the set $\{a_1,...,a_r\}$ is $K$-linearly independent and also $a_1P_1+...+a_rP_r = P$. Show that $P_iA = BP_i$ for all $i$.  (4) Show that there exists $b_1,...,b_r \in K$ such that $b_1P_1+...+b_rP_r$ is invertible (Hint: use (2) with $f(x_1,...,x_r) = det(x_1P_1+...+x_rP_r)$  (5) Conclude from (4) and (3) that there exists an invertible matrix $Q \in M_n(K)$ such that $QA=BQ$.
I was able to solve everything but part (3). I tried searching that in google and all I found was this: Similar matrices and field extensions  And there he just uses part (3) as guaranteed. How do I prove that?

A: Consider the finite-dimensional $K$-vector subspace $V$ of $L$ spanned by all the entries of the matrix $P$. Let $a_{1}, \dots, a_{r}$ be a basis of $V$ over $K$. Then the $(j, k)$ entry of $P$ can be written as (I use exponents for the entries of a matrix, since indices are taken for another role)
$$
P^{jk}
=
a_{1} P^{jk}_{1} + \dots + a_{r} P^{jk}_{r}
$$
for suitable $P^{jk}_{i} \in K$. Now $P_{i}$ is the matrix whose $(j, k)$ component is $P_{i}^{j k}$.
We have
$$
a_{1} (P_{1} A) + \dots + a_{r} (P_{r} A)
=
P A
=
B P
=
a_{1} (B P_{1}) + \dots + a_{r} (B P_{r}).
$$
Now consider each component of this matrix identity:
$$
a_{1} (P_{1} A)^{jk} + \dots + a_{r} (P_{r} A)^{jk}
=
a_{1} (B P_{1})^{jk} + \dots + a_{r} (B P_{r})^{jk}.
$$
Since the $a_{i}$ are independent over $K$, and the $(P_{i} A)^{jk}, (B P_{i})^{jk}$ are in $K$, this shows that $(P_{i} A)^{jk} = (B P_{i})^{jk}$ for each $i, j, k$, so that $P_{i} A = B P_{i}$ for all $i$.


text:
Q: Unable to close pygame window when try again button clicked I am making a spaceship game where you control a spaceship and fire bullets to destroy enemy spaceships. When you click the try again button when you lose, you should be able to both replay and close the game. However, even though I was able to play multiply times, I wasn't able to close the window. I think this has something to do with the if statement that checks if the try again button is clicked. Or maybe it has something to do with something else. How can I fix it so I can close the window at all times?
This is my current code:
import pygame
from pygame.locals import *
from random import randint, choice
from tools import *

pygame.init()
pygame.font.init()

SCREEN_X = 800
SCREEN_Y = 500
CENTER_POS = (400, 225)

screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y))

class Spaceship(pygame.sprite.Sprite):
    """A spaceship object. Used for the player."""

    def __init__(self, s, x, y):
        pygame.sprite.Sprite.__init__(self)

        self.screen = s
        self.x, self.y = x, y
        self.image = pygame.image.load("spaceship.png")
        self.image = pygame.transform.scale(self.image, (175, 175))
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)

    def update(self):
        """Updates the spaceship rect"""
        self.rect.center = (self.x, self.y)

class Bullet(pygame.sprite.Sprite):
    """A bullet object. Appears when the player clicks."""

    def __init__(self, s, x, y):
        pygame.sprite.Sprite.__init__(self)

        self.screen = s
        self.x, self.y = x, y
        self.image = pygame.image.load("bullet.png")
        self.image = pygame.transform.scale(self.image, (100, 100))
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)

    def update(self):
        """Let's the bullet move upward."""

        self.y -= 5
        self.rect.center = (self.x, self.y)
        if self.y < 0:
            self.kill()

class Enemy(pygame.sprite.Sprite):
    """An enemy object. The player's job is to destroy enemies."""

    def __init__(self, s, x, y, t):
        pygame.sprite.Sprite.__init__(self)

        self.type = t
        self.screen, self.x, self.y = s, x, y
        self.image = pygame.image.load(get_enemy_image()[self.type])

        # There is an if statement because the
        # N1 Galaxy Fighter and M7 Comet Glider need different sizes

        if self.type == "N1 Galaxy Fighter":
            self.image = pygame.transform.scale(self.image, (235, 215))
        elif self.type == "M7 Comet Glider":
            self.image = pygame.transform.scale(self.image, (155, 215))
        self.rect = self.image.get_rect()
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)
        self.score_given = get_enemy_given_score()[self.type]

    def update(self):
        if self.y < 0:
            self.kill()
        self.y += 3
        self.rect.center = (self.x, self.y)

class GameOverBackground(pygame.sprite.Sprite):
    """The game over background object."""

    def __init__(self, s, x, y, size=(100, 100)):
        pygame.sprite.Sprite.__init__(self)

        self.screen, self.x, self.y = s, x, y
        self.size = size
        self.image = pygame.image.load("Game_Over.jpg")
        self.image = pygame.transform.scale(self.image, self.size)
        self.rect = self.image.get_rect()

    def blitme(self):
        """Blits the game over image on the screen"""
        self.screen.blit(self.image, self.rect)

class Coin(pygame.sprite.Sprite):
    """A coin object."""

    def __init__(self, pos=(0, 0), size=(100, 100)):
        pygame.sprite.Sprite.__init__(self)

        self.x, self.y = pos[0], pos[1]
        self.size = size
        self.image = pygame.image.load("coin.png")
        self.image = pygame.transform.scale(self.image, self.size)
        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)

    def update(self):
        """Updates the coin rect"""
        self.rect.center = (self.x, self.y)

class StartButton(pygame.sprite.Sprite):
    def __init__(self, s, x, y, size=None):
        pygame.sprite.Sprite.__init__(self)

        self.screen = s
        self.x = x
        self.y = y
        self.image = pygame.image.load("start_button.png")

        if size is not None:
            self.image = pygame.transform.scale(self.image, size)

        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)

    def blitme(self):
        self.screen.blit(self.image, self.rect)

class TryAgainButton(pygame.sprite.Sprite):
    def __init__(self, s, x, y, size=None):
        pygame.sprite.Sprite.__init__(self)

        self.screen = s
        self.x = x
        self.y = y
        self.image = pygame.image.load("try_again.png")

        if size is not None:
            self.image = pygame.transform.scale(self.image, size)

        self.rect = self.image.get_rect()
        self.rect.center = (self.x, self.y)

    def blitme(self):
        self.screen.blit(self.image, self.rect)

def main():
    bg = GameOverBackground(screen, 0, 0, size=(800, 500))

    spaceship = Spaceship(screen, 400, 400)

    start_button = StartButton(screen, CENTER_POS[0], CENTER_POS[1], size=(300, 195))
    button_rect = start_button.image.get_rect(topleft=(start_button.x, start_button.y))
    game_started = False

    try_again_button = TryAgainButton(screen, CENTER_POS[0], CENTER_POS[1]+215, size=(300, 195))
    button_rect_2 = try_again_button.image.get_rect(topleft=(try_again_button.x, try_again_button.y))
    try_again = False

    bullets = pygame.sprite.Group()
    enemies = pygame.sprite.Group()
    coins = pygame.sprite.Group()

    clock = pygame.time.Clock()

    enemy_interval = 2000
    enemy_event = pygame.USEREVENT + 1
    pygame.time.set_timer(enemy_event, enemy_interval)

    coin_interval = 3500
    coin_event = pygame.USEREVENT + 1
    pygame.time.set_timer(coin_event, coin_interval)

    score = 0
    lives = 3

    with open("high_score.txt", "r") as file:
        highscore = file.read()

    font = pygame.font.SysFont("Arial", 30)
    score_text_surface = font.render("Score: {:,}".format(score), True, (0, 0, 0))
    lives_text_surface = font.render("HP: %s" % lives, True, (0, 0, 0))
    high_score_text_surface = font.render("High Score: %s" % highscore, True, (0, 0, 0))

    spaceship_collided = False

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == MOUSEBUTTONDOWN:
                if not game_started:
                    if button_rect.collidepoint(event.pos):
                        game_started = True

                if game_started is True and button_rect_2.collidepoint(event.pos):
                    try_again = True

            if game_started and event.type == MOUSEBUTTONDOWN:
                bullet = Bullet(screen, spaceship.x, spaceship.y - 20)
                bullets.add(bullet)

            if game_started and event.type == enemy_event and not lives <= 0:
                enemy = Enemy(screen, randint(-100, 725), 0, choice(["N1 Galaxy Fighter", "M7 Comet Glider"]))
                enemies.add(enemy)

            if game_started and event.type == coin_event and not lives <= 0:
                if len(coins) < 100:
                    coins.add(Coin((randint(-125, 750), randint(-200, 400))))

        screen.fill((255, 255, 255))  # DO NOT DRAW ANYTHING IN FRONT OF THIS LINE, I'M WARNING YOU

        if not game_started:
            start_button.blitme()

        if try_again:
            main()

        if game_started:
            bullets.update()

            key = pygame.key.get_pressed()
            amount = 5

            if key[pygame.K_a]:
                spaceship.x -= amount
            elif key[pygame.K_d]:
                spaceship.x += amount
            elif key[pygame.K_w]:
                spaceship.y -= amount
            elif key[pygame.K_s]:
                spaceship.y += amount

            spaceship.update()

            if not lives <= 0:
                screen.blit(spaceship.image, spaceship.rect)

            if not lives <= 0:
                bullets.draw(screen)
                enemies.draw(screen)

                coins.update()
                coins.draw(screen)

                for i in enemies:
                    i.update()
                    if pygame.sprite.spritecollide(i, bullets, True):
                        score += i.score_given
                        i.kill()

            if spaceship_collided and lives <= 0:
                bg.blitme()
                if score > int(highscore):
                    with open("high_score.txt", "w") as file:
                        file.write(str(score))

            if score >= 99999:
                score = 99999

            if not lives <= 0:
                score_text_surface = font.render("Score: {:,}".format(score), True, (0, 0, 0))
                screen.blit(score_text_surface, (590, 0))

                lives_text_surface = font.render("HP: %s" % lives, True, (0, 0, 0))
                screen.blit(lives_text_surface, (260, 0))

                high_score_text_surface = font.render("High Score: %s" % highscore, True, (0, 0, 0))
                screen.blit(high_score_text_surface, (360, 0))

            if pygame.sprite.spritecollide(spaceship, enemies, dokill=True):
                lives -= 1
                spaceship_collided = True

            if pygame.sprite.spritecollide(spaceship, coins, dokill=True):
                score += 10

        if lives <= 0:
            try_again_button.blitme()

        pygame.display.update()
        clock.tick(60)

if __name__ == "__main__":
    main()

A: You can't do it like that. Never run the main application loop recursively. The issue is

if try_again:
   main()

What you are actually doing is starting a new game within the game in progress. If you want to close the game, you will need to close all games that you have started before. Hence, you have to press close several times.
Instead of calling main recursively, you either have to reset all game states or call main in a loop.
In your particular situation, the later solution is easier to implement. Remove the recursive call but set running = False, return try_again from main and call main while it returns True:
def main():
    # [...]

    try_again = False
    running = True
    while running:
        # [...]

        if try_again:
            # main() <---- DELETE
            running = False

        # [...]

    return try_again

if __name__ == "__main__":

    keep_running = True
    while keep_running:
        keep_running = main()


text:
Q: Loading a lot of data onto Unity Editor before pushing Play button As you know, Unity Editor owns graphic model and textures in its Hierarchy.
This helps us develop games much faster: we push Play button, test code immediately, then push Stop, and modify code.
I have a big data to which to be loaded when the game starts. A lot of game information tables(not DB tables, but literally tables.) It takes a minute to load after I push Play button. If there is a way of loading the big tables before I push Play button, for example, Unity Editor loads it as it loads textures and models, I can save a lot of development time.
Is there a way of loading a big data other than models and textures onto Unity Editor, just like models and textures?

A: Go to Edit--> Preferences... ---> Cache Server then enable Cache Server by changing it from Disabled to Local or Remote depending on where you want to save it.
If you choose Remote you have to download Cache Server from here then start it and plug the IP to the IP Address input filed in Unity.

This should help save loading time when you have large resources in your project.


text:
Q: Umask In open() Syscall? While reading about open syscall and in more details the parameters we send, I read:

The umask acts as a set of
permissions that applications cannot set on files. It's a file mode
creation mask for processes and cannot be set for directories itself.
Most applications would not create files with execute permissions set,
so they would have a default of 666, which is then modified by the
umask.  As you have set the umask to remove the read/write bits for
the owner and the read bits for others, a default such as 777 in
applications would result in the file permissions being 133. This
would mean that you (and others) could execute the file, and others
would be able to write to it.  If you want to make files not be
read/write/execute by anyone but the owner, you should use a umask
like 077 to turn off those permissions for the group & others.  In
contrast, a umask of 000 will make newly created directories readable,
writable and descendible for everyone (the permissions will be 777).
Such a umask is highly insecure and you should never set the umask
to 000.  The default umask on Ubuntu is 022 which means that newly
created files are readable by everyone, but only writable by the
owner.

Can someone kindly explain what is this mask in general? I never heard of it before?

A: The umask value determinants the permissions given to a file when is created, the default permissions given to a file, after is created you can change it with chmod.
If you want to check the value setting, you have to execute the command "umask", this could tell you the value as default that the user has to create files.
If you want to change the umask value you can run the following command to set it.

umask 022

Keep in mind that the numbers that are you described in the command above are the permissions that won't give to the file, so, in this case, will be generated with 755.


text:
Q: Mount ISO image on Windows 7 You can easily open a .dmg is OS X thanks to their drive utility application. However, there is not a hint of this functionality in Windows 7.
What's the best program for mounting a .iso file in a virtual drive?
Virtual CD-ROM Control Panel (from Microsoft) seemed promising:
However, I could not install it. I moved the driver into system32/drivers, and when I browsed for it via the program, it wasn't in the drivers folder. I don't know why I thought it was promising. It's from Microsoft.
Now you see it:

Now you don't:

I promise you they're the same locations. I've made sure I can see all hidden files and folders and system files in the control panel.
Basically, if this Microsoft program is the best way to mount ISO image files in Windows 7? If so I'd like some guidance on how to install it. However, I doubt it is, I mean if its install is this flaky, nobody is using it.
What's the best third-party alternative?

A: Personally, I really like Virtual CloneDrive.

Virtual CloneDrive works and behaves just like a physical CD/DVD drive, however it exists only virtually. Image files generated with CloneDVD or CloneCD can be mounted onto a virtual drive from your hard-disk or from a network drive and used in the same manner as inserting them into a normal CD/DVD drive.

Features:

*

*Supports all common image formats such as ISO, BIN, CCD

*Supports up to 8 virtual drives at the same time

*Easy to use - just double-click an image file to mount as a drive

*Virtual CloneDrive is freeware, you may use it at no cost.


text:
Q: MIC-1 Simulation how to get started Not sure how to start this..
For the given high-level code:
c = b - a;
a = a * 2;

complete the tasks:

*

*create corresponding ijvm hexcode

*store into appropriate cells

*simulate the instructions

*show changing contents of each data cell using "/", using the notation:
< old_value > / < new_value >

A: Start by writing the equivalent instructions in IJVM. If you are using Tannenbaum's book, there is a simple example for doing a calculation like one of these statements.
Since you have to update the contents of the registers in the data path, IJVM is not sufficient. If you only had to show the contents of the stack, the IJVM would suffice. Tannenbaum has an example of how the stack changes from IJVM instructions.
Once you have the IJVM, look up the opcodes in the instruction table and change operands into offsets from LV.
You will have to take the IJVM instructions and simulate them through MIC-1. Fill in the stack and registers with initial values. Show how the values change as you step through the code, using paper and pen.


text:
Q: Print 'all' full Lists when a certain characters exist within the element of a string a = [['ab', 'cd'], ['cd'], ['cd', 'ef']

for line in a:
    if 'c' in line:
        print line

See above code. How can I print the lines that contain the character 'c'. I can only get a result if the full string within the element is present.

A: I still don't know exactly what you want but I tried covering both scenarios.
Scenario I: Get the full list which has elements consisting of character
You have a list of lists. When iterating over a, you are now accessing the second list.
With your current code, you are checking to see if c exists inside the contents of a. It obviously doesn't because a consists of another list and not string. You need to iterate over the second list and perform character existence check on it as shown below.
a = [['ab', 'cd'], ['cd'], ['cd', 'ef'], ['ar'], ['tu'], ['ip', 'cr']]

for list in a: #this loop accesses the second list
  for element in list: #this accesses the actual elements i.e. 'ab, cd' etc
    if 'c' in element:
      print list

Output
['ab', 'cd']
['cd']
['cd', 'ef']
['ip', 'cr']

Scenario II: Get the full string which consists of character
Same code as above. Replace print list with print element
Output
cd
cd
cd
cr

A: a = (['ab', 'cd'], ['cd'], ['cd', 'ef'])

for i in range(0,3):
    for j in range(0, len(a[i])):
        if 'c' in a[i][j]:
            print a[i][j]

This works if you are only trying to print the specific element within the lists; in this case the output is
cd
cd
cd

A: when iterating over a, check if character 'c' is present in joined items.
This would work if a is list of lists.
a = [['ab', 'cd'], ['cd'], ['cd', 'ef']

for item in a:
    if 'c' in "".join(item):
        print item


text:
Q: Populating a master sheet google sheets
*

*I am struggling! Is there a way to fill out information on a Template and then push a button to send the data to a row on the "Master" sheet ?? Without adding a new sheet on the bottom each time it gets populated, the data on the template doesn't need to be as detailed in the master

On Google sheets
I'm new to this, I know I need to write a code but I can't find one and don't have the time to study coding before the deadline needs completing.

A: Simple form with answers in rows in Master List
function saveFormData() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Form");
  const msh = ss.getSheetByName("Master");
  const rgl = sh.getRangeList(["B1","B2","B3","B4","B5","B6"]);
  const r = rgl.getRanges().map(r => r.getValue());
  msh.getRange(msh.getLastRow() + 1,1,1,r.length).setValues([r]);
}

Form:

A
B

1
Question1
Answer1

2
Question2
Answer2

3
Question3
Answer3

4
Question4
Answer4

5
Question5
Answer5

6
Question6
Answer6


text:
Q: Calculate the average rate of population increase per decade of a country
The population of a country increased by 20% in the first decade, 30% in the second decade and 45% in the third decade. What is the average rate of increase per decade in the population?

The answer is 31.28. The best I got was near 30 when I took the  geometric mean $(20\times30\times45)^{1/3}$ but obviously it's incorrect. Please explain briefly your answers thank you!

A: Suppose an initial (i.e. at time zero) population $P_0$ rises by $25\%$ so one year later is $P_1$. What is the relationship between $P_1$ and $P_0$? Since $P_1$ is $25\%$ higher than $P_0$, i.e. has added on $25\%$ of the value of $P_0$ onto $100\%$ of the value of $P_0$, then $P_1$ must be $125\%$ of the value of $P_0$. Written as a decimal, we can say that $P_1 = 1.25 P_0$. This factor of $1.25$ is called — among other names — the scale factor, decimal multiplier or decimal growth factor.
Suppose from year one to year two the population rises by $33.1\%$, then we could write (as a decimal) that the growth rate is $r_{1,2} = 0.331$ (here I am writing subscripts to indicate this is the growth from period one to period two) while the decimal multiplier is $1.331$; the decimal multiplier is simply $1 + r_{1,2}$. If in the third year the population falls by $20\%$, then we would write the growth rate as $r_{2,3}=-0.2$ and the decimal multiplier as $1 + r_{2,3} = 0.8$. Note that a decimal multiplier below one indicates a reduction rather than growth; from time two to time three the population has fallen from $100\%$ of its value at time two to $80\%$ of its value at time two.
What is the overall effect of these changes? Well $P_3 = 0.8P_2$, $P_2 = 1.331P_1$ and $P_1 = 1.25P_0$ so we can write that:
$$P_3 = 0.8 \times 1.331 \times 1.25 \times P_0 = 1.331 P_0$$
So we see the overall decimal multiplier is $1.331$ which indicates a $33.1\%$ increase from year zero to year three. (Effectively the $20\%$ decrease and the $25\%$ increase have cancelled each other out. This might surprise you since the $25\%$ increase sounds "bigger", but if you try a few numbers you will see that e.g. a $10\%$ increase followed by a $10\%$ decrease, or vice versa, actually results in a $1\%$ reduction overall. This is because the $10\%$ fall and $10\%$ rise were not $10\%$ of the same quantity, so will not cancel out. Note that $0.9 \times 1.1 = 1.1 \times 0.9 = 0.99$.)
Suppose there were an "average growth rate" $R$ such that the effect of that growth rate, if it acted over three years, were the same as the effect of these individual growth rates. Then we would need:
$$P_3 = (1+R)(1+R)(1+R)P_0 = (1+R)^3 P_0 = 1.331 P_0$$
From which we deduce $1+R = 1.331^{1/3} = 1.10$ and hence $R = 10\%$. We are applying the geometric mean to the decimal multipliers, not to the percentage changes themselves.
In general, if we seek an $R$ such that
$$P_3 = (1+r_{2,3})(1+r_{1,2})(1+r_{0,1})P_0 = (1+R)^3 P_0$$
then we must take
$$1+R = \sqrt[3]{(1+r_{2,3})(1+r_{1,2})(1+r_{0,1})}$$


text:
Q: Curve equidistant to sine and cosine. If I have the sine and cosine curves plotted, what would be the formula of the curve that is equidistant to both curves? Here's a picture of how it looks like.

The original question comes from a reddit post, I have worked on it for a bit but don't even know where to start.
I have no idea about how to even find the closest point on the cosine graph given a point on the sine graph. I suspect the answer would not be very nice, a closed form may not even exist.
Edit: the Reddit post: https://www.reddit.com/r/math/comments/487lfw/a_problem_that_has_been_bothering_me_for_a_while/?sort=confidence

A: Consider a point $(x_s,\sin(x_s))$ on the sin curve and a point $(x_c,\cos(x_c))$ on the cos curve. The normals to the curves at these points are:
$$y=\sin(x_c)+\cos(x_s)(x-x_s)$$
$$y=\cos(x_s)-\sin(x_c)(x-x_c)$$
Solving simultaneously gives the point of intersection $(x_i,y_i)$.
$$(x_i,y_i)=\left(\frac{\cos(x_c)-\sin(x_s)+x_s\sin(x_c)+x_c\cos(x_s)}{\sin(x_c)+cos(x_s)},\frac{\cos(x_c)\cos(x_s)+\sin(x_s)\sin(x_)+x_c\cos(x_s)\sin(x_c)-x_s\cos(x_s)\sin(x_c)}{\sin(x_s)+\cos(x_c)}\right)$$
Next we want to solve such that the distances are equal:
$$\left(\frac{\cos(x_c)-\sin(x_s)+(x_c-x_s)\sin(x_c)}{\sin(x_s)+\cos(x_c)}\right)^2+\left(\frac{\cos(x_s)(\cos(x_c)-\sin(x_s)+(x_c-x_s)\sin(x_c))}{\sin(x_s)+\cos(x_c)}\right)^2=\left(\frac{\cos(x_c)-\sin(x_s)+(x_s-x_c)\cos(x_s)}{\sin(x_s)+\cos(x_c)}\right)^2+\left(\frac{\sin(x_c)(\sin(x_s)-\cos(x_c)+(x_c-x_s)\cos(x_s))}{\sin(x_s)+\cos(x_c)}\right)^2$$
Removing denominator and factorizing gives:
$$(1+\cos(x_s)^2)(\cos(x_c)-\sin(x_s)+(x_c-x_s)\sin(x_c))^2=(1+\sin(x_c)^2)(\cos(x_c)-\sin(x_s)+(x_c-x_s)\cos(x_s))^2$$
This doesn't have a closed form for $x_s$ in terms of $x_c$ (or vice versa) so we can't express the distance in terms of just one of $x_s$ or $x_c$ let alone try to minimize it so I'm pretty confident there is no closed form for it.

A: Take a point $P=(a,b)\in [0,2\pi]\space\text{x}\space [-1,1]$; the squares of the distances of $P$ to the curves $y= \sin x$ and $y=\cos x$ are
$$D_1(x)=(x-a)^2+(\sin x-b)^2\\D_2(x)= (x-a)^2+(\cos x-b)^2$$
The extremum of these two fonctions can be got taking derivatives so
$$D_1'(x)=2x+\sin 2x-2b\cos x-2a\\D_2'(x)=2x-\sin 2x+2b\sin x-2a$$
The equations $$D_1'(x)=0\\D_2'(x)=0$$ are trascendental; furthermore, using slider control you can see that these equations can have both, just one real root or exactly three real roots. Among these roots of transcendental equations are the corresponding to the minimum of $\sqrt{D_i}; i=1,2$.
We can ensure that it is quite improbable a closed form for the searched function.


text:
Q: Python/Numpy: Combining boolean masks by row in grouped columns in multidimensional array I have a 3D boolean array (a 2D numpy array of boolean mask arrays) with r rows and c cols. In the example below the array shape is (3, 6, 2); 3 rows and 6 columns, where each column contains 2 elements.
maskArr = np.array([
                     [[True, False], [True, True], [True, True], [True, True], [True, True], [True, True]],
                     [[False, True], [False, True], [True, True], [False, True], [True, True], [True, True]],
                     [[True, False], [True, True], [True, True], [True, True], [True, True], [True, True]],
                  ])

           # If n=2:  |<-   AND   these 2 cols  ->|<-   AND   these 2 cols  ->|<-   AND   these 2 cols  ->|

           # If n=3:  |<-----       AND  these 3 cols    ----->|<-----      AND   these 3 cols     ----->|

I know I can use np.all(maskArr, axis=1) to and together all the mask arrays in each row as in previous answer, but instead I would like to and together the boolean arrays in each row in increments of n columns.
So if we start with 6 columns, as above, and n=2, I would like to apply the equivalent of np.all on every 2 columns for an end result of 3 columns, where:

*

*The first column of the result array equals the rows of the first (2) columns of the original array ANDed together - result[:,0] = np.all(maskArr[:,0:1], axis=1)

*The second column of the result array equals the rows of the second (2) columns of the original array ANDed together. - result[:,1] = np.all(maskArr[:,2:3], axis=1)

*And the third column of the result array equals the rows of the last (2) columns of the original array ANDed together. - result[:,2] = np.all(maskArr[:,4:5], axis=1)
Is there a way to use np.all (or another vectorized approach) to get this result?
Expected result with n=2:
>>>    np.array([
                     [[True, False], [True, True], [True, True]],
                     [[False, True], [False, True], [True, True]],
                     [[True, False], [True, True], [True, True]],
               ])

Note: The array I'm working with is extremely large so I'm looking for a vectorized approach to minimize performance impact. The actual boolean arrays can be thousands of elements long.
I've tried:
n = 2
c = len(maskArr[0])      ## c = 6  (number of columns)
nResultColumns = int(c / n)   ## nResultColumns = 3

combinedMaskArr = [np.all(maskArr[:,i*n:i*n+n], axis=1) for i in range(nResultColumns)]

which gives me:
>>>  [
         array([[True, False], [False, True], [True, False]]),
         array([[True, True], [False, True], [True, True]]),
         array([[True, True], [True, True], [True, True]])
     ]

The output above is not the expected format or values.
Any guidance or suggestions on how to get to the expected result?
Thank you in advance.

A: The following works, if I understood your problem correctly.
n = 2
cols = mask_arr.shape[1]
chunks = math.ceil(cols / n)
groups = np.array_split(np.swapaxes(mask_arr, 0, 1), chunks)
combined = np.array([np.all(g, axis=0) for g in groups])
result = np.swapaxes(combined, 0, 1)

If cols is divisible by n, I think this works:
n = 2
rows, cols = mask_arr.shape[0:2]
result = np.all(mask_arr.reshape(rows, cols // n, n, -1), axis=2)


text:
Q: computeRatio() method not working in newly created class Beginner Java problem. I have an assignment that requires me to create a new class and in that class is a computeRatio() method that divides variables LDL by HDL and prints out the ratio. I can't seem to get the calculation to work and print out. I'll post the code I have an the output I get. I appreciate any guidance you can give.
'public class SimonChristopher_Checkup {
private int patient;
private int systolic;
private int diastolic;
private int ldl;
private int hdl;

public static void computeRatio(int ldl, int hdl) { // Divides LDL by HDL
    // to return ratio
    double ratio = ldl/hdl;
    System.out.println("The ratio of good and bad cholesterol is " + ratio + ".");
}

public SimonChristopher_Checkup(int p, int s, int d, int l, int h) { // constructor
    patient = p;
    systolic = s;
    diastolic = d;
    ldl = l;
    hdl = h;
}

public int getPatient() { // accessor (getters)
    return patient;
}

public void setPatient(int p) { // mutator (setter)
    if (p > 0 && p <= 100) {
        patient = p;
    }
}

public int getSystolic() { // accessor (getters)
    return systolic;
}

public void setSystolic(int s) { // mutator (setter)
    if (s >= 100 && s <= 150) {
        systolic = s;
    }
}

public int getDiastolic() { // accessor (getters)
    return diastolic;
}

public void setDiastolic(int d) { // mutator (setter)
    if (d >= 50 && d <= 120) {
        diastolic = d;
    }
}

public int getLdl() { // accessor (getters)
    return ldl;
}

public void setLdl(int l) { // mutator (setter)
    {
        ldl = l;
    }
}

public int getHdl() { // accessor (getters)
    return hdl;
}

public void setHdl(int h) { // mutator (setter)
    {
        hdl = h;
    }
}

public String toString() { // mandatory convention: returns a String object
                            // representation
    String result;
    result = "Patient number: " + patient + "\n" + "Systolic: " + systolic + "\n" + "Diastolic: " + diastolic + "\n"
            + "LDL: " + ldl + "\n" + "HDL: " + hdl + "\n"
            + "HDL is known as good chloresterol. A ratio of 3.5 or better is considered optimal.";
    return result;

}

}
`
public class Simon_TestCheckup {
public static void main(String[] args) {

    SimonChristopher_Checkup patient1 = new SimonChristopher_Checkup(223, 100, 80, 105, 60);
    SimonChristopher_Checkup patient2 = new SimonChristopher_Checkup(244, 102, 76, 101, 62);

    System.out.println(patient1);
    System.out.println("--------------------------------------------------------");
    System.out.println(patient2);
}

}
    When I run TestCheckup I get the following output:
Patient number: 223
Systolic: 100
Diastolic: 80
LDL: 105
HDL: 60
HDL is known as good chloresterol. A ratio of 3.5 or better is considered optimal.
Patient number: 244
Systolic: 102
Diastolic: 76
LDL: 101
HDL: 62
HDL is known as good chloresterol. A ratio of 3.5 or better is considered optimal.

A: Few things,
Firstly, it doesn't look like you call upon computeRatio() at any time thus it will never print anything.
Secondly, I would change it to
public double computeRatio(int ldl, int hdl) { // Divides LDL by HDL
return ldl/hdl;
}

and in your toString() method add:
public String toString() { // mandatory convention: returns a String object
                        // representation
String result;
result = "Patient number: " + patient + "\n" + "Systolic: " + systolic + "\n" + "Diastolic: " + diastolic + "\n"
        + "LDL: " + ldl + "\n" + "HDL: " + hdl + "\n"
        + "The ratio of good and bad cholesterol is " + computeRatio(ldl,hdl) + ".");
        + "HDL is known as good chloresterol. A ratio of 3.5 or better is considered optimal.";
return result;
}

Also, you may want to declare hdl and ldl as doubles down the line. When you get ratio you're looking to get a double but you're dividing 2 ints. It should work as intended for now but in the future you may run into problems.


text:
Q: File Permissions - Service vs Console We have just setup a new build Windows 2008 R2 server for our Jenkins CI system. Our issue appears to be related to file permissions being different depending on whether a process is a service, or a console process.
When logged in as UserX, we can successfully do a directory listing of dir /b c:\Windows\System32\q*.exe (actual command), and it returns 6 files. However, running the same command through a service, we only get 5. Same user account. Same computer.
The bigger issue is that, because the file doesn't appear in a directory listing, it can't be executed.
There doesn't appear to be any differences in the permissions between the files that do appear, and the one that doesn't.
Any ideas?

A: We figured this problem out, so I'm posting the solution for others.
The problem was that the Jenkins slave process (the service) was running as a 32-bit process. Windows, being helpful, was automatically redirecting access to c:\Windows\System32 to c:\Windows\SysWOW64.
The executables we were looking for should have been in SysWOW64 anyway, so we copied them across, and the problem has been solved.


text:
Q: How to efficiently update a huge amount of data via code I am working on updating a huge amount of data. About 200k of data in the particular table. But I find my code inefficient and slow. Is there a way to optimize this code and make it twice or thrice faster? I am trying to convert their existing password to hashed. I tried linq before but I encounter an "Execution Timeout" issue. Until now I can't find a solution to it. The code below was the one that I am currently using.
var hashedProvider = Membership.Providers["HashedProvider"];
if (hashedProvider != null)
{
    using (SqlConnection con = new SqlConnection(System.Configuration
        .ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
    {
        con.Open();
        string sql = "SELECT Email from aspnet_membership where IsLockedOut = '0'" +
            " AND IsApproved = '1' And PasswordFormat != '1'";
        SqlCommand cmd = new SqlCommand(sql, con);
        SqlDataReader Reader = cmd.ExecuteReader();
        while (Reader.Read())
        {
            var UserName = Reader["Email"].ToString();
            MembershipUser user = Membership.GetUser(UserName);
            if (user != null)
            {
                Guid userID = new Guid(user.ProviderUserKey.ToString());
                string CurrentPassword = user.GetPassword();
                try
                {
                    UpdateUser(userID, 1);
                    var resetPassword = hashedProvider.ResetPassword(UserName, null);
                    bool Password_Changed = hashedProvider.ChangePassword(
                        UserName, resetPassword, CurrentPassword);
                    if (!Password_Changed)
                    {
                        UpdateUser(userID, 2);
                    }
                }
                catch (Exception e)
                {
                    UpdateUser(userID, 2);
                }
            }
        }
        if (Reader != null)
            Reader.Close();
    }
}

Below is the code for UpdateUser() method.
public static void UpdateUser(Guid userID, int type)
{
    for (Int32 attempt = 1; ;)
    {
        using (SqlConnection con = new SqlConnection(System.Configuration
            .ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
        {
            con.Open();
            string Sql = "UPDATE [aspnet_Membership] SET [PasswordFormat] = @Type where" +
                " UserID = @UserID";
            SqlCommand cmd = new SqlCommand(Sql, con);
            cmd.Parameters.AddWithValue("@UserID", userID);
            cmd.Parameters.AddWithValue("@Type", type);
            cmd.ExecuteNonQuery();
            break;
        }
    }
}


text:
Q: A global variable is not seen in my JavaScript function I am pretty new to JavaScript.
I am trying to build the standard "Rock, Paper, Scissors" game that will call a game winner after 5 wins of a round. So if the computer gets to 5 first, computers win, etc.
It all seems to be running OK except that once 5 wins are reached I get an error that says my variable for the playerscore or computerscore is not defined. I have it defined globally (at least I think I do) and a different part of the same function (in the "else" statement) returns these scores while they build up to 5. So I don't understand why it isn't recognized once they reach 5.
The error message is below and my code is below that. I included all my JavaScript code but I am pretty sure the issue is in the game function (the last function in the html code below).
This is the error message I receive when either the player or the computer reach 5 points.
*index_new.html:147 Uncaught ReferenceError: playerScore is not defined
    at game (index_new.html:147)
    at round (index_new.html:127)
    at HTMLButtonElement.<anonymous> (index_new.html:68)*

I have tried using "var" and "Const" instead of let but neither have fixed the issue. I have also tried to define the variable inside the function but that seems to break the score counting.
Edit
I added all my HTML and CSS code. My JavaScript is written in the HTML file in the

A: The error was because you redefined the playerScore & computerScore in the game() IF / ELSE statements, and while doing that, you had the redefined variable underneath the place where it was actually being used. So, I got rid of the redefining part of the variables, since you already defined them GLOBALLY and also moved out the score.innerHTML out of the if/else statements, theres no need of repetition it will do the same thing everytime the function is being called (on button click that is). Left a comment there in the code as well. Hopes this works properly for you as it did when I checked it out.
<!DOCTYPE html>

    <title>RockPaperScissors</title>
    <link href="palm.png" rel="icon">
    <link href="reset.css" rel="stylesheet" type="text/css">
    <link href="style.css" rel="stylesheet" type="text/css">

Wanna play Rock Paper Scissors?

Humans Vs. Computers... First to 5 wins.

(((Loser is forever dominated!!!!)))

        <button id="button1"> Rock </button>
        <button id="button2"> Paper </button>
        <button id="button3"> Scissors </button>

Score:

Humans

Computers


text:
Q: Windows 10 freeze while switching input method I'm currently using Microsoft Windows 10 Enterprise Version 1703 OS Build 15063.483.
Recently I've noticed that there's a little freeze (about 3 to 5 secs) while I switching the input method (form English to Chinese).
This issue happened on one of my computer recently (was fine/no freeze before).  All the other computers with same OS and input method installed are just fine and no freezing.
I didn't install any new software these days.  And I've tried to uninstalled/reinstalled the Chinese input method but still no help.
Is there any possible cause and solution for this?  Thanks in advance.

A: I decide to update my question since I've encountered this exactly same issue several times on different computers.  And I finally figured out the cause and fixed it.

TL;DR
  Installed too many font (several GBs) will affect certain IME performance while switching)

(All the screenshots are in Traditional Chinese since that is the language setting of my working PC.)
I've notice that my "Disk Usage" would dramatically increase while switching IME and the program freezing.  This happened every time no matter which program was freezing, including: Skype, Google Chrome, even in Windows Settings.
After some investigations, I finally found that the freezing was caused by too many (GBs) font files were loading by OS.  For my case, it's over 5 GB font files installed in my Windows 10.  I dunno why the font files need to load while switching IME.  But reducing the font files in OS solved the problem for me.
Hope this helps and thanks.


text:
Q: imported data is not showing in search OpenEmpi I am using Open Empi 3.1.0 and trying to import some files using flexible data loader. I am successfully able to import data but i am not able to search it on search window. Below are the files i used :
Sample data with tab seperated:
1   15  abc def 1963-08-25 00:00:00.0   M
1   16  hij klm 2003-07-03 00:00:00.0   F

mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<file-loader-map
xsi:schemaLocation="http://configuration.openempi.openhie.org/fileloadermap fileloadermap.xsd"
xmlns="http://configuration.openempi.openhie.org/fileloadermap"
xmlns:fl="http://configuration.openempi.openhie.org/fileloadermap"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
delimiter="\t"
header-first-line="false">
<fields>
<field
datatype="String"
is-identifier="true"
identifier-domain-name="DNO"
namespace-identifier="2.16.840.1.113883.4.1"
universal-identifier="2.16.840.1.113883.4.1"
universal-identifier-type-code="DNO">
<column-index>2</column-index>
<field-name>pid</field-name>
</field>
<field
datatype="String">
<column-index>1</column-index>
<field-name>cid</field-name>
</field>
<field
datatype="String">
<column-index>3</column-index>
<field-name>lastname</field-name>
</field>
<field
datatype="String">
<column-index>4</column-index>
<field-name>firstname</field-name>
</field>
<field
datatype="String">
<column-index>5</column-index>
<field-name>dob</field-name>
</field>
<field
datatype="String">
<column-index>6</column-index>
<field-name>gender</field-name>
</field>
</fields>
</file-loader-map>

After loading data i followed below process:

*

*Rebuild indexes

*Initialize links

*Regenerate links

*Assign global identifiers

Below is the log entries
[2016-12-19 22:59:12,751] INFO007183[pool-1-thread-5] - org.openhie.openempi.loader.SpringEntityLoaderManager.setupConnection(SpringEntityLoaderManager.java:74) - Will be doing an import instead of an add
[2016-12-19 22:59:12,752] INFO007184[pool-1-thread-5] - org.openhie.openempi.loader.SpringEntityLoaderManager.setupConnection(SpringEntityLoaderManager.java:90) - Will be doing an import for entity person
[2016-12-19 22:59:12,757] INFO007189[pool-1-thread-5] - org.openhie.openempi.loader.SpringEntityLoaderManager.setupConnection(SpringEntityLoaderManager.java:100) - Will be doing a massive import
[2016-12-19 22:59:12,762] WARN007194[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.IntentMassiveInsertImpl.begin(IntentMassiveInsertImpl.java:49) - Removing all indexes.
[2016-12-19 22:59:12,762] WARN007194[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.removeIndexes(SchemaManagerAbstract.java:560) - Droping index idx-person-givenName
[2016-12-19 22:59:13,033] WARN007465[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.removeIndexes(SchemaManagerAbstract.java:560) - Droping index idx-person-familyName
[2016-12-19 22:59:13,252] WARN007684[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.removeIndexes(SchemaManagerAbstract.java:560) - Droping index idx-person-_dirty
[2016-12-19 22:59:13,510] WARN007942[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.removeIndexes(SchemaManagerAbstract.java:564) - Droping index idx-identifier-identifier
[2016-12-19 22:59:13,861] INFO008293[pool-1-thread-2] - org.openhie.openempi.loader.FlexibleFileLoader$RecordLoaderTask.run(FlexibleFileLoader.java:633) - Loading record as: pool-1-thread-2
[2016-12-19 22:59:13,895] INFO008327[pool-1-thread-2] - org.openhie.openempi.loader.FlexibleFileLoader$RecordLoaderTask.saveRecordsInTaskList(FlexibleFileLoader.java:736) - Persisting (4/4/60062) in 32 msec.
[2016-12-19 22:59:17,412] INFO011844[pool-1-thread-2] - org.openhie.openempi.loader.FlexibleFileLoader$RecordLoaderTask.saveRecordsInTaskList(FlexibleFileLoader.java:736) - Persisting (1000/10004/78825) in 220 msec.
[2016-12-19 22:59:19,978] INFO014410[pool-1-thread-2] - org.openhie.openempi.loader.FlexibleFileLoader$RecordLoaderTask.saveRecordsInTaskList(FlexibleFileLoader.java:736) - Persisting (1000/20004/78825) in 235 msec.
[2016-12-19 22:59:32,570] INFO027002[pool-1-thread-5] - org.openhie.openempi.loader.FlexibleFileLoader.isDone(FlexibleFileLoader.java:273) - Completed the loader task: java.util.concurrent.FutureTask@215e7314
[2016-12-19 22:59:32,602] WARN027034[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.IntentMassiveInsertImpl.end(IntentMassiveInsertImpl.java:68) - Recreating all indexes.
[2016-12-19 22:59:32,604] WARN027036[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.createIndex(SchemaManagerAbstract.java:447) - Creating index: CREATE INDEX idx-person-givenName ON person (givenName) NOTUNIQUE
[2016-12-19 22:59:33,427] WARN027859[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.createIndex(SchemaManagerAbstract.java:447) - Creating index: CREATE INDEX idx-person-familyName ON person (familyName) NOTUNIQUE
[2016-12-19 22:59:33,961] WARN028393[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.createIndex(SchemaManagerAbstract.java:447) - Creating index: CREATE INDEX idx-person-_dirty ON person (_dirty) NOTUNIQUE
[2016-12-19 22:59:35,337] WARN029769[pool-1-thread-5] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.createIndex(SchemaManagerAbstract.java:447) - Creating index: CREATE INDEX idx-identifier-identifier ON identifier (identifier) NOTUNIQUE
[2016-12-19 23:00:48,979] INFO103411[pool-1-thread-4] - org.openhie.openempi.blocking.basicblockinghp.BlockingServiceImpl.rebuildIndex(BlockingServiceImpl.java:97) - Rebuilding the indices for the Traditional Blocking Service
[2016-12-19 23:00:48,983] INFO103415[pool-1-thread-4] - org.openhie.openempi.blocking.basicblockinghp.cache.BlockingServiceCache.dropBlockingClasses(BlockingServiceCache.java:206) - The round is called: BlockingRound [name=round.0, fields=[org.openhie.openempi.configuration.BaseField@6030b2e4[fieldName=patientid]]]
[2016-12-19 23:00:48,983] INFO103415[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.EntityDaoOrientdb.dropClass(EntityDaoOrientdb.java:1104) - Dropping in base class person the class: Blockinground-0
[2016-12-19 23:00:49,542] INFO103974[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.dropClass(SchemaManagerAbstract.java:218) - Class Blockinground-0 was dropped.
[2016-12-19 23:00:49,543] INFO103975[pool-1-thread-4] - org.openhie.openempi.blocking.basicblockinghp.cache.BlockingServiceCache.dropBlockingClasses(BlockingServiceCache.java:218) - BlockingServiceCache dropped classes in time: 560
[2016-12-19 23:00:49,543] INFO103975[pool-1-thread-4] - org.openhie.openempi.blocking.basicblockinghp.cache.BlockingServiceCache.createBlockingClasses(BlockingServiceCache.java:186) - The round is called: BlockingRound [name=round.0, fields=[org.openhie.openempi.configuration.BaseField@6030b2e4[fieldName=patientid]]]
[2016-12-19 23:00:49,543] INFO103975[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.EntityDaoOrientdb.classExists(EntityDaoOrientdb.java:1010) - Locating in base class person the class name: Blockinground-0
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: OTriggered in cluster -1
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: OSchedule in cluster 7
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: person in cluster 11
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: OUser in cluster 5
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: OIdentity in cluster -1
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: ORole in cluster 4
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: identifier in cluster 12
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: V in cluster 9
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: ORIDs in cluster 8
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: identifierEdge in cluster 13
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: OFunction in cluster 6
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: recordLink in cluster 14
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: E in cluster 10
[2016-12-19 23:00:49,556] INFO103988[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.isClassDefined(SchemaManagerAbstract.java:129) - Class name: ORestricted in cluster -1
[2016-12-19 23:00:49,557] INFO103989[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.EntityDaoOrientdb.createClass(EntityDaoOrientdb.java:1080) - Creating in base class person the class using definition: Entity [entityVersionId=null, entityId=null, versionId=null, name=Blockinground-0, description=null, displayName=null, dateCreated=null, userCreatedBy=null, dateChanged=null, userChangedBy=null, dateVoided=null, userVoidedBy=null]
[2016-12-19 23:00:50,390] INFO104822[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.createClass(SchemaManagerAbstract.java:238) - Class Blockinground-0 has been assigned cluster 15
[2016-12-19 23:00:50,970] WARN105402[pool-1-thread-4] - org.openhie.openempi.entity.dao.orientdb.SchemaManagerAbstract.createIndex(SchemaManagerAbstract.java:447) - Creating index: CREATE INDEX idx-Blockinground-0-blockingKeyValue ON Blockinground-0 (blockingKeyValue) NOTUNIQUE
[2016-12-19 23:00:51,562] INFO105994[pool-1-thread-4] - org.openhie.openempi.blocking.basicblockinghp.cache.BlockingServiceCache.createBlockingClasses(BlockingServiceCache.java:200) - BlockingServiceCache created classes in time: 2019
[2016-12-19 23:00:51,570] INFO106002[pool-1-thread-4] - org.openhie.openempi.blocking.basicblockinghp.cache.BlockingServiceCache.init(BlockingServiceCache.java:86) - Need to load data for this round.
[2016-12-19 23:01:02,040] WARN116472[Thread-14] - org.openhie.openempi.entity.dao.orientdb.EntityDaoOrientdb.loadRecords(EntityDaoOrientdb.java:827) - Producer loaded 10000 records.
[2016-12-19 23:01:03,762] INFO118194[Thread-15] - org.openhie.openempi.blocking.basicblockinghp.cache.BlockingServiceCache$RecordConsumerForBlocking.run(BlockingServiceCache.java:129) - Consumer Thread-15 processed 10000 records.
[2016-12-19 23:01:26,650] WARN141082[Thread-14] - org.openhie.openempi.entity.dao.orientdb.EntityDaoOrientdb.loadRecords(EntityDaoOrientdb.java:827) - Producer loaded 20000 records.
[2016-12-19 23:01:30,127] INFO144559[Thread-15] - org.openhie.openempi.blocking.basicblockinghp.cache.BlockingServiceCache$RecordConsumerForBlocking.run(BlockingServiceCache.java:129) - Consumer Thread-15 processed 20000 records.
[2016-12-19 23:01:59,731] INFO174163[pool-1-thread-4] - org.openhie.openempi.blocking.basicblockinghp.cache.BlockingServiceCache.init(BlockingServiceCache.java:95) - BlockingServiceCache init time: 70748
[2016-12-19 23:01:59,732] INFO174164[pool-1-thread-4] - org.openhie.openempi.blocking.basicblockinghp.BlockingServiceImpl.rebuildIndex(BlockingServiceImpl.java:108) - Finished building the indices for the Traditional Blocking Service
[2016-12-19 23:03:08,625] INFO243057[pool-1-thread-5] - org.openhie.openempi.matching.exactmatching.DeterministicExactMatchingService.initializeRepository(DeterministicExactMatchingService.java:234) - The deterministic matching service finished initializing the repository for entity person
[2016-12-19 23:50:32,241] WARN086673[pool-1-thread-6] - org.openhie.openempi.entity.impl.RecordManagerServiceImpl.assignGlobalIdentifier(RecordManagerServiceImpl.java:738) - Assigning global ids to block of size 10000
[2016-12-19 23:50:39,272] WARN093704[pool-1-thread-6] - org.openhie.openempi.entity.impl.RecordManagerServiceImpl.assignGlobalIdentifier(RecordManagerServiceImpl.java:738) - Assigning global ids to block of size 10000
[2016-12-19 23:50:47,023] WARN101455[pool-1-thread-6] - org.openhie.openempi.entity.impl.RecordManagerServiceImpl.assignGlobalIdentifier(RecordManagerServiceImpl.java:738) - Assigning global ids to block of size 6275
[2016-12-20 06:49:07,321] INFO201753[http-bio-8080-exec-5] - org.openempi.webapp.server.ReferenceDataServiceImpl.getSystemConfigurationInfo(ReferenceDataServiceImpl.java:216) - The system is configured with blocking algorithm: Traditional Blocking Algorithm (High Performance)
[2016-12-20 06:49:07,322] INFO201754[http-bio-8080-exec-5] - org.openempi.webapp.server.ReferenceDataServiceImpl.getSystemConfigurationInfo(ReferenceDataServiceImpl.java:219) - The system is configured with matching algorithm: Deterministic Matching Algorithm

Eveything completes without any error but i am not able to search anything .
Any help is highly appreciated.


text:
Q: In dropdown menu When we add values from database what is the id that comes to "Please select" selection? I need to write default action for the selection if user select "Please select" on dropdown menu on rails so how can I identify whether user have selected that??

A: The select helper generates an option tag with no specific value for the "Please select" entry. So the params hash gets assigned "Please select" for that param when you submit the form.

A: I'm not familiar with rails and how select boxes are handled, but in general html mark-up you could add attribute  value="0" for the "Please select" element and later check for it. If the passed value is 0 you'll know that the user failed to select something from the select box.


text:
Q: Asp.net Update Panel I am working in asp.net 3.5 and have some issue of update panel.I have some html content and Formview control in a page. I want to hide the html content when there is no data in the Formview and to show when there is data in the Formview control. My Formview control is in the updatepanel and it it is bind to SqlDataSource and Formview binds on some criteria.
If somebody know how to solve this issue then please help me.

A: If you want the HTML content to be hidden after an Ajax postback, it will need to be in an UpdatePanel, either the same one your FormView is in, or a separate one.
If it's in a separate one, you'll need some way of forcing it to update when the FormView updates. You can either do this in some code-behind, calling the Update() method of the UpdatePanel, or by adding an AsyncPostBackTrigger to the UpdatePanel containing the HTML, maybe using the DataBound event of the FormView.
Also, to easily hide the HTML content, put it in a Panel, and use the Visible property.
An example of the trigger:
<asp:UpdatePanel ID="updatePanel" ... runat="server">
   <ContentTemplate>
      ...
   </ContentTemplate>
   <Triggers>
      <asp:AsyncPostBackTrigger ControlID="formViewId" EventName="DataBound" />
   </Triggers>
</asp:UpdatePanel>

A: This issue simply resolved using the putting all the html content in the Updatepanels and on UpdatePanel_preRender event of Updatepanels check that if Gridview has data then show html content otherwise hide


text:
Q: How to show that $GCD(f,f')=(x-a_1)^{r_1-1}\cdots(x-a_l)^{r_l-1}$
Given any polynomial $f\in \mathbb C[x]$ of degree $n>0$, $f$ can be written in the form $f=c(x-a_1)^{r_1}\cdots(x-a_l)^{r_l},$ where $a_1,...,a_l$ are distinct. Also, $f'$ is the product $f'=(x-a_1)^{r_1-1}\cdots(x-a_l)^{r_l-1}H,$ where $H\in \mathbb C[x]$ is a polynomial vanishing at none of $a_1,...,a_l$.
I need to prove $GCD(f,f')=(x-a_1)^{r_1-1}\cdots(x-a_l)^{r_l-1}$, and I intend to to show that they divides each other. By the definition of GCD, RHS|LHS is easy to show. But I fail to show LHS|RHS. Any suggestions?

A: Hint: $\gcd(f,f') = (x-a_1)^{r_1-1}\!\cdots(x-a_l)^{r_l-1}\gcd(c(x-a_1)\cdots(x-a_l),H)$. The latter gcd $= 1$ since $H(a_i)\ne 0\ \Rightarrow\ H$ coprime to all $x-a_i\ \Rightarrow\ H\:$ coprime to their product by Euclid's lemma (or by unique factorization).
The essence of the matter (differentiating reduces the power of each factor $x-a$ by precisely $1$) is clear if you view a polynomial as a (formal) power series. Shifting from $x= a$ to $x= 0$, we have
$\qquad\qquad\quad\ \ \  f\: =\ c_n\: x^n + \cdots\quad\ $ has order $\:n > 0\ \ $ (i.e. $\ x^n\ | f,\ \ x^{n+1}\nmid f$)
$\qquad\qquad\Rightarrow\ f' = n c_n x^{n-1}+ \cdots\ $ has order $\:n-1\ $ since $\ n,c_n\ne 0\ \Rightarrow\ nc_n \ne 0$
which makes clear they key role played by the nonzero characteristic of the coefficient ring. Indeed,  over $\:\mathbb Z/p,\:$ for $f = x^p,\ f' = 0,\:$ so $\:\gcd(f,f') = f$.


text:
Q: How to remove files older than in a huge directory I have a directory with over 13 milion files and I want to remove some of them based on mtime, how do I do it efficiently? It's on ext4.

A: You probably won't get more efficient than:
find /dir -type f -mtime +6 -delete

To delete files older than 7 (yes, 7, not 6) days.
In any case, you'll need to do one lstat() system call on each file to determine its last modification time. Deleting a file (unlink()ing it from a directory) is expensive as it needs to edit the contents of the directory, update the directory's modification time, update the file's link count in the inode and update block/extent allocation information.
Using -delete (a GNU extension) is efficient as then the unlink() is done by find directly without having to invoke a separate rm utility. It implies -depth, but I don't expect that would make much difference in terms of performance.


text:
Q: Counteract a bootstrap / select2 rendering delay? I'm using bootstrap on a site, and using the following code on load to turn my select boxes into select2 dropdowns
$("select").select2();

However when any page with a select dropdown loads, there's a brief delay where the original can be seen before the select2 replacement is drawn in. This is quite jarring as elements of the forms on my pages move around.
Is there a way to generate the select2 HTML in my backend (ASP MVC3) and write it out to the page in such a way that the select2 plugin will still hook up all the behaviours correctly?

A: I went for a slighly simpler answer. All form elements now have style='display:none;'. On page load I simply do $('form').show()
This is at the end of any select2 commands, so the form only appears when everything else has been rendered.
In the case of lazy loaded table rows with checkboxes, I set style='display:none;' on the checkboxes and then have them show when loading is finished for a particular 'page' of results.

A: Here's a similar question on preventing flickering with Bootstrap-Select.
The fact is that a Flash of Unstyled Content (FOUC) is going to happen anytime that JavaScript is running on the client after the page has rendered and changes the appearance of the page.  You're best bet is to just minimize the changes ahead of time.
The heavy handed approach would be to wait to display the page until all the scripts have run, but this is much worse for users.
As Roryok suggested, the best way to mitigate this issue is to style the appearance of the native element as close as possible to the plugin control.
To do that, just add the following css to any select element which will be applied before the javascript renders the control.
/* apply styles to original select element before hidden */
select.select2{
  color: #444;
  background-color: #FFF;
  border: 1px solid #AAA;
  border-radius: 4px;
  box-sizing: border-box;
  cursor: pointer;
  display: block;
  height: 28px;
  padding-left: 5px;
  font: unset;
}

Demo in Stack Snippets

$('.select2').select2();
body {
  display: flex;
  flex-direction: row;
}

div {
  padding: 15px;
  display: flex;
  flex-direction: column;
}

label {
  font-weight: bold;
}

select {
  min-width: 150px;
}

.select2-theme {
  color: #444;
  background-color: #FFF;
  border: 1px solid #AAA;
  border-radius: 4px;
  box-sizing: border-box;
  cursor: pointer;
  display: block;
  height: 28px;
  padding-left: 5px;
  font: unset;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css" rel="stylesheet" />

  Select 2
  <select class="select2">
    <option>Mustard</option>
    <option>Ketchup</option>
    <option>Relish</option>
  </select>

  Select2 Themed
  <select class="select2-theme">
    <option>Mustard</option>
    <option>Ketchup</option>
    <option>Relish</option>
  </select>

  Default Select
  <select >
    <option>Mustard</option>
    <option>Ketchup</option>
    <option>Relish</option>
  </select>

A: Per @roryok's answer, CSS is rendered first so the best solution is to hide the form until after select2 loads.
However you should use visibility:hidden; rather than display:none; so Select2 can access the form input width when rendering its own DOM additons.

A: select.select2{display: none}

Works for me (at least in a horizontal form). It simply hides the search box until search2 has rendered it.

A: The best and most simple answer:
Add the existing Bootstrap class invisible to your Select2 object on the markup page, whether it's an ASP:DropDownList, HTML Input element, HTML Select element, etc: https://getbootstrap.com/docs/5.2/utilities/visibility/
This prevents the HTML version of the Select/DDL from being visible to the user, while reserving the space in the layout that the SELECT would take up (which is rendered in once the Select2 JS is initialized).


text:
Q: Addressing a WPS using Geotools' ExecuteProcessRequest I am trying to address a WPS that is running on a known machine to retrieve some isochrones. Below are excerpts from the relevant parts of the WSDL of said server:
<schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.opengis.net/wps/1.0.0">
        <element name="ExecuteProcess_xxx_isochrones">
            <complexType>
                <sequence>
                    <element minOccurs="1" maxOccurs="1" name="network_id" type="xsd:string"/>
                    <element minOccurs="1" maxOccurs="1" name="y_coord" type="xsd:float"/>
                    <element minOccurs="1" maxOccurs="1" name="x_coord" type="xsd:float"/>
                </sequence>
            </complexType>
        </element>
    </schema>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.opengis.net/wps/1.0.0">
        <element name="ExecuteProcess_xxx_isochronesResponse">
            <complexType>
                <sequence>
                    <element name="isochrones_pngResult" minOccurs="1" maxOccurs="1"/>
                    <element name="isochrones_gmlResult" minOccurs="1" maxOccurs="1"/>
                </sequence>
            </complexType>
        </element>
    </schema>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.opengis.net/wps/1.0.0">
        <element name="ExecuteProcessAsync_xxx_isochrones">
            <complexType>
                <sequence>
                    <element minOccurs="1" maxOccurs="1" name="network_id" type="xsd:string"/>
                    <element minOccurs="1" maxOccurs="1" name="y_coord" type="xsd:float"/>
                    <element minOccurs="1" maxOccurs="1" name="x_coord" type="xsd:float"/>
                </sequence>
            </complexType>
        </element>
    </schema>
    <schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.opengis.net/wps/1.0.0">
        <element name="ExecuteProcessAsync_xxx_isochronesResponse">
            <complexType>
                <sequence>
                    <element name="statusURLResult" minOccurs="1" maxOccurs="1"/>
                </sequence>
            </complexType>
        </element>
    </schema>

Here are the capabilities as retrieved from the server:
<?xml version="1.0" encoding="utf-8"?>
<wps:ExecuteResponse xmlns:wps="http://www.opengis.net/wps/1.0.0" xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsExecute_response.xsd" service="WPS" version="1.0.0" xml:lang="en-CA" serviceInstance="ourServerUrl?service=WPS&request=GetCapabilities&version=1.0.0">
<wps:Process wps:processVersion="0.1">
    <ows:Identifier>xxx_isochrones</ows:Identifier>
    <ows:Title>XXX Isochrones</ows:Title>
    <ows:Abstract>This process calculates isochrones.</ows:Abstract>
</wps:Process>
<wps:Status creationTime="2015-08-31T11:55:20Z">
    <wps:ProcessSucceeded>Process xxx_isochrones successfully calculated</wps:ProcessSucceeded>
</wps:Status>
<wps:ProcessOutputs>
    <wps:Output>
        <ows:Identifier>isochrones_png</ows:Identifier>
        <ows:Title>Isochrones PNG</ows:Title>
        <ows:Abstract>PNG showing segments of isochrones
                        for 5, 10 and 20 minutes of traveltime
                        for the chosen means of transport.
                        It reassembles the given bounding box</ows:Abstract>
        <wps:Reference href="ourServerUrl/wpsoutputs/isochrones_png-6027d3d4-4fc6-11e5-9303-005056a52e0d.png" mimeType="image/png" />
    </wps:Output>
    <wps:Output>
        <ows:Identifier>isochrones_gml</ows:Identifier>
        <ows:Title>Isochrones GML</ows:Title>
        <ows:Abstract>GML vector data consisting of segments of isochrones
                        for 5, 10 and 20 minutes of traveltime
                        for the chosen means of transport.</ows:Abstract>
        <wps:Reference href="ourServerUrl/wpsoutputs/isochrones_gml-6027d3d4-4fc6-11e5-9303-005056a52e0d.gml" mimeType="text/xml" />
    </wps:Output>
</wps:ProcessOutputs>

To address the service I am doing the following (error and exception handling removed to increase readability):
// The WeProcessingServiceManager manages a map of already instantiated services, nothing fancy.
WebProcessingService wps = WebProcessingServiceManager.getServiceFor(new URL("ourServerURL"));

ExecuteProcessRequest request = wps.createExecuteProcessRequest();
request.setIdentifier("xxx_isochrones");
request.addInput("network_id", Arrays.asList(wps.createLiteralInputValue("bicycles")));
request.addInput("x_coord", Arrays.asList(wps.createLiteralInputValue("1234567")));
request.addInput("y_coord", Arrays.asList(wps.createLiteralInputValue("1234567")));

ResponseDocumentType doc = wps.createResponseDocumentType(false, true, true, "isochrones_pngResult");
DocumentOutputDefinitionType odt = (DocumentOutputDefinitionType) doc.getOutput().get(0);
odt.setMimeType("image/png");
odt.setAsReference(true);
ResponseFormType responseForm = wps.createResponseForm(doc, null);
request.setResponseForm(responseForm);

ExecuteProcessResponse response = wps.issueRequest(request);

Unfortunately it seems that I cannot extract the desired result. I am not sure why it isn't working. I followed a very basic tutorial who doesn't explain much. I also find the documentation lacking.
Would anyone have an idea how to extract the desired result, that is, the PNG or at least the URL of the png?
To verify the service I invoke the following URL:
http://[our server URL]?
REQUEST=Execute&
IDENTIFIER=gtui_isochrones&
SERVICE=WPS&
VERSION=1.0.0&
DATAINPUTS=
network_id=pedestrian;
x_coord=682884;
y_coord=6371184

This is the response I get:
<?xml version="1.0" encoding="utf-8"?>
<wps:ExecuteResponse [namespaces and stuff] service="WPS" version="1.0.0" xml:lang="en-CA" serviceInstance="http:[our server URL]?service=WPS&request=GetCapabilities&version=1.0.0">
<wps:Process wps:processVersion="0.1">
    <ows:Identifier>xxx_isochrones</ows:Identifier>
    <ows:Title>XXX Isochrones</ows:Title>
    <ows:Abstract>This process calculates isochrones.</ows:Abstract>
</wps:Process>
<wps:Status creationTime="2015-09-02T12:46:28Z">
    <wps:ProcessSucceeded>Process xxx_isochrones successfully calculated</wps:ProcessSucceeded>
</wps:Status>
<wps:ProcessOutputs>
    <wps:Output>
        <ows:Identifier>isochrones_png</ows:Identifier>
        <ows:Title>Isochrones PNG</ows:Title>
        <ows:Abstract>PNG showing segments of isochrones
                        for 5, 10 and 20 minutes of traveltime
                        for the chosen means of transport.
                        It reassembles the given bounding box</ows:Abstract>
        <wps:Reference href="http:[our server URL]/wpsoutputs/isochrones_png-d716304a-515f-11e5-b2d0-005056a52e0d.png" mimeType="image/png" />
    </wps:Output>
    <wps:Output>
        <ows:Identifier>isochrones_gml</ows:Identifier>
        <ows:Title>Isochrones GML</ows:Title>
        <ows:Abstract>GML vector data consisting of segments of isochrones
                        for 5, 10 and 20 minutes of traveltime
                        for the chosen means of transport.</ows:Abstract>
        <wps:Reference href="http:[our server URL]/wpsoutputs/isochrones_gml-d716304a-515f-11e5-b2d0-005056a52e0d.gml" mimeType="text/xml" />
    </wps:Output>
</wps:ProcessOutputs>


text:
Q: Run a linux command php when a button is pressed
Possible Duplicate:
Running Linux Command from PHP

I have script which combines some audio files depending upon the users selection. When the user click on a button, I want a script to execute in linux and play the resulting file, that is generated.
What is the way to run a linux command when a button is pressed in PHP?