Q:

Not getting results from SpeechRecognizer class?

I have a maind UI class that has button which instantiate a class that is implementing SpeechRecognizer  library to convert speech from text.
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

        btnSpeak.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startNoiseProcessService();
            }
        });

startNoiseProcessService() is a function which is calling another class object.
public void startNoiseProcessService() {

                StreamService ss = new StreamService(this);
                String s = ss.startStreaming();
                if ( s.equals("NA") ) {
                    Toast t = Toast.makeText(getApplicationContext(),threadCnt +
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
            }

}

StreamService class implements SpeechRecognizer API.
This StreamService class is getting called perfectly fine and problem lies is I am unable to get the converted text from speech at the time after results are calculated by onResults(Bundle) method.
I need the converted text to update my textbox and I am not getting it.
startStreaming() implementation:
 public String startStreaming() {

            text = "";

            if ( !SpeechRecognizer.isRecognitionAvailable(context) ) {
                text = "NA";
                return text;
            }

            Log.d(TAG, "started taking input");
            sr = SpeechRecognizer.createSpeechRecognizer(context);

            Intent intent = new Intent(
                     RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);

            sr.setRecognitionListener( new mylistener());
            sr.startListening(intent);

     }

A:

Based on your comment, I think you can't have the results at the time sr.startListening(intent) is called. You need to get the results using the onResults method of the listener and process the text that comes inside the Bundle from there.
The way I implemented this was to have a Service in charge of handling the SpeechRecognizer. Then when onResults is called I send the text back to the original caller using a message handler. You can see details on how to do this here: https://developer.android.com/training/multiple-threads/communicate-ui.html


Q:

Will this algorithm always solve a constrained sudoku puzzle in quadratic time?

Constrained Puzzle Generation:
Let us say a sudoku puzzle is generated with the following procedure:

Gather a sequence input of 9 unique numbers in the range $[1 .. 9]$. Call it $S$.
Map $S$ to a $3 \times 3$ grid $G$ as follows:
$$G_{i,j} = \begin{cases}
S_{j} & i = 0\\
S_{j + 3} & i = 1\\
S_{j + 6} & i = 2
\end{cases}$$
Let's now call $M$ the sudoku board contained of 9 smaller $3 \times 3$ grids. (For instance $G$ will be one of these grids in the board). Define it as follows:

$$M_{i,j} = \text{shift}(G, i + 3 j)$$
Where $\text{shift}(G, 1)$ is defined as:

Move $G_{0,0}$ to $G_{0,1}$
Move $G_{0,1}$ to $G_{0,2}$
Move $G_{0,2}$ to $G_{1,0}$
Move $G_{1,0}$ to $G_{1,1}$
Move $G_{1,1}$ to $G_{1,2}$
Move $G_{1,2}$ to $G_{2,0}$
Move $G_{2,0}$ to $G_{2,1}$
Move $G_{2,1}$ to $G_{2,2}$
Move $G_{2,2}$ to $G_{0,0}$

Then define $\text{shift}(G, n) = \text{shift}(\text{shift}(G, n-1), 1)$. Basically a "shift" is moving everything one cell to the right when possible or else move it down to the leftmost position in the next row.

Now, for all present entries in a difficult puzzle (let's say world's hardest puzzle) we make the entries in $M$ present in the final output.

Example

Let's say our input is $S = [8,5,9,6,1,2,4,3,7]$.
We map $S$ to $G$ and get:

$$G = \begin{bmatrix}
8 & 5 & 9\\
6 & 1 & 2\\
4 & 3 & 7
\end{bmatrix}$$

Now we can produce $M$ with the shifts which would look like the following:

$$M = \begin{bmatrix}
8 & 5 & 9 & 4 & 3 & 7 & 6 & 1 & 2\\
6 & 1 & 2 & 8 & 5 & 9 & 4 & 3 & 7\\
4 & 3 & 7 & 6 & 1 & 2 & 8 & 5 & 9\\
7 & 8 & 5 & 2 & 4 & 3 & 9 & 6 & 1\\
9 & 6 & 1 & 7 & 8 & 5 & 2 & 4 & 3\\
2 & 4 & 3 & 9 & 6 & 1 & 7 & 8 & 5\\
3 & 7 & 8 & 1 & 2 & 4 & 5 & 9 & 6\\
5 & 9 & 6 & 3 & 7 & 8 & 1 & 2 & 4\\
1 & 2 & 4 & 5 & 9 & 6 & 3 & 7 & 8\\
\end{bmatrix}$$

Now map this onto the present entries in a difficult puzzle like this one. We get the final grid:

$$M = \begin{bmatrix}
8 &  &  &  &  &  &  &  & \\
 &  & 2 & 8 &  &  &  &  & \\
 & 3 &  &  & 1 &  & 8 &  & \\
 & 8 &  &  &  & 3 &  &  & \\
 &  &  &  & 8 & 5 & 2 &  & \\
 &  &  & 9 &  &  &  & 8 & \\
 &  & 8 &  &  &  &  & 9 & 6\\
 &  & 6 & 3 &  &  &  & 2 & \\
 & 2 &  &  &  &  & 3 &  & \\
\end{bmatrix}$$

Semi-Solver
If we assume that a sudoku puzzle was generated with this procedure we can now create a "semi"-solver. I say "semi" because we need the $3 \times 3$ grid $M_{2,2}$ already solved for us. Let's assume we have this. As an example I will assume we are provided:
$$\begin{bmatrix}
5 & 9 & 6\\
1 & 2 & 4\\
3 & 7 & 8
\end{bmatrix}$$
Now we will flatten it into: $[5,9,6,1,2,4,3,7,8]$ and permute as follows:
[8, 5, 9, 6, 1, 2, 4, 3, 7]-----list 1
[7, 8, 5, 9, 6, 1, 2, 4, 3]-----list 2
[3, 7, 8, 5, 9, 6, 1, 2, 4]-----list 3
[4, 3, 7, 8, 5, 9, 6, 1, 2]-----list 4
[2, 4, 3, 7, 8, 5, 9, 6, 1]-----list 5
[1, 2, 4, 3, 7, 8, 5, 9, 6]-----list 6
[6, 1, 2, 4, 3, 7, 8, 5, 9]-----list 7
[9, 6, 1, 2, 4, 3, 7, 8, 5]-----list 8
[5, 9, 6, 1, 2, 4, 3, 7, 8]-----list 9

Now for each list, we will turn them into a $3 \times 3$ grid using the same mapping in step 2 above. For example list 1 would get mapped to
$$\begin{bmatrix}
8 & 5 & 9 \\
6 & 1 & 2 \\
4 & 3 & 7
\end{bmatrix}$$
Now we position these in the game board the same way we did as step 3 above. For example our layout would be as follows:
**list1**  **list4**  **list7**

**list2**  **list5**  **list8**

**list3**  **list6**  **list9**

In the prior example this would give us the correct solution:
$$M = \begin{bmatrix}
8 & 5 & 9 & 4 & 3 & 7 & 6 & 1 & 2\\
6 & 1 & 2 & 8 & 5 & 9 & 4 & 3 & 7\\
4 & 3 & 7 & 6 & 1 & 2 & 8 & 5 & 9\\
7 & 8 & 5 & 2 & 4 & 3 & 9 & 6 & 1\\
9 & 6 & 1 & 7 & 8 & 5 & 2 & 4 & 3\\
2 & 4 & 3 & 9 & 6 & 1 & 7 & 8 & 5\\
3 & 7 & 8 & 1 & 2 & 4 & 5 & 9 & 6\\
5 & 9 & 6 & 3 & 7 & 8 & 1 & 2 & 4\\
1 & 2 & 4 & 5 & 9 & 6 & 3 & 7 & 8\\
\end{bmatrix}$$
Then we have list 9 (our input) will always give you correct solution in quadratic time.
Question
Will this algorithm always solve the given puzzle if we assume the puzzle input was created with these constraints?

A:

Let me start from correctness check, will this method always generate grids abiding sudoku rules?
In fact yes, your shift operator is simply circulant matrix, scattering boxes. Since circulant matrix always abide rules by row and column but not by box, you use permutation (scattering scheme), which now abide all rules, it will produce a subset of possible grids, let us call it $G$.
Now mapping $G_i$ entries to some mask (here given sudoku) is bijective, since you promise to give puzzles generated that way, and those are deterministic.
There are only $9!$ grids generated that way, as far as go either way it will always work. Please note there are 6 670 903 752 021 072 936 960 grids computed by Bertram Felgenhauer and Frazer Jarvis.
Your mapping allow to recover solution if you give 9 unique numbers from grid.
Any other puzzle provided as input will simply fail.


Q:

Excel - How to make a certain value set of numbers return different text values in another cell

I am trying to make a certain cell in excel make another cell in excel say something specific. Example using cells J15 and J16:
If cell J15 has a number value greater than or equal to 1 but less than 2, then I want cell J16 to read Unsatisfactory.
If cell J15 has a number value greater than or equal to 2 but less than 3, then I want cell J16 to read Needs Improvement.
If cell J15 has a number value greater than or equal to 3 but less than 4 . I want then Cell J16 to read Meets Expectations.
If cell J15 has a number value greater than or equal to 4 but less than 5, then I want cell J16 to read Exceeds Expectations.
If cell J15 has a number value greater than or equal to 5, then I want cell J16 to read Exceptional.
So basically depending on the number in cell J15, I need cell J16 to either read, Unsatisfactory, Needs Improvement, Meets Expectations, Exceeds Expectations, or Exceptional.

A:

You could use a formula with nested IF Statements (see below).  Your direction don't indicate how to handle the value of 1 or less, so that would return the word "FALSE" in J16.
=IF(J15>1,IF(J15<2,"Unsatisfactory",IF(J15<3,"Needs Improvement",IF(J15<4,"Meets Expectations",IF(J15<5,"Exceeds Expectations","Exceptional")))))

One or less could be handled by adding a result to the false condition of the first IF statement.
 =IF(J15>1,IF(J15<2,"Unsatisfactory",IF(J15<3,"Needs Improvement",IF(J15<4,"Meets Expectations",IF(J15<5,"Exceeds Expectations","Exceptional")))),"Your Text Here")


Q:

Mapping a value $g^x \bmod p$ to a small interval $[1...H]$

My question is in $\mathbb{Z}_p^{*}$ context, where $p=q\cdot k+1$ for two primes $p,q$ and $k \in \mathbb{Z}$; $g$ is the generator of the subgroup $G_q$ of $\mathbb{Z}_p^{*}$, of order $q$.
Let's consider a small $H$ (e.g. $H=1024$) and a specific $h \in \mathbb{Z}_p$, with $0 < h < H$, and we randomly choose $g \in \mathbb{Z}_q$: is it true (I hope it is) that it is easy to find a $x$ such that $h \equiv (g^x \bmod p) \bmod H$?
My concern is: is it possible to create a mapping from a randomly chosen $g^x \bmod p$ that can be mapped to a target (desired) value $h$ in a small range, such that we can find it easily, e.g., in $\mathcal{O}(H)$?

A:

Just sample a random $x$, and $[(g^x \bmod p) \bmod H]$ will equal your target value $h$ with probability $1/H$. After trying $O(H)$ candidates you will find a preimage.
Fine print: Technically speaking, the probability isn't exactly $1/H$. Each $h \in \mathbb{Z}_H$ has either $\lfloor \frac{p-1}{H} \rfloor$ or $\lceil \frac{p-1}{H} \rceil$ preimages under the mapping $a \in \mathbb{Z}^*_p \mapsto (a \bmod H)$. So the probability of hitting your target $h$, when you choose a random $a \in \mathbb{Z}_p^*$, is $\lfloor \frac{p-1}{H} \rfloor/(p-1)$ for some $h$'s and $\lceil \frac{p-1}{H} \rceil/(p-1)$ for others. But if $p$ is exponentially large (as I suspect it is here since you're talking about discrete logs), then this probability is negligibly close to $1/H$.


Q:

Proofs of The Fundamental Theorem of Symmetric Polynomials

I have been considering a few proofs of this theorem, and I noticed that a few of them (for example Proof 1, and Proof 2) prove the theorem first for homogeneous symmetric polynomials and then generalise it. However I have seen other proofs which don't seem to require this step (e.g. Proof 3) and it seems to me superfluous.
Could anyone explain why so many proofs include this step and/or if it is necessary?

A:

As you observe regarding "Proof 3", the lexicographic order proof (which goes back to Gauss and may be the earliest clean, clear proof of this theorem), there is no need to reduce to the homogeneous case to prove the theorem. The lex-order algorithm operates happily on any symmetric polynomial, homogeneous or not. There are many other proofs that also avoid this reduction. In fact, as you correctly sense, both your other linked proofs ("Proof 1" at PlanetMath, which is really the same lex-order proof, and "Proof 2" at Wikipedia, which I first encountered in the algebra textbooks by Serge Lang and Michael Artin) can be easily rewritten without this assumption. The theorem can also be proven non-constructively from Galois theory (as is done e.g. in the textbook by Hungerford), and in such a proof it would be kind of ridiculous to bother with the assumption of homogeneity.
However, when one wants in practice to represent a symmetric polynomial in terms of the elementary ones, one does in fact always end up working separately on each homogeneous component, for the simple reason that the elementary symmetric polynomials are themselves homogeneous. So while the reduction to the homogeneous case can be eliminated to make the exposition of the proof more economical, it cannot be eliminated from the actual calculation of a representation (of a symmetric polynomial in terms of the elementary ones).
Thus, to the constructively-minded, there is no real loss of efficiency in a proof that reduces to the homogeneous case first. If the proof is at all constructive (as are all the proofs you link), rigging it to avoid this step could be seen as a kind of deception, since when you unpack the calculations behind the proof, you must work separately on each homogeneous component. I'm guessing that's why those proofs are written that way.


Q:

For a finite set of numbers $x_1, \ldots, x_n$, how does $\frac{x_4+\frac{x_3+\frac{x_1+x_2}{2}}{3}}{4}\ldots$ differ from the mean?

I recently had an issue where a function in a programming language was taking the mean of $n$ numbers, $x_1, \ldots, x_n$ as:
$$
M_1 = \dfrac{x_4+\dfrac{x_3+\dfrac{x_1+x_2}{2}}{3}}{4}\ldots
$$
instead of the usual:
$$
M_2 = \dfrac{1}{n}\sum_{i=1}^nx_i
$$
I am wondering if there is a name for such a summation and if there is a theoretical result for how wide the deviation $M_1$ will be from the usual $M_2$? Specifically I had the case that $x_1, \ldots, x_n \in [0,1]$, but am curious about the case where $x_1,\ldots, x_n \in \mathbb{R}$ as well. I am wondering how far it might differ and in what cases results might be similar? Thanks!

A:

$$M_1(x_1, \ldots , x_n) = \sum_{k=1}^{n} \frac{(k-1)!}{n!} x_{k}$$
The sum of “weightings”:
\begin{align}
  u_n &= \frac{1}{n!}\sum_{k=1}^{n} (k-1)! \\
  (n+1) \, u_{n+1} &= 1+u_{n} \\
  (n+2) \, u_{n+2} &= 1+u_{n+1} \\
  u_{n+2} &= u_{n+1}-\frac{u_{n}}{n+2} \\
  u_1 &= 1 \\
  u_2 &= 1 \\
  u_3 &= \frac{2}{3} \\
  u_4 &= \frac{5}{12}
\end{align}
For $n > 2$, $$0<u_n<1$$

We cannot regard $M_1(x_1, \ldots , x_n)$ as a weighted mean for $n>2$.


Q:

Why would you mark an answer as Community Wiki?

My question is at least loosely related (but not identical to) this one.
Most of the answers I've seen related to Community Wiki have focused on the advantages to the community of marking something as Community Wiki. The official explanation of why you have these is "One of the goals of the website is to be a continually evolving source of good information. Community wiki posts help enhance the wiki aspect of the site." In other words, it's an advantage to the community.
My question is what the advantage of having a Community Wiki answer is to the individual. Given that you can't gain reputation for Community Wiki answers, what's the incentive to mark your own posts as Community Wiki (other than to avoid losing reputation on something that's likely to be downvoted)? I'm a little confused as to why you'd ever want to do that for a high-quality answer.

A:

My question is what the advantage of having a Community Wiki answer is to the individual.

Making you feel righteous, if your answer is merely compiled together from what already was answered by other's in comments, or your answer was banged in shape with the help of other users.

Given that you can't gain reputation for Community Wiki answers, what's the incentive to mark your own posts as Community Wiki (other than to avoid losing reputation on something that's likely to be downvoted)?

Your answer may get downvoted in situations described above, by users that think what you're doing is kind of plagiarism.

I'm a little confused as to why you'd ever want to do that for a high-quality answer.

If you have given a high quality answer based completely on your own work, I don't see much reasons why to do so.

A:

When I copy an answer directly from another user's comment, without adding any information of my own (besides the attribution), I mark it as CW. There's absolutely no requirement to do this, but personally, I don't like getting rep for other people's work, no matter how trivial.

A:

When I come across an old question where the user has edited their solution into the question, and the user is no longer around, I sometimes remove the solution from the question and repost it as a Community Wiki (with appropriate attribution).


Q:

Vertical asymptote of certain function

Define $f(x)$ in the following way $f(x)=\frac{(-1)^{[\frac{1}{x}]}}{x}$ where $[y]$ denotes the integer part of $y$. Then the limit $\lim_{x \to 0^+}f(x)$ does not exist: however the graph of this function splits into two "pieces" one approaching $+\infty$ and the other $-\infty$. Do we say that $f$ has got (say right, for left it is analogous) vertical asymptote?

A:

As per the definition from Wikipedia:
The line $x = a$ is a vertical asymptote of the graph of the function $y = ƒ(x)$ if at least one of the following statements is true:
$\lim _{x\to a^{-}}f(x)=\pm \infty\\
\lim _{x\to a^{+}}f(x)=\pm \infty$
Indeed, this is true, so we have a vertical asymptote.


Q:

Can I use Google Mobile Vision API in IntelliJ IDEA or Atom IDE?

I am exploring the APIs provided by Google. Firstly, I was experimenting with Google Cloud Vision API with Python in PyCharm in order to try to perform Optical Character Recognition (OCR) with various texts.
So I wrote a basic program in Python in PyCharm which was calling this API, I gave to it as an input an image which included text e.g. the image/photo of an ice-cream bucket and then the output was the text written on this bucket.
Now I want to test the barcode scanner of Google Mobile Vision API. ButGoogle Mobile Vision API is supported by Java and not Python so ideally I would like to call the Google Mobile Vision API in a Java program which calls this API, give as an input an image/photo of a barcode and take as an output the details saved in this barcode.
My question is if this can be (easily) done with IntelliJ IDEA or Atom IDE or if I should download Android Studio to do this simple task?
In other words, can I call easily call a mobile API in an IDE which is not specifically for mobile app development like Android Studio but it is for general java applications like IntelliJ IDEA or Atom IDE?

A:

An API is just that: a programming interface.
Source code that you want to compile against that API only needs to see that API in the class path.
In other words: the editor you are using absolutely doesn't matter here.
The only thing that matters is that you understand how to efficiently setup a "project" that includes the JARs required for that API.
Meaning: Android studio is a powerful but complex tool. You typically use it for developing mobile android apps.
Just writing a java class that uses some kind of external API is not something that requires Android Studio. Or do you think you would need to use Visual Studio when going to experiment with a JAR originating from Microsoft?!
On the part "what would be easier" - that mainly depends on your knowledge of the tool.
If somebody knows Android Studio by heart, creating the required project setup might take 1 minutes. The same person might need 5 or 10 minutes with IntelliJ.
Having said that: of course, IntelliJ is primarily designed to work as Java IDE. So setting up new projects and adding the required setup to use some JAR libraries is a straight forward task here. Atom on the other hand is even "simpler" - it basically allows you to skip that "project" part and work directly on hierarchies defined by folders.
In any case: you simply have to do a bit of research and see what works for you. Like following this answer for atom, or this extensive guide for IntelliJ.


Q:

Ultrasonic program in raspberry pi stops working after some time

Below is the code I'm running on my raspberry pi zero to detect the range by Ping))) ultrasonic.
after some time (ex: 300 pings) the program uses most of the CPU (90%) and then it stops working, is there anything wrong with my code? or the circuit might need revision.
#!/usr/bin/python3

import time
import RPi.GPIO as GPIO

#Use board based pin numbering
GPIO.setmode(GPIO.BOARD)

def ReadDistance(pin,ping_duration):

    # Set the pin to False (Low)
    GPIO.setup(pin, GPIO.OUT)
    GPIO.output(pin, False)

    # Allow module to settle
    time.sleep(0.02)

    # Send ping
    GPIO.output(pin, True)

    # Signal duration
    time.sleep(ping_duration)

    # Stop pinging
    GPIO.output(pin, False)

    # Set pin to input
    GPIO.setup(pin, GPIO.IN)

    starttime = 0
    endtime = 0

    # wait for ping echo
    while GPIO.input(pin)==0:
      starttime = time.process_time()
    while GPIO.input(pin)==1:
      endtime = time.process_time()

    # Calculate echo time
    duration=endtime-starttime

    # Distance is defined as time/2 (there and back) * speed of sound 34000 cm/s
    distance=duration*34000/2

    return distance

counter = 0;

while True:
    print (ReadDistance(11,0.00001)," t:",counter)
    counter = counter+1
    time.sleep(.5)

A:

The bug is in the following lines.
# wait for ping echo
while GPIO.input(pin)==0:
  starttime = time.process_time()
while GPIO.input(pin)==1:
  endtime = time.process_time()

You should timeout both whiles.
Otherwise occasionally the echo will have come and gone by the time the first while is executed which means it will spin on pin is 0 for eternity.


Q:

"there are no special names for each city"

I got this question: What names are most common in your hometown?
My answer:

There are traditional names like "Jake", "Jacob" and "Holmes", but they are used across the whole country, and there are no special names for each city.

How to answer this in a more idiomatic way? Also, I wonder whether the meaning which I want to convey is clear enough.

A:

I would answer. "Names like Bob and Jane are very common in my town. Names are usually used countrywide, and there are not really any special names for each city."
(Native English Speaker)


Q:

How does the usage of MVC in web development fundamentally differ from the original usage of the pattern?

I recently read an answer regarding MVC and web development, mostly about how it was originally designed for older systems and has since been applied poorly in web development. That being said, I'm sure every pattern has by now been used poorly in web development. But I'd still like to make sure that I don't make the same mistakes in applying this pattern to web development, leading myself and potentially my team into having the same bad experience with MVC.

We now deal with an obscene web-mvc hybrid that, with its awful
  buzzword status, ill definition, and having
  semi-illiterate-programmers as a target demographic, makes a really
  bad publicity to software patterns in general.
MVC, thus, became separation of concerns distilled for people who
  don't really want to think too much about it.

As someone learning about MVC and considering using it in a web application, I'd like to know from an objective perspective how the MVC pattern should be applied to web development.
It's occurred to me that web development, having pre-existing methods for rendering content via the DOM, and with JavaScript being a loosely typed language, MVC probably relates very differently to web development than it does to older systems used when it was first popularized.
Fundamentally speaking, how does the usage of the MVC pattern's (proper) usage in web development differ from its usage in a non-web environment, with strictly typed languages and no DOM and browser rules for easy GUI rendering and alteration? In other words, does the fact that we're ususing

JavaScript, a loosely typed and very different language from the ones used when the MVC pattern was designed
and use the DOM + CSS, a predefined simplified method of rendering content, whereas before web development, applications used their own rendering engines or rendering libraries to display content, perhaps making the MVC pattern more necessary

change the way we should define and use the MVC pattern in a web development environment? Are there any fundamental differences in the original usage of MVC in a non web environment and using MVC in web development?

A:

The typing or the language makes no impact whatsoever, so ignore that.
The Model is the same, as its the holder for all data that is passed on for display.
There's difference in the View - where the original constructed a GUI that was persistent, the Web equivalent constructs a GUI each time a request is made from the client browser. However, both are doing the same kind of work (roughly) - constructing a view, its just that one is persistent and the other transient. Operations on one directly call the controller to manipulate elements, whereas the other has a browser as a 'proxy' for this, only calling the controller when links are clicked that require a refreshed view.
This suggests the Controller part is the main difference - whereas the original used this to route messages to event handlers to manipulate the GUI elements, the web version is more concerned with routing the request for a view.
So I would say there's little difference from a conceptual point of view, though big differences in implementation, but then you could say this about a MVC system created using C++ MFC and another created using Swift and Cocoa for example. I imagine you could create a MVC desktop system that recreated the GUI display every time a link was pressed (and could say this happens anyway, if you click a button that pops up a dialog, its creating a brand new view for you). Similarly, persistence of data is the same - lots of thick GUIs write directly to a database, and although they don't fetch state for every request, using session state or not isn't exactly a fundamental aspect of MVC.


Q:

How to segregate turtles in NetLogo in a specific region

Is it possibile, in NetLogo, to create a sort of fenced area (corral) in which I can isolate n sick turtles (not unlimited) while sane turtles can't access it?
If yes, how can I move sick turtles there? And how can I prevent sane turtles from getting there?

A:

What i've done is isolating a bunch of patches.
Say your origin point is in the center of your frame. And your max-xcor is 30 and your max-ycor is 30 too.
Take this map as a reference.

Say now that sick turtles must be in the first quadrant and healthy turtles must be in the third quadrant.
You want to ask turtles with sick status to face the upper right corner. This would be coordinates (30,30)  then they should check if they are in the designated area. If not, keep moving forward. Since you want them to segregate around the first quadrant you want to make a procedure to make them move randomly once they're in there.
Same goes for healthy turtles, ask them to face coordinates -30,-30 and then ask them to go forward a random number of steps, then they should check if they are in the designated area. If not, keep moving forward.

How to prevent sick turtles from getting in sick turtle's area?

Ask every healthy turtle which their coordinates are, if these coordinates are very close to sick turtle's area, make them face the other way (say random coords).

How to know if they're very close to sick turtle's?

With an if!
Ifelse [turtles.coordinateX + 5 >= 30 && turtle.coordinateY + 5 >= 30] [true][false] < This means they're close by 5 patches!

Rewrite that in netlogo of course.
There's a lot of help here too. http://ccl.northwestern.edu/netlogo/docs/


Q:

How to get most significant n bits from int in java

I have an int, and I would like to get the 19 most significant bits in java. I tried all sorts of methods, none of them work.
Can someone please help me?

A:

Adding to Bram's answer, you don't even need the AND if you use unsigned shift.
myInt >>> 13; will give you the 19MSB (although they're now situated in the lowest bits).

A:

From the 32 bit int, you want to keep the 19 most significant, so discard the 13 least; then you shift right by 13 bits, but have to get rid of the possible sign extension, by anding with a 19 bit pattern:
(myint >> 13) & 0x7ffff


Q:

Add JavaScript using CSS 'Content' Style

I have a certain web application with a page that is procedurally generated using table data from a database, and the only customization I have over how it functions is with the CSS that's used to stlye the results.
I'd like to know if it's possible to insert a javascript action into part of the page using a CSS content style.
As an example, it would look something like the below:
.actioncatalogwrapper:after{
    content: (Javascript here);
}

I have some questions about how this would function, though:

Do I need to escape quotes in my Javascript, to use it inside of a Content style?
Is what I'm asking for even possible? What would this look like, if not exactly pasting the javascript as the data for the content style?

The script looks like the below:
<script type="text/javascript">
  $('ul ul').hide();
  $('.description').hide();
  $('h2').click(function() {
    $(this).siblings().slideToggle();
    $('ul ul ul').slideDown();
    $(this).parent().siblings().children().next().slideUp();
  });
</script>

A:

This is not possible.
See the spec: https://www.w3.org/TR/CSS21/generate.html#propdef-content

Generated content does not alter the document tree. In particular, it
  is not fed back to the document language processor (e.g., for
  reparsing).


Q:

CDPieMenu (cocoapod) in swift

I'm trying to add CDPieMenu to my swift project using a .podspec gist I found here.
I downloaded the podspec locally & added it to my podfile like so:
  pod 'CDPieMenu', :path => '~/Documents/Project/CDPieMenu.podspec'

Here's the podspec:
Pod::Spec.new do |s|
    s.name     = 'CDPieMenu'
    s.version  = '0.1'
    s.license  = 'MIT License'
    s.summary  = 'Fully and easily customizable rotary wheel control also called pie menu for iPhone and iPad.'
    s.homepage = 'https://github.com/wczekalski/CDPieMenu'
    s.author   = { 'W. Czekalski'    => 'me@wczekalski.com' }

    s.source   = { :git => 'https://github.com/wczekalski/CDPieMenu.git', :commit => '2f49362' }
    s.source_files = 'Wheel'

    s.description = 'Fully and easily customizable rotary wheel control also called pie menu for iPhone and iPad.'
    'Very similar to the control in Convertbot. As the only one in the internet it rotates with inertia/mementum.'
    'Drawn using CoreGraphics without any images.'

    s.platform = :ios
    s.frameworks = 'AudioToolbox', 'QuartzCore'
    s.requires_arc = true
end

I ran pod update and everything worked fine and it seems to have been installed.
However, I'm unable to reference it from my project files now.
Did I miss something?
EDIT 1:
I forgot to mention I have already setup a bridging-header and added CDPieMenu headers to it.
Project-bridging-header:
#import "CDCircle.h"
#import "CDCircleGestureRecognizer.h"
#import "CDCircleOverlayView.h"
#import "CDCircleThumb.h"
#import "CDIconView.h"
#import "Common.h"

EDIT 2:
I just checked and it seems the pod isn't installed at all. There isn't a CDPieMenu in the Pods directory.
But pod update didn't throw any errors.

A:

I had two problems here, one of which I was able to resolve using @whatever38's suggestion, i.e. I was using pod update instead of pod install.
The other problem was that I needed to specify the path to my podspec file in my Podfile. I was doing this by specifying the :path => parameter, whereas I should've instead used the :podspec => parameter.
So, my Podfile entry for CDPieMenu should look like so:
pod 'CDPieMenu', :podspec => '~/Documents/Project/CDPieMenu.podspec'


Q:

ERROR: "4.9E-324" is out of range for type double precision

I saw this error when trying to perform the following insert into a PostgreSQL 8.4.20:
java.sql.BatchUpdateException: Batch entry 12 insert into perf_raw_2017_03_16 values ('3129', '182', '818', '2017-03-20 16:01:17.507000 +00:00:00', '4.9E-324') was aborted.  Call getNextException to see the cause.
org.postgresql.util.PSQLException: ERROR: "4.9E-324" is out of range for type double precision

However, when I try the same insert on a different machine with PostgreSQL 8.4.4, the insert finishes fine. When I do a select to verify that the value is there, it also finishes fine:
select * from perf_raw_2017_03_20 where guid_key=3129 and property_key=182;

 guid_key | property_key | instance_id_key |       time_stamp        |         value
----------+--------------+-----------------+-------------------------+-----------------------
     3129 |          182 |             818 | 2017-03-20 16:01:17.507 | 4.94065645841247e-324

The type of the column is double precision, which, according to the documentation, is "15 decimal digits precision". The error makes sense, I am indeed outside of its range, so I am not very surprised by the error. Here are my questions though:
The binary format of the DB does not change with minor releases. Why did this even work in 8.4.4 and not 8.4.20?
I did not find anything in the changelog that would explain this:
https://bucardo.org/postgres_all_versions.html
Why does the DB still allow me to insert the value if I use a select to get it from an existing record?
I will probably post an answer to this question based on what I observed, but it would be cool if somebody could provide a deeper insight into this issue.

A:

You're asking for software that was EOL in July 2014. It's far from supported. I'm not sure I trust git on those releases. The work transferring over the repo may have been sloppy. You may have to go back to SVN to get an authoritative answer but this seems to be responsible...

On some platforms, strtod() reports ERANGE for a denormalized value (ie,
  one that can be represented as distinct from zero, but is too small to have
  full precision).  On others, it doesn't.  It seems better to try to accept
  these values consistently, so add a test to see if the result value
  indicates a true out-of-range condition.  This should be okay per Single
  Unix Spec.  On machines where the underlying math isn't IEEE standard, the
  behavior for such small numbers may not be very consistent, but then it
  wouldn't be anyway.
Marti Raudsepp, after a proposal by Jeroen Vermeulen

You can see the thread about this here.


Q:

Simple Unsubscribe Script

Possible Duplicate:
Simple PHP Mailer Script

i run a small website and we have had requests for a mailing list....
i have found a simple free script to add email addresses to a txt file - "email.txt" (which is protected) is csv format (email1@yahoo.com,email2@yahoo.com,blah,blah,blah)
this script works flawlessly.....
however it is a nuciance to go through this text file to manually remove email addresses when users cancel their subscription to the mailing list.....
i am having trouble creating a simple script to remove email addresses....
so far i have ....

    <form method="post" action="">

Email Address: <input type="text" name="email">

    <input type="submit" value="Cancel Newsletter" name="submit">
    </form>

    <?php

    $email = $_POST["email"];

    $text = file_get_contents("email.txt");

    $oldWord = "$email";

    $newWord = "";

    $text = str_replace($oldWord , $newWord , $text);

    $fp = fopen('email.txt', 'w');
     fwrite($fp, $text);

    fclose($file);

     ?>

this works perfect to remove the email address from the list.....
however i cannot figure out how to echo a comment dependant on whether
    str_replace($oldWord , $newWord , $text);

is successful at replacing the email address with an empty space....
if the code removes email address i would like "You Have Been Removed From The Flying Shuttle Newsletter."
and if the email address isnt there (code doesnt replace email with empty space)
"The Email Address You Specified Is Not On The Mailing List!"
thanks in advance for any help

A:

You could just compare the length of the returned string.
$newText = str_replace($oldWord, $newWord, $text);
if (strlen($newText) < strlen($text)) {
  // Success
} else {
  // Failure
}


Q:

How to add the emojicon library in chatting android application?

I 'm using this library rockerhiue emojicon but tell me the programming step by step.

A:

there are enough examples on Github
or check is out
. it's written in chinese. be prepared


Q:

How to show only hidden directories, and then find hidden files separately

I'm trying to list all the hidden files in a directory, but not other directories, and I am trying to do this using only ls and grep.
ls -a | egrep  "^\."

This is what I have so far, but the problem is that it also lists hidden directories, when I don't want that.
Then, completely separately, I want to list the hidden directories.

A:

To list only hidden files:
ls -ap | grep -v / | egrep "^\."

Note that files here is everything that is not a directory. It's not file in "everything in Linux is a file" ;)
To list only hidden directories:
ls -ap | egrep "^\..*/$"

Comments:

ls -ap lists everything in the current directory, including hidden
ones, and puts a / at the end of directories.
grep -v / inverts results of grep /, so that no directory is included.
"^\..*/$" matches everything that start with . and end in /.
If you want to exclude . and .. directories from results of the second part, you can use -A option instead of -a for ls, or if you like to work with regex, you can use "^\.[^.]+/$" instead of "^\..*/$".

Have fun!

A:

To list the hidden files and directories in the current directory, including . and ..:
echo .*

To list the hidden files and directories in the current directory and its subdirectories recursively:
find . -name '.*'

If you want to save the results to a file, use a redirection:
find . -name '.*' >output-file.txt


Q:

SAS EG DATE/TIME IN WHERE CLAUSE

I need to use a date/timestamp field in my where clause where it is >today()1pm
I'm setting it up to be a scheduled task, so the "today()" part is important
I dont know how to combine that with the time piece though
all I could come up with was this- and it seems like very inefficent code if it even works
datepart(fielda)=today() and timepart(fielda)>01:00:00pm

I need to be able to say here are the items with a timestamp of "today" after "1pm"
*I am passing my sql to an underlying database.

A:

If you're using PROC SQL directly (not pass-through) you can use the SAS dhms function:
proc sql noprint;
  * Assume myData contains a var named datestamp;
  create table selected as
    select * from myData
    where datestamp > dhms(today(), 13, 0, 0)
  ;
quit;

The function constructs a datetime value from the supplied Date, Hour, Minutes and Seconds values, hence dhms.
This won't work if your SQL is being passed through to the underlying database because it's unlikely to understand the dhms function.


Q:

Cutting SciPy hierarchical dendrogram into clusters on multiple threshold values

I would like to cut my SciPy's dendrogram into a number of clusters on multiple threshold values.
I've tried using fcluster but it can cut only on one threshold value.
(Here is a piece of code which I have taken from another question for example.)
import pandas

data = pandas.DataFrame({
'total_runs': {0: 2.489857755536053, 1: 1.2877651950650333, 2: 0.8898850111727028, 3: 0.77750321282732704, 4: 0.72593099987615461, 5: 0.70064977003207007, 6:0.68217502514600825,7: 0.67963194285399975, 8: 0.64238326692987524, 9:0.6102581538587678, 10: 0.52588765899448564, 11: 0.44813665774322564, 12: 0.30434031343774476, 13: 0.26151929543260161, 14: 0.18623657993534984, 15: 0.17494230269731209,16: 0.14023670906519603, 17: 0.096817318756050832, 18:0.085822227670014059, 19: 0.042178447746868117, 20: -0.073494398270518693,21: -0.13699665903273103, 22: -0.13733324345373216, 23: -0.31112299949731331, 24: -0.42369178918768974, 25: -0.54826542322710636,26: -0.56090603814914863, 27: -0.63252372328438811, 28: -0.68787316140457322,29: -1.1981351436422796, 30: -1.944118415387774,31: -2.1899746357945964, 32: -2.9077222144449961},
'total_salaries': {0: 3.5998991340231234,1: 1.6158435140488829, 2: 0.87501176080187315, 3: 0.57584734201367749, 4: 0.54559862861592978, 5: 0.85178295446270169,6: 0.18345463930386757, 7: 0.81380836410678736, 8: 0.43412670908952178, 9: 0.29560433676606418, 10: 1.0636736398252848, 11: 0.08930130612600648, 12: -0.20839133305170349, 13: 0.33676911316165403, 14: -0.12404710480916628, 15: 0.82454221267393346,16: -0.34510456295395986, 17: -0.17162157282367937, 18: -0.064803261585569982, 19: -0.22807757277294818, 20: -0.61709008778669083,21: -0.42506873158089231, 22: -0.42637946918743924, 23: -0.53516500398181921, 24: -0.68219830809296633, 25: -1.0051418692474947,26: -1.0900316082184143, 27: -0.82421065378673986, 28: 0.095758053930450004, 29: -0.91540963929213015, 30: -1.3296449323844519,31: -1.5512503530547552, 32: -1.6573856443389405}
})

from scipy.spatial.distance import pdist
from scipy.cluster.hierarchy import linkage, dendrogram

distanceMatrix = pdist(data)
dend = dendrogram(linkage(distanceMatrix, method='complete'),
       color_threshold=4,
       leaf_font_size=10,
       labels = df.teamID.tolist())

Dendrogram
So for above dendrogram I would like to make a cut at 3 for Green cluster but for Blue & Red cluster cut should be made at 5 (so both of them comes in a single cluster).

A:

The method fcluster can do this with monocrit parameter, which allows you to pinpoint exactly where to cut on the dendrogram. You want to make cuts at positions -1 and -3, where -1 is the top of the tree and -3 is the third node (where blue meets green) counting from the top down. This is how:
Z = linkage(distanceMatrix, method='complete')
monocrit = np.zeros((Z.shape[0], ))
monocrit[[-1, -3]] = 1
fc = fcluster(Z, 0, criterion='monocrit', monocrit=monocrit)

The flat clusters will be formed by performing separation only at nodes with values strictly greater than the threshold (which is 0).
To illustrate this, I first redo the dendrogram with numbered leaves:
dend = dendrogram(Z, color_threshold=4, leaf_font_size=10, labels = range(33))

and then print the flat clusters:
for k in range(1, 4):
    print(np.where(fc == k))

They are
(array([30, 31, 32]),)
(array([12, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]),)
(array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 13, 15]),)

So, green is split in two and red and blue are together.


Q:

What is the work around for TYPE_KEYGUARD now that it's been removed?

I've successfully disabled the notification bar from appearing by using the following code and now I need to upgrade to version 21 of the SDK.
    @Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}

However, now I'm getting "cannot find symbol TYPE_KEYGUARD".  Does anyone have a workaround for this?

A:

Apparently, it's a simple change:
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);


Q:

Why is a space required in Regex when part of match is optional?

I have been looking for noun phrases (noun, plus optional determiner, plus multiple optional adjectives). I wrote this long and terrible bit:
import argparse, re, nltk
def get_words(tagged_sentences):
words = re.findall(r'\w*\.*\,*/', tagged_sentences)
clean_word = []
for word in words:
    word = word[:-1]
    clean_word.append(word)
# return clean_word
return ' '.join(clean_word)

noun_phrase = re.findall(r'(\w*/DT\s\w*/JJ\s\w*/NN)|(\w*/DT\s\w*/JJ\s\w*/NN)|(\w*/DT\s\w*/JJ\s\w*/NNP)|(\w*/DT\s\w*/JJ\s\w*/NNPS)|(\w*/JJ\s\w*/NNS)|(\w*/JJ\s\w*/NN)|(\w*/JJ\s\w*/NNP)|(\w*/JJ\s\w*/NNPS)|(\w*/DT\s\w*/NNS)|(\w*/DT\s\w*/NN)|(\w*/DT\s\w*/NNP)|(\w*/DT\s\w*/NNPS)|(\w*/NNS)|(\w*/NN)|(\w*/NNP)|(\w*/NNPS)', tagged_sentences)
    phrases = []
for word in noun_phrase:
    phrase = get_words(str(word))
    phrases.append(phrase)
return phrases

At first, I was trying to use .* after the NN or the JJ, but that didn't work. What was I doing wrong? I did something like (\w*/DT\s\w*/JJ.* \s\w*/NN.*) to account for all the different ways words could be tagged as (Adjectives can be JJ,JJR,JJS while Nouns can be NN,NNS,NNP,NNPS)
pos_sent = 'All/DT good/JJ animals/NNS are/VBP equal/JJ ,/, but/CC some/DT animals/NNS are/VBP more/RBR equal/JJ than/IN others/NNS ./.'

Then I saw this:
noun_phrase = re.findall(r'(\S+\/DT )?(\S+\/JJ )*(\S+\/NN )*(\S+\/NN)', tagged_sentences)

I liked it because it is way better in every way to what I first did. BUT I don't understand why the spaces are required after 'DT', 'JJ', and the first 'NN'(but cannot be there after the second 'NN'). I am not even sure why the two NN 'finds' cannot be placed into one.
I also preferred to use \w to \S, because it should be real letters not just not white space. Anyway, help understanding WHY would very much be appreciated.

A:

Ok, here is your example text:
All/DT good/JJ animals/NNS are/VBP equal/JJ ,/, but/CC some/DT
animals/NNS are/VBP more/RBR equal/JJ than/IN others/NNS ./.

And this is your regular expression you want to understand:
r'(\S+\/DT )?(\S+\/JJ )*(\S+\/NN )*(\S+\/NN)'

Let's take it one group at a time:
(\S+\/DT ) matches 'All/DT ' and 'some/DT '
(\S+\/JJ ) matches 'good/JJ ' and 'equal/JJ '
(\S+\/NN ) matches nothing
(\S+\/NN) matches 'animals/NN' and 'others/NN'
You're using re.findall(), but that doesn't mean find all of these groups, it means consider the entire regex and find all occurrences of the entire pattern. In addition to the groups, it's key that note that the because of the question mark, your first pattern (\S+\/DT ) is optional. Because of the asterisks, your second (\S+\/JJ ) and third (\S+\/NN ) patterns will match zero more times. Thus, they are also effectively optional and the only thing required is your last pattern (\S+\/NN).
A quick test looks like this
import re
s = 'All/DT good/JJ animals/NNS are/VBP equal/JJ ,/, but/CC some/DT animals/NNS are/VBP more/RBR equal/    JJ than/IN others/NNS ./.'
pat = r'(\S+\/DT )?(\S+\/JJ )*(\S+\/NN )*(\S+\/NN)'
res = re.findall(pat, s)
for i, g in enumerate(res):
    print('{}: {}'.format(i, g))

which gives this output:
0: ('All/DT ', 'good/JJ ', '', 'animals/NN')
1: ('some/DT ', '', '', 'animals/NN')
2: ('', '', '', 'others/NN')

If we remove the spaces,
pat2 = r'(\S+\/DT)?(\S+\/JJ)*(\S+\/NN)*(\S+\/NN)'
res2 = re.findall(pat2, s)
for i, g in enumerate(res2):
    print('{}: {}'.format(i, g))

the output will be exactly what you'd expect,
0: ('', '', '', 'animals/NN')
1: ('', '', '', 'animals/NN')
2: ('', '', '', 'others/NN')

i.e., only the required ones match. Your question is why? I think the issue is that you may feel you are issuing a series of patterns to look for, but you are looking for a single pattern that has multiple match groups. In other words, your regular expression requires these pattern to exist in the order you specify. If they aren't there, then sure, it doesn't matter that they are ordered, but if they are there, they have to be ordered exactly as the regex specifies.
So with the spaces (\S+\/DT )?(\S+\/JJ ), matches 'All/DT good/JJ ' because it literally says match 1 or more non whitespace characters plus a forward slash plus DT plus a space followed by 1 or more whitespace characters plus a forward slash plus 'JJ'. Without the spaces (\S+\/DT)?(\S+\/JJ), the match would require either that the entire (\S+\/DT ) pattern NOT be there, or that if it IS there, it's definitely does NOT contain a space after 'DT'.
I think the key is that you're matching the entire sequence. Without the space, it simply doesn't match the text anymore. If you want these patterns to be considered independently, you will need to use the pipe symbol (|) to indicate OR between your pattern groups.


Q:

Should I use the same name for a member variable and a function parameter in C++?

I am wondering if it is a good practice to use the same name for both a member variable and a function parameter in C++.
I come from a Java background, where this was common. I am wondering if in C++ there are drawbacks doing the following (the code works):
class Player
{
    public:
    void setState(PlayerState *state)
    {
        this->state = state;
    }

    private:
       PlayerState *state;
}

Thank you for the answers. As I understand while it works, a better practice would be to put some kind of marker to differentiate member variable from function parameters like:
 _ or m_

In some editors (like Qt Designer), member variables are shows in a different color. This is why it did not seem necessary to add any prefixes.

A:

That is correct, and allowed by the Standard. But a better approach is to use some naming-convention for member variables. For example, you could use m_ prefix for all member variables, then anyone could infer what m_state is. It increases the readability of the code, and avoids common mistakes.
Also, if m_state is the member, then you don't have to write this->m_state  = state in the member function, you could just write m_state = state. In your current code, this-> part becomes necessary, without which state = state will become self-assignment.

A:

Normally people just put an underscore after the variable or use shorter less descriptive var names for the function parameter.
I personally do not like the same name thing because when reading it, it is easy to make mistakes.

A:

I find it a good choice to give member variables the same name as constructor initialization parameters.
Here are my reasons:

reduces the number of identifiers, hence reduces the complexity
you don't need to invent so many identifiers
same things should have same name if possible, that is logically speaking, I know
parameter != member
contexts and indices can allow to give the same name to the same thing
you more easily find references (identifiers) to the logical thing by searching,
if all references have the same name


Q:

How to compare one file's data to other file's data using python?

I have 90 files in csv format which have data like this-
    PID,          STARTED,%CPU,%MEM,COMMAND
    1,Wed Sep 12 10:10:21 2018, 0.0, 0.0,init
    2,Wed Sep 12 10:10:21 2018, 0.0, 0.0,kthreadd

Now I have to compare in such a way that whether file2 has any repeting data(PID,STARTED,%CPU,%MEM,COMMAND)with file1 or not.
If file2 has repeated data then pick the repeated data with all values(PID,COMMAND,STARTED,%CPU,%MEM) and store it in a seperate files.
Same explained process I have to do with all 90 files.
My code(Approach) is here. Please have a look -
file=open(r"Latest_27_02_2019.csv","r")
pidList=[]
pNameList=[]
memList=[]
startTimeList=[]
df=pd.read_csv(file)
pidList=df.index
df.columns = df.columns.str.strip()
pidList = df['PID']
pNameList=df['COMMAND']
memList=df['%MEM']
startTimeList=df['STARTED']
After that compare one by one.

But since I have large number files. So it will take more time and more iteration.
Somehow I have found that it can be do in easier way with help of python(pandas library) but don't know how? Please help me?

A:

here is the solution for comparing 2 files:
#read file1 to df1
#your header seems no good with blank, so i rename it
df1 = pd.read_csv('file1',  sep=',' header=1, names=['PID','STARTED','%CPU','%MEM','COMMAND']])
#df1 is your first file, df2 the second
df_compare = df1.merge(df2.drop_duplicates(), on=['PID','STARTED','%CPU','%MEM','COMMAND'],
                   how='right', indicator=True)

print(df_compare)

#in result, you'll have a column '_merge' with both or right_only
#right_only means only in df2 and not in df1
#after you just filtered:

filter = df_compare._merge == 'both'
df_compare = df_compare[filter].drop(['_merge'],axis=1)

#in df_compare, you have the repeateted rows from df2 and df1, you could reindex if you want
print(df_compare)

or another solution (better i think):
df_compare = df1[df1.index.isin(df1.merge(df2, how='inner', on=['PID','STARTED','%CPU','%MEM','COMMAND']).index)]
print(df_compare)


Q:

Removing trailing whitespace with awk

I'm trying to get and print some system information off my Mac using the system_profiler command. I'm able to get the information just fine but for each item there's a leading space and trailing newline (I think). The problem is the trailing newline (or whatever's there). Here's an example of one of the commands I'm using:
system_profiler SPHardwareDataType | awk -F: '/Processor Speed/ {gsub(/^[ \t]+|[ \n]+$/, "", $2); print $2}'

Here's the result:
2.5 GHz

It doesn't show up here but there's some sort of character on the end that causes a newline. The gsub that I have above correctly removes the space at the beginning of the result but I've tried everything I can think of to remove the newline but nothing's worked.
To see the newlines in action, run system_profiler > output from the terminal and open the output file in your favourite text editor and show invisible characters.
What I'm ultimately trying to do with this information I'm grabbing is print my basic computer information using a TextExpander snippet. I have all of the snippets set up and running correctly but I'm having problems with the newline characters as explained above.
Here's the output currently:
Model:  MacBookPro9,2

OS Version: Mac OS X
 10.8.3
 (12D78
)
Processor:  2.5 GHz
  Intel Core i5

Graphics:  Intel HD Graphics 4000
  512 MB

Storage:  APPLE SSD SM128E Media

Memory:  8 GB

And here's what I want it to look like:
Model: MacBookPro9,2
OS Version: Mac OS X 10.8.3 (12D78)
Processor: 2.5 GHz Intel Core i5
Graphics: Intel HD Graphics 4000 512 MB
Storage: APPLE SSD SM128E
Memory: 8 GB

TextExpander allows you to run any shell script so if there's any other way I can get the functionality I want I'll gladly use it. (i.e. I've done some searches and I've seen sed mentioned among other things but I really don't know anything about shell scripting).
Thanks!

A:

print adds a newline.
Use printf, instead, if you don't want the newline:
system_profiler SPHardwareDataType | awk -F: '/Processor Speed/ {
    gsub(/^[ \t]+|[ \n]+$/, "", $2)
    printf "%s", $2
}'

It doesn't show up here but there's some sort of character on the end that causes a newline.

To demonstrate things like this, I use cat -vet, viz:
% system_profiler SPHardwareDataType | awk -F: '/Processor Speed/ {gsub(/^[ \t]+|[ \n]+$/, "", $2); print $2}' | cat -vet
2.13 GHz$


Q:

Error on compilation on c++ : Undefined reference to

I am trying to compile a C++ file in MPI but it is not working.It says:
main.cpp:(.text+0x35d): undefined reference to `Complex::Complex(double, double)'
main.cpp:(.text+0x384): undefined reference to `Complex::Complex(double, double)'
main.cpp:(.text+0x3a5): undefined reference to `Complex::multiply(Complex*)'
main.cpp:(.text+0x3b7): undefined reference to `Complex::add(Complex*)'
main.cpp:(.text+0x3cf): undefined reference to `Complex::modul()'
/tmp/ccoIbWIN.o: In function `f2(int)':
main.cpp:(.text+0x53d): undefined reference to `Complex::Complex(double, double)'
main.cpp:(.text+0x580): undefined reference to `Complex::Complex(double, double)'
main.cpp:(.text+0x5a1): undefined reference to `Complex::multiply(Complex*)'
main.cpp:(.text+0x5b3): undefined reference to `Complex::add(Complex*)'
main.cpp:(.text+0x5cb): undefined reference to `Complex::modul()'
collect2: ld returned 1 exit status

Here is Complex.h:
#include <math.h>
#include <iostream>

using namespace std;

class Complex{
    public:
        Complex();
        Complex(double real,double imag);
        ~Complex();
        double real,imag;
        double modul();
        void multiply(Complex *t);
        void add(Complex *t);
        void toString();

};

Here is Complex.cpp:
#include "Complex.h"

Complex::Complex(){
    this->real = 0;
    this->imag = 0;
}

Complex::Complex(double real,double imag){
    this->real = real;
    this->imag = imag;
}

Complex::~Complex(){}

double Complex::modul(){
    double realM = this->real*this->real;
    double imagM = this->imag*this->imag;
    return realM + imagM;
}

void Complex::multiply(Complex *t){
    this->real = this->real*t->real - this->imag*t->imag;
    this->imag = this->real*t->imag + this->imag*t->real;
}

void Complex::add(Complex *t){
    this->real = this->real + t->real;
    this->imag = this->imag + t->imag;
}

And here is the main:
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <fstream>
#include "mpi.h"
#include "Complex.h"

using namespace std;

int tip,MAX_STEPS,width,height,iteratie;
double x_min,x_max,y_min,y_max,rezolutie,julia1,julia2;
int thread,*matrice,*buffer;
int nr_linii,add_master;
int i = 0, j = 0;

void f1(int rank){
    Complex *z,*c;
    for(double y = y_min; y < y_max; y += rezolutie){
        for(double x = x_min; x < x_max; x += rezolutie){
            z = new Complex(0,0);
            c = new Complex(x,y);
            iteratie = 0;
            while(z->modul() < 4 && iteratie < MAX_STEPS){
                z->multiply(z);
                z->add(c);
                iteratie ++;
            }
        matrice[i*width + j] = iteratie % 256;
        j++;
         }
    j = 0;
    i ++;
    if((i == nr_linii && rank != 0) || (i == height && rank == 0))
        break;
    }
}

void f2(int rank){
    Complex *z,*c;
    c = new Complex(julia1,julia2);
    for(double y = y_min; y < y_max; y += rezolutie){
        for(double x = x_min; x < x_max; x += rezolutie){
            z = new Complex(x,y);
            iteratie = 0;
            while(z->modul() < 4 && iteratie < MAX_STEPS){
                z->multiply(z);
                z->add(c);
                iteratie ++;
            }
        matrice[i*width + j] = iteratie % 256;
        j++;
        }
    j = 0;
     if ((i == nr_linii && rank != 0) || (i == height && rank == 0))
                break;
        }
}

int main(int argc,char *argv[]){
    //more code that doesn't depend on f1 or f2
    ......
    // here i want to use the function f1 or f2
    if(tip == 0){
        f1(rank);

    } else {
        f2(rank);
    }

 return 0;
}

Why it says "undefined reference to Complex:: ".What it is wrong?
Can you help me?Thanks.

A:

You're not getting a compiler error, you're getting a linker error. Make sure that the complex.cpp output (usually complex.o) can be found by the linker (ld).
You probably just need to ensure that complex.cpp is part of your compiler command line:
mpic++ main.cpp complex.cpp -o main


Q:

Rounding float up to first non-zero value

guys, I have some very little floats and I want to round it up to first not nil value.
For example:
float toRound = 0.000002125231553;
toRound = //Operations//;

toRound == 0.000002;

Have you any ideas?

A:

perhaps not the best approach. but it does what you want ;)
float s = 0.000322333123;
BOOL exit = 0;
NSString *x = [NSString stringWithFormat:@"%f", s];
for (int i = 0; i <= [x length]; i++) {
NSString *t = [x substringToIndex:i];

if ([t floatValue] == 0 || exit == 1) {
    ;;
}
else {
    exit = 1;
    s = [t floatValue];
}
}

NSLog(@"round: %f", s);

Log: round: 0.0003


Q:

Data Type Conversion Error while trying to dynamically add columns(fields) from excel in MS-Access database using Python

I'm trying to populate the 1st row(i.e. the column names) from an excel sheet to the ms-access database, but it's giving me 'Data type conversion Error(3421)'. Any idea why this is happening ?
from comtypes.client import CreateObject
from xlrd import open_workbook,cellname
import os
from comtypes.gen import Access

access = CreateObject('Access.Application')

DBEngine = access.DBEngine

db = DBEngine.CreateDatabase('test.mdb', Access.DB_LANG_GENERAL)

excel_file = open_workbook('test_excel_file.xlsx')
work_sheet = excel_file.sheet_by_index(0)

db.BeginTrans()
db.Execute("CREATE TABLE MY_TABLE (ID Text)")

for row_index in range(0, 1):
    for col_index in range(0, work_sheet.ncols):
        cell_value = work_sheet.cell(row_index,col_index).value
        db.Execute("ALTER TABLE MY_TABLE ADD COLUMN %s", cell_value)

db.CommitTrans()
db.Close()

Error:
Traceback (most recent call last):
File "My_DB_Code.py", line 21, in <module>
db.Execute("ALTER TABLE MY_TABLE ADD COLUMN %s", cell_value)
_ctypes.COMError: (-2146824867, None, (u'Data type conversion error.', u'DAO.Dat
abase', u'jeterr40.chm', 5003421, None))

A:

A parameterized query allows parameters to be substituted for the values of a column, but not for table and column names themselves. You will need to use string formatting for that, as in
db.Execute("ALTER TABLE MY_TABLE ADD COLUMN [{0}] TEXT(50)".format(cell_value))


Q:

VK API Как скачать видео со стороннего ресурса?

Видеоролики, которые расположены на сторонних ресурсах, ВК отдает без прямых ссылок, а именно на само видео. Например, если видео с YouTube, то ссылка ведет на страницу с этим видео. Скачивание не работает, вернее качается файл .html с подсказкой включить JavaScript. Как тогда скачать файл? Замечаю, что некоторые видео залиты не только на YouTube, например, на RuTube. Тем не менее название сайта содержится в ответе JSON. Тоесть можно в зависимости от него вызывать разные алгоритмы для закачки. Тогда где можно узнать полный список всех возможных ресурсов? И, вообще, может есть какое-то готовое решение?

A:

Взбесили приложения, в которых эта функция недоступна, разрабы очень ленивые и, к тому же, говнокодеры (посмотрите на длительность, они перевели секунды в миллисекунды зачем-то). Прикладываю скриншоты

Нашел сайт - http://getvideo.at
Его API. X3 как, но получилось наобум, может это где-то написано, но я не нашел, странно, что GET запрос)
http://getvideo.at/search?q=ссылка

В качестве ссылки можно указать любой URL даже с YouTube. Сервер отдаст JSON обьект с прямыми ссылками, по которым и надо качать видео со сторонних ресурсов.
P.S Google, sorry
UPD
Подключился! Volley не работал, так как на сайте какая-то проблема с сертификатами. Пришлось писать HttpUrlConnection в ... AsyncTask :( Кому интересно - скину код


Q:

How do I convert a Peekable iterator back to the original iterator?

I want to implement an algorithm that skips ! or !^num at the start of a string:
fn extract_common_part(a: &str) -> Option<&str> {
    let mut it = a.chars();
    if it.next() != Some('!') {
        return None;
    }
    let mut jt = it.clone().peekable();

    if jt.peek() == Some(&'^') {
        it.next();
        jt.next();
        while jt.peek().map_or(false, |v| !v.is_whitespace()) {
            it.next();
            jt.next();
        }
        it.next();
    }
    Some(it.as_str())
}

fn main() {
    assert_eq!(extract_common_part("!^4324 1234"), Some("1234"));
    assert_eq!(extract_common_part("!1234"), Some("1234"));
}

playground
This works, but I can not find way to return from Peekable to Chars, so I have to advance it and jt iterators. This causes duplicate code.
How can I return from Peekable iterator to corresponding Chars iterator, or maybe there is a simpler way to implement this algorithm?

A:

In short, you cannot. The general answer is to use something like Iterator::by_ref to avoid consuming the Chars iterator:
fn extract_common_part(a: &str) -> Option<&str> {
    let mut it = a.chars();
    if it.next() != Some('!') {
        return None;
    }

    {
        let mut jt = it.by_ref().peekable();

        if jt.peek() == Some(&'^') {
            jt.next();
            while jt.peek().map_or(false, |v| !v.is_whitespace()) {
                jt.next();
            }
        }
    }

    Some(it.as_str())
}

The problem is that when you call peek and it fails, the underlying iterator has already been advanced. Getting the rest of the string will lose the character that tested false, returning 234.
However, Itertools has peeking_take_while and take_while_ref, both of which should solve the issue.
extern crate itertools;

use itertools::Itertools;

fn extract_common_part(a: &str) -> Option<&str> {
    let mut it = a.chars();
    if it.next() != Some('!') {
        return None;
    }

    if it.peeking_take_while(|&c| c == '^').next() == Some('^') {
        for _ in it.peeking_take_while(|v| !v.is_whitespace()) {}
        for _ in it.peeking_take_while(|v|  v.is_whitespace()) {}
    }

    Some(it.as_str())
}

Other options include:

using a crate like strcursor which is designed for this kind of incremental advance over a string.
do the parsing on regular strings directly, and hope the optimizer eliminates redundant bounds checks.
Use a regex or other parsing library


Q:

Why "__getattr__" does not work in python "ctypes"?

I stop it in the example of "datetime", is rewritten in a real example of lxml.
(It may be strange because English is translated in Google Translate is my statement I'm sorry.)

It is thought that I like lxml from very good performance, but the source is hard to read.
If you are actively using the XML, I do frequently can also be modified code of python.
Time has passed since forgotten, source because very difficult to understand,
I have taken the time to debug and fix.
For example, I think usually when you search as follows: deep XML hierarchy.
elem = lxml.etree.parse ("xxx/xxx/sample.xml").getroot()

elem.xpath("//depth3/text()")[0]

elem.find("./depth1/depth2/depth3").get("attr1").text

I wanted to use as follows.
(Use this code it's just me.)
elem.depth3.text (Ex.1)
OR
elem.depth1.depth2.depth3.text (Ex.2)

I tried the class inheritance is first to implement this.
You have customized a little bit by referring to the "Using custom Element classes in lxml".
I used the __getattr__ in order to search an XML element.
from lxml import etree
class CustomElement (etree.ElementBase):
    def __ getattr__ (self, k):
        ret = self.xpath ("/ /" + k)
        setattr(self, k, ret)
        return getattr(self, k)

Example of (Ex.1) to succeed.
But the example of (Ex.2) becomes Attribute Error __getattr__ is not present in the instance of the return of etree._Element depth1.

Although not (supplemental) practical, but I used an example of adding a "millisecond" of "datetime" in the first question from Easy to understand.

It was thought then it was a way to add functions to the Element class of lxml using the ctypes module.
import ctypes
import lxml.etree

class PyObject_HEAD(ctypes.Structure):
    _fields_ = [
        ('HEAD', ctypes.c_ubyte * (object.__basicsize__ -
                           ctypes.sizeof(ctypes.c_void_p))),
        ('ob_type', ctypes.c_void_p)
    ]
def __getattr__(self, k):
    ret = self.xpath("//" + k)
    setattr(self, k, ret)
    return getattr(self, k)

_get_dict          = ctypes.pythonapi._PyObject_GetDictPtr
_get_dict.restype  = ctypes.POINTER(ctypes.py_object)
_get_dict.argtypes = [ctypes.py_object]

EE = _get_dict(lxml.etree._Element).contents.value
EE["__getattr__"] = __getattr__

elem = lxml.etree.parse("xxx/xxx/sample.xml").getroot()
elem.xpath("//depth3")[0]

=> Return _Element object
from ispect import getsource
print getsource(elem.__getattr__)

=>def __getattr__(self, k):
=>    ret = self.xpath("//" + k)
=>    setattr(self, k, ret)
=>    return getattr(self, k)
sources is added..
elem.depth3

=> AttributeError .. no attribute 'depth3'

I do not know if or should I write how using the "PyObject_GetAttr".
Please tell me if.
Best regards
====================Previous Question===================================
I'm trying to enhancements in ctypes.
Add function usually go well.
However, it does not work if you add a special method and Why?
import ctypes as c

class PyObject_HEAD(c.Structure):
    _fields_ = [
        ('HEAD', c.c_ubyte * (object.__basicsize__ -
                              c.sizeof(c.c_void_p))),
        ('ob_type', c.c_void_p)
    ]

pgd = c.pythonapi._PyObject_GetDictPtr
pgd.restype = c.POINTER(c.py_object)
pgd.argtypes = [c.py_object]

import datetime

def millisecond(td):
    return (td.microsecond / 1000)

d = pgd(datetime.datetime)[0]
d["millisecond"] = millisecond

now = datetime.datetime.now()
print now.millisecond(), now.microsecond

This prints 155 155958, Ok!
def __getattr__(self, k):
    return self, k

d["__getattr__"] = __getattr__

now = datetime.datetime
print now.hoge

This doesn't work, why?
Traceback (most recent call last):
  File "xxxtmp.py", line 31, in <module>
    print now.hoge
AttributeError: type object 'datetime.datetime' has no attribute 'hoge'

A:

PyObject_GetAttr (Objects/object.c) uses the type's tp_getattro slot, or tp_getattr if the former isn't defined. It doesn't look up __getattribute__ in the MRO of the type.
For a custom __getattr__ you'll need to subclass datetime. Your heap type will use slot_tp_getattr_hook (Objects/typeobject.c) as its tp_getattro. This function will look for __getattribute__ and __getattr__ in the type's MRO by calling _PyType_Lookup (Objects/typeobject.c).

Given your update, see "using custom Element classes in lxml". For multiple results I've hacked a __getattr__ hook that uses a suffix notation for the index. It defaults to index 0 otherwise. Admittedly I haven't given it much thought, but clashes with existing names can be avoided if you always use the index.
from lxml import etree

def make_parser(element):
    lookup = etree.ElementDefaultClassLookup(element=element)
    parser = etree.XMLParser()
    parser.setElementClassLookup(lookup)
    return parser

class CustomElement(etree.ElementBase):
    def __getattr__(self, attr):
        try:
            name, index = attr.rsplit('_', 1)
            index = int(index)
        except ValueError:
            name = attr
            index = 0
        return self.xpath(name)[index]

parser = make_parser(CustomElement)

For example:
>>> spam = etree.fromstring(r'''
... <spam>
...     <foo>
...         <bar>eggs00</bar>
...         <bar>eggs01</bar>
...     </foo>
...     <foo>
...         <bar>eggs10</bar>
...         <bar>eggs11</bar>
...     </foo>
... </spam>
... ''', parser)

>>> spam.foo_0.bar_0.text
'eggs00'
>>> spam.foo_0.bar_1.text
'eggs01'
>>> spam.foo_1.bar_0.text
'eggs10'
>>> spam.foo_1.bar_1.text
'eggs11'


Q:

Why list monad combines in that order?

I was reading about list monads and encountered:
[1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)

it produces
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]

Here's how I understand it:
Implicit parentheses are:
([1,2] >>= \n -> ['a','b']) >>= (\ch -> return (n,ch))

([1,2] >>= \n -> ['a','b']) should give [('a',1),('b',1),('a',2),('b',2)]
because
instance Monad [] where
  return x = [x]
  xs >>= f = concat (map f xs)   -- this line
  fail _ = []

so concat (map f xs) is concat (map (\n -> ['a','b']) [1,2]) which should produce [('a',1),('b',1),('a',2),('b',2)] - quite the opposite of the actual output.
Then I don't understand >>= (\ch -> return (n,ch)) part - I think that n here has no sense. That specific reasoning is flawed, could you please explain how that expression([1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)) is computed step-by-step?

A:

Your implicit parentheses are wrong.  The way you have it, the n parameter to the first lambda would not be in scope in the return.  It is more like:
([1,2] >>= (\n -> ['a','b'] >>= (\ch -> return (n,ch))))

Which becomes:
concatMap (\n -> concatMap (\ch -> [(n,ch)]) ['a','b']) [1,2]

A:

No, you're using wrong parenthesization. It's nested to the right, so that
[1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch)
=
[1,2] >>= (\n -> ['a','b'] >>= (\ch -> return (n,ch) ))
=
do { n <- [1,2]
   ; do { ch <- ['a','b']
        ; return (n,ch) }}
=
for n in [1,2]:              -- pseudocode
    for ch in ['a','b']:
        return (n,ch)
=
[ r | n <- [1,2], ch <- ['a','b'], r <- [(n,ch)] ]    -- return == (:[])
=
[ (n,ch) | n <- [1,2], ch <- ['a','b'] ]
=
pure (,) <*> [1,2] <*> ['a','b']      -- using list applicative
=
[(1,'a'), (1,'b'), (2,'a'), (2,'b')]

and the innermost list is "spinning" the fastest, like in a car's odometer.
You are absolutely right, with the wrong parenthesization the n binding would make no sense. It is precisely for that reason that it must associate to the right, to make the nested binding possible; for the nested computations are the essence of the monad:
[ foo x   | x <- xs ]           -- functor : amendable computations
[ bar x y | x <- xs AND y <- ys ]     -- applicative : combinable computations
[ baz x y | x <- xs, y <- foo x ]         -- monad : reinterpretative computations

(and yes, omitting parentheses in learning material is the root of all evil... not really, but still...)

A:

Implicit parentheses are:
([1,2] >>= \n -> ['a','b']) >>= (\ch -> return (n,ch))

This is wrong. \ has  the lowest precedence and thus extends to the end of the expression. So the parentheses are:
[1,2] >>= (\n -> ['a','b'] >>= (\ch -> return (n,ch)))

([1,2] >>= \n -> ['a','b']) should give [('a',1),('b',1),('a',2),('b',2)]

As you can see from the above parenthesization ([1,2] >>= \n -> ['a','b']), isn't actually a subexpression of the given expression. But if it were, its result would be ['a', 'b', 'a', 'b']. n is not actually used anywhere in the expressions ['a', 'b'], so there's no way the numbers could appear in the result.

Then I don't understand >>= (\ch -> return (n,ch)) part - I think that n here has no sense.

Given your parenthesization n would indeed be undefined there. However given the proper parenthesization it should be clear where n comes from: We're still inside the \n -> ... function, so n still refers to the argument of that function, namely the current element of the [1, 2] list.


Q:

Appropriate goodness of fit measure for signal with unknown errors

I have a signal (voltage vs time) from a measurement device. The device outputs exactly one datapoint every constant time interval dt. Theoretical reasons lead me to suppose that the data is following a hyperbolic curve $f(x)= \frac{mx}{k+x}$. Using scipy I performed a fit to the data using the curve_fit function (which does a least squares fit).
I asking myself what would be an appropriate goodness of fit measurement if I don't know the error of the data. Additionally, is it possible to get an estimate of the parameter uncertainty?
I first thought about a Chi-squared test (see my question Chi squared test for goodness of fit ) but there the errors (at least in y) should be known.

A:

If you estimate the curve parameters (i.e. $m$ and $k$) using least squares, then you are implicitly using the root-mean-squared error as the misfit metric (i.e. objective to be minimized).
In general for a regression problem you hypothesize a model of the form
$$y=f_\theta(x)+\epsilon$$
where $(x,y)$ is the observed data, $f_\theta$ is a function depending on unknown parameters $\theta$, and $\epsilon$ is an unknown pointwise error (with expected value zero). Generally the parameters $\theta$ are estimated by minimizing some function of the residuals, $r=y-f_\theta(x)$.
In the case of least squares, this is $E(r)=\overline{(r^2)}$, so the "RMSE" corresponds to an estimated standard deviation of the error term (computed over the sampled residuals). If the errors $\epsilon$ are normally distributed, then least squares is a maximum-likelihood estimator of the parameters.
In your case, the errors appear to have some outliers (around $t=0.5$), which will inflate the error-scale estimate (and possibly bias the parameter estimate). You could mitigate this by using a robust estimate for the residual-dispersion (either as a post-processing, or as part of a robust regression scheme). In any case, while a single-number summary is convenient, it is always good to also inspect the residual distribution (both vs. time, and the bulk PDF).
For parameter uncertainty, a simple approach would be bootstrapping. This will also have the benefit of showing the impact of any outliers (as these will be less likely to be included in bootstrap samples).


Q:

Matching an object somewhere in a Scala List

I'm trying to pattern match on a Scala list with a pattern that will match if an object of the desired type is contained anywhere within the list.
I tried:
case _ :: (something: DesiredSubclass) :: _ => ???

But this only matches if there is at least one element before the one that I'm looking for.

A:

Use an if guard along with the exists higher order method.
case xs if xs.exists(_.isInstanceOf[DesiredSubclass]) => ???

A:

Use of overt isInstanceOf[SomeType] is unsightly. Using the match-like PartialFunction literal notation is preferable:
list.exists { case _: DesiredSubclass => true; case _ => false }


Q:

Scala batch processing triggered by size or time

I'd like to batch up some events for processing, and have the triggering of the processing for a batch be based on the number of events reaching a certain threshold OR a time interval expiring (whichever happens first).  What should I consider?  Futures?  Akka?  Some more special-purpose library that might exist?

A:

Two options come to mind:

Using Akka
Using Quartz

This depends on your specific architecture, but you can use any form of scheduling. You can use an Akka scheduler to schedule a task to run regularly and use your own internal queue to trigger the batch job if it's full. You can also do very similar things with Quartz but you might have to write more boilerplate code with the benefit of having more flexibility.
If you don't wish to bring in a fairly heavyweight library, I suppose you could implement something yourself, but you would be reinventing the wheel.


Q:

jQuery Timer for click event

We have a facts page on our website with the following code:

<button class="facts-button1">Fun Fact #1</button>
<button class="facts-button2">Fun Fact #2</button>
<button class="facts-button3">Fun Fact #3</button>
<button class="facts-button4">Fun Fact #4</button>
<button class="facts-button5">Fun Fact #5</button>
<button class="facts-button6">Fun Fact #6</button>

<?php $lang_code = icl_object_id(15,'page', true, ICL_LANGUAGE_CODE); ?>

<?php the_field( "fact_1", $lang_code );  ?>

<?php the_field( "fact_1", $lang_code);  ?>

<?php the_field( "fact_2", $lang_code );  ?>

<?php the_field( "fact_3", $lang_code );  ?>

<?php the_field( "fact_4", $lang_code );  ?>

<?php the_field( "fact_5", $lang_code );  ?>

<?php the_field( "fact_6", $lang_code );  ?>

What we would like to do is to make it a timed event. So that the facts change every 5 seconds, but still has the click funtion as it has now. Does anyone know a way to do this?

A:

Use setInterval function for initiating a click on every 5 seconds
var i=1;
setInterval(function(){
jQuery(".facts-button"+i).click();
i++;
if(i==7)
 i=1;
}, 5000);


Q:

How to format a Python string to resemble a dictionary using .format()?

I have a python variable containing the string A and another one containing the string B.
I want to generate the string which represents the dictionary containing the aforementioned two strings as a key value pair. How can I do it? Using nested curly brackets inside a string literal seems not to work. But I need that notation to use .format()
>>> x = "A"
>>> y = "B"
>>> assert(eval('\{"{}": "{}"\}'.format(x, y)) == str({x: y}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '"{}"

A:

You can escape curly braces by adding double curly braces i.e {{ and }}.
To generate the string:
>>> x = 'A'
>>> y = 'B'
>>> dict_str = "{{'{}': '{}'}}".format(x,y)
>>> dict_str
"{'A': 'B'}"


Q:

How to addObject as NSMutableArray in NSMutableArray in swift

I want to addObject of NSMutableArray into NSMutableArray so how can I achieve this in swift.
and also retrieve it so please help me because right now I'm learning swift.
Indirectly say that I want 2D array means NSMutableArray of NSMutableArray.
//The below 2 lines iterative!
var dict:NSMutableDictionary? = NSMutableDictionary();
 linePointsArray!.addObject(dict!);

// and below 2 line is execute after complete the above iteration
 arrLine!.addObject(linePointsArray!);
 linePointArray!.removeAllObject();

//after that the above whole process is done iterative.

A:

If I am not wrong you want to add an object of NSMutableArray in another NSMutableArray you can do it by following code
var myArray : NSMutableArray = ["Hello"]
var arrayOfArray : NSMutableArray = [myArray]

// Insert more arrays with insertObject or addObject

arrayOfArray.insertObject(myArray, atIndex: 0)
arrayOfArray.addObject(myArray)

//Retrive
var newArray:NSMutableArray = arrayOfArray[0] as NSMutableArray
println("\(newArray)")

For Swift 3:
var myArray : NSMutableArray = ["Hello"]
var arrayOfArray : NSMutableArray = [myArray]

// Insert more arrays with insertObject or addObject

arrayOfArray.insert(myArray, at: 0)
arrayOfArray.add(myArray)

//Retrive
var newArray:NSMutableArray = arrayOfArray[0] as! NSMutableArray
print("\(newArray)")

A:

Here is an example:
var mutableArray: NSMutableArray = []
var nestedMutableArray: NSMutableArray = []
mutableArray.addObject(nestedMutableArray)
var retrievedNestedMutableArray:NSMutableArray = mutableArray[0] as NSMutableArray


Q:

C Programming for 8051: SFR directions as arguments

I'm currently making a very simple Tic-Tac-Toe game with an AT89C51RC2 and I am having issues getting the button input right.
Basically, the input is a 3x3 Button Matrix which I want to utilize by scanning through the rows with a pulse while checking the columns for a connection; pretty basic. However, the way I wanted to do this was by making a unique scroll method that received the row parameter and set it to HIGH accordingly.
I already have
sbit R1 = P1^0;

all through the needed inputs, but I'm not sure if this is correct.
Then, on my main method, I run something like
while(TRUE)
{
    scroll(R1);
}

which is named scroll, I have this
void scroll (bit P)
{
   P = HIGH; //Sets the row being checked to HIGH (HIGH is already defined as a 1). Same goes with the aformentioned TRUE
   ...
}

So, this is not working. I know I'm not doing this right, but I had to start somewhere. Is what I am attempting to do possible? Sending a single Pin adress as an overload for a method? If so, what datatype should it be? I was juggling between char and bit but I can't settle.
I hope my question is understandable! If not, I will gladly elaborate and maybe post all the code (although it is quite messy). Thanks, everyone, in advance!

A:

Edit: I changed code example to answer your question much better
I never used that chip, but it looks like a 8 bit variant of the 8051, so I would make the following guess: your port are defined as "sfr".  Usually your MCU header file contains definitions such as :
sfr P1=0x90;

As per your chip's datasheet on page 5, P1 is at address 0x90.  So that means that you could write something like that:
unsigned char scroll(sbit pin);

int main(int argc,char** argv)
{
 sbit pinMap[3]={P0^6,P0^7,P1^0}; // P0.6, P0.7 and P1.0.
 char keyboardRows[3]; // Keyboard layout is: one row per byte.  Column are mapped on 0 to 2.
 int i;

 while(1)
 {
  for(i=0;i<3;++i)
  {
   scroll(pinMap[i]);
  }
 }

 return 0;
}

unsigned char scroll(sbit pin)
{
 unsigned char rowState;
 pin=1; // or HIGH.

 // Save your column state in rowState here.

 pin=0; // or LOW?

 return rowState;
}

Now, an you didn't say what kind of problem you were having.  We need more information to help you out.

Is it software or could it be hardware?
software
What kind of error are you getting?
I'm still not sure other than it doesn't work
It doesn't compile?
It is fine.
It doesn't do what you expect?
I still don't know what you get vs. what you expect.
Is it a custom matrix?
Yes and it works.
Is so, have you used pull up resistors to set a definite state when the buttons are not pressed?
It's ok.
Have to put diode to prevent ghost keys to appear (when pressing many keys at once)?
It's ok.

Edit:  Ok, your compiler don't like sbit as parameter, so one may try this:
unsigned char scroll(unsigned char* port,unsigned char pin);

int main(int argc,char** argv)
{
 unsigned char* portAddr={&P0,&P1,&P2}; // Put whatever here.
 unsigned char pin[3]={0x40,0x80,0x01}; // P0.6, P0.7 and P1.0.
 char keyboardRows[3]; // Keyboard layout is: one row per byte.  Column are mapped on 0 to 2.
 int i;

 while(1)
 {
  for(i=0;i<3;++i)
  {
   scroll(portAddr[i],pinMap[i]);
  }
 }

 return 0;
}

unsigned char scroll(unsigned char* port,unsigned char pin)
{
 unsigned char rowState;
 *port|=pin; // Let the bus weak pull-up pull the bus up.

 // Save your column state in rowState here.

 *port&=~pin; // Drive low the output.

 return rowState;
}

If you really insist on using sbit and such things, you could make the declaration global such as this:
sbit RowPins[3]={P0^6,P0^7,P1^0};

unsigned char scroll(int rowIndex);

int main(int argc,char** argv)
{
 char keyboardRows[3]; // Keyboard layout is: one row per byte.  Column are mapped on 0 to 2.
 int i;

 while(1)
 {
  for(i=0;i<3;++i)
  {
   scroll(i);
  }
 }

 return 0;
}

unsigned char scroll(int rowIndex)
{
 RowPins[i]=HIGH;

 // Read stuff here and put in "column".

 RowPins[i]=LOW;

 return column;
}


Q:

Logilab compatability with Python 27 windows?

I wanted to installed logilab-common 0.61.0 on to my computer I am a windows user and my python version i 27. Whenever I import the module it throws me the error
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import logilab
  File "logilab\__init__.py", line 28, in <module>
    from logilab.common.__pkginfo__ import version as __version__
ImportError: No module named common.__pkginfo__

However I checked this file exists. Also when I try to call Pylint (the reason I installed logilab) from command line it throws import error
  Loaded Module logilab not not found in sys.modules

I also tried to reinstall logilab and logilab astng. I do not If its a compatibility issue perhaps?

A:

You probably have two distinct installation of the logilab package, one for logilab-common and the other for logilab-astng. Take a look at:
import logilab
print logilab.__path__

You should fix  things (adjust PYTHONPATH?) so that you get the directory containing the common subdirectory there.
Also notice that for recent version of pylint (>= 1.0), logilab-astng has been replaced by astroid.


Q:

Update columns like in MySQL

I want to update multiple columns which have similar names. Is it possible in MySQL?
Something like this:
update `my_table` set `column` = 0 where `column` regexp `'Q%[0-9]$'`

A:

Try this. You require the use of sys database tables to get the column names so you can set your SQL properly:
DECLARE @tableName varchar(10)
SET @tableName = 'yourtablenamehere'

DECLARE @sql VARCHAR(MAX)
SET @sql = ''

SELECT @sql = @sql + 'UPDATE ' + @tableName + ' SET ' + c.name + ' = '''' WHERE ' + c.name + ' IS NULL ;'
FROM sys.columns c
INNER JOIN sys.tables t ON c.object_id = t.object_id
INNER JOIN sys.types y ON c.system_type_id = y.system_type_id
WHERE t.name = @tableName
and c.name regexp `'Q%[0-9]$'`

EXEC (@sql)

reference: Dynamic update statement with variable column names


Q:

Does electron in wave form have mass?

I heard from my lecturer that electron has dual nature. For that instance in young's double slit experiment electron exhibits as a particle at ends but it acts as a wave in between the ends. It under goes diffraction and bends. But we don't see a rise in energy. It has to produce 500kev of energy (please correct if my approximation is wrong) according to mass energy equivalence relation. But wave is a form of pure energy and doesn't show properties of having mass as of experimental diffraction. So where is the mass gone?

A:

I don't really like the whole wave-particle duality business because it obscures the more startling truth about particles: they aren't sometimes waves and sometimes particles, and they also don't transform into waves sometimes before reforming as particles, they are something completely different.
It's like the story of the blind men and the elephant: a group of blind men are trying to describe an elephant by touch, but each man is touching a different part of the elephant. The man who touches the elephant's side says it's like a rough wall, the man who touches its leg says it's like a pillar, the man who touches its tail says its like a rope, and so on. All the men are right, of course, but they simply have incomplete pictures of the elephant because they cannot observe its full character.
Similarly, when we observe the behavior of things like electrons or photons, we sometimes think they are acting as particles, and other times that they are acting as waves. But really, they are neither waves nor particles, but something new that has properties of both; it is only the case that in many cases, only their particle-like or wave-like behavior happens to be relevant to their behavior, and so we treat them as such. So while the phrase "wave-particle duality" might make it seem as if particles can become waves (hence your question), what actually exists is a strange sort of object that always has properties of both particles and waves, only one of which may be easily observable in some cases, and the question of where an electron's mass goes when it becomes a wave isn't really applicable, since it doesn't become a wave at all.
EDIT: It's worth noting, as Anna pointed out, that the wave-like character of objects isn't quite the same as a normal wave, as there isn't really any physical substance that's waving in any real sense. Instead, the "wave" is a probability function that assigns a probability to each point in space, representing the likelihood of finding the particle there; it just so happens that this function takes the mathematical form of a wave. This is a deep subject, so I'll refer you to Anna's answer for further information.

A:

The waves of quantum mechanics are probability waves.  The solutions of quantum mechanical equations are the wave functions and the square of the wave function gives the probability of finding the particle at $(x,y,z,t)$.
That is why the solutions  for the electrons in the field of a nucleus are not orbits, but orbitals, i.e. probability distributions.
The wave particle duality for particles with mass says that they behave like classical particles  when detected macroscopically, as in this bubble chamber picture, or as probability waves when looked at small distances, commensurate with $\hbar$.
For photons the particle nature appears in the photoelectric effect, and the probability wave formalism builds up the classical electromagnetic wave with the same frequency.

A:

It seems that you have misundrstood the wave-particle duality.
What happens in the double slit experiment is that the electrons impact at the screen as they were particles. But they also interfere, just as waves. So you can see a wave-particle behaviour.
But it doesn't say that the electron is destroyed, becomes a wave and then a particle again (as you seem to think).

But wave is a form of pure energy and doesn't show properties of having mass as of experimental diffraction.

NO, waves are not pure energy (for example, sound waves have mass). Maybe you understood that it was supposed to be an electromagnetic wave?
As a sidenote, I think that the wave-particle duality gives a wrong impression, since it's not a classical wave and it can be explained using just particles . See my answer here.
Basically, the wave effect is due to the probabilistic behaviour in quantum mechanics, why can be explained using the wavefunction. But we can predict everything using particles and no waves.
You just have to consider that the electrons passes through both slits and sum the contributions of each path:


Q:

Control for displaying level of cost with currency signs

This might be an opinionated question, but I'd like to ask it because capabilities of UI5 are quite broad. I need to have these elements as

To which I am planning to introduce a custom font. Do you think it's a good solution or is there any better way to do that with some out of the box solutions?

A:

What you're looking for is sap.m.RatingIndicator.
<RatingIndicator
  editable="false"
  maxValue="6"
  value="4"
  iconSelected="imageOrIconURI1"
  iconUnselected="imageOrIconURI2"
/>

API reference
Samples

In your case, you'll need two images: one for the cash / currency symbol, and one greyed-out version of it. Both URIs should be assigned to iconSelected and iconUnselected accordingly.
Here is my attempt:

sap.ui.require([
  "sap/ui/core/Core"
], Core => Core.attachInit(() => sap.ui.require([
  "sap/ui/core/Fragment",
  "sap/ui/model/json/JSONModel",
  "sap/ui/core/theming/Parameters",
], async (Fragment, JSONModel, ThemeParameters) => {
  "use strict";

  const control = await Fragment.load({
    definition: `<form:SimpleForm xmlns:form="sap.ui.layout.form" xmlns="sap.m">
      <Label text="Cost A" />
      <RatingIndicator
        displayOnly="true"
        editable="false"
        maxValue="6"
        value="4"
        iconSelected="{myCurrency>/filled}"
        iconUnselected="{myCurrency>/unfilled}"
      />
      <Label text="Cost B" />
      <RatingIndicator
        displayOnly="true"
        editable="false"
        maxValue="6"
        value="2"
        iconSelected="{myCurrency>/filled}"
        iconUnselected="{myCurrency>/unfilled}"
      />
    </form:SimpleForm>`,
  });

  //==================================================================
  //============= Sample rating indicator icons ======================

  const currencyCode = "€";
  // determine theme-dependent color values for font colors:
  const colorFilled = ThemeParameters.get("sapUiContentForegroundTextColor").replace("#", "%23");
  const colorUnfilled = ThemeParameters.get("sapUiContentImagePlaceholderBackground").replace("#", "%23");
  const model = new JSONModel({ // assign the icon URIs, e.g. data-URI with SVG content:
    filled: `data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'
      viewBox='0 0 14 14'>
      <text x='50%' y='66%'
        fill='${colorFilled}'
        dominant-baseline='middle'
        text-anchor='middle'>
        ${currencyCode}
      </text>
    </svg>`,
    unfilled: `data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 14 14'>
      <text x='50%' y='66%'
        fill='${colorUnfilled}'
        dominant-baseline='middle'
        text-anchor='middle'>
        ${currencyCode}
      </text>
    </svg>`,
  });

  control.setModel(model, "myCurrency").placeAt("content");
})));
<script id="sap-ui-bootstrap"
  src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
  data-sap-ui-libs="sap.ui.core, sap.m, sap.ui.layout"
  data-sap-ui-async="true"
  data-sap-ui-theme="sap_fiori_3"
  data-sap-ui-compatversion="edge"
  data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>

Since I put a plain text character to the SVG, the "image" is zoomable without losing quality and the color can be also made theme-dependent as shown above. But of course, you can also just use two raster images instead.
Either way, I believe the RatingIndicator is a good candidate which could be used instead of creating and maintaining a custom control or custom font.


Q:

CUDA 6: Simplest Sample Segmentation Fault

I get access to CUDA 6 RC as register developer and I want try to use new feature of CUDA 6: Unified Memory. So, I created simple example when I try use this feature:
Here is me example:
#include <stdio.h>
#include <cuda_runtime.h>

int
main(void)
{
    int numElements = 5000;
    size_t size = numElements * sizeof(float);
    float *a;
    cudaMallocManaged(&a, numElements);

    for (int i = 0; i < numElements; ++i)
     {
         a[i] = rand()/(float)RAND_MAX;
    }

    return 0;
}

I tried run it example, but I got segmentation fault error:

Segmentation fault: 11

Question  - what I doing wrong?

A:

Whenever you are having trouble with cuda code, you should always implement proper cuda error checking
If you do so, I'm pretty sure you'll see the error "operation not supported" as the return code from your cudaMallocManaged call.
Unified Memory support is only available (at this time) on Kepler GPUs.  Refer to appendix J "Unified Memory Programming" in the CUDA_C_Programming_Guide.pdf document which will be in the /usr/local/cuda/doc/pdf directory on a standard linux install:

J.1.4. System Requirements
Unified Memory has three basic requirements:
•a GPU with SM architecture 3.0 or higher (Kepler class or newer)
•a 64-bit host application and operating system, except on Android
•Linux or Windows

So switch to a Kepler GPU if you are not already using one, use 64 bit linux or windows (i.e. not MacOS) and be sure to compile your code with an appropriate Kepler architecture specified, e.g. -arch=sm_30
Since your cudaMallocManaged call is failing, the a pointer never gets set, and any subsequent operations with it will result in a seg fault.
And as @talonmies pointed out, change your allocation size from numElements to your computed size variable.


Q:

Extract data between br Tag with beautifulsoup

how can I extract INFO1 and INFO2 from following html code with beautifulsoup?

webiste: https://swisswrestling.ch/wrestlers?id=91

I try also to extract data for the fights but that works for me with bs4.

Notice:  Undefined index: HTTP_ACCEPT_LANGUAGE in /srv/www/chroot/site05/web/app/bootstrap.php on line 159

wrestlers_club INFO1

wrestlers_birthday INFO2

wrestlers_licence_number wrestlers_licence_no_licence

wrestlers_club_dl wrestlers_licence_no_dl

My code looks now:
info = soup.find('div', id='content')
club = info.findAll('span')
for clubs in club:
 test = clubs.text
 print(test)

And the Result is:
Notice:
 Undefined index: HTTP_ACCEPT_LANGUAGE in /srv/www/chroot/site05/web/app/bootstrap.php on line 159

wrestlers_club
wrestlers_birthday
wrestlers_licence_number
wrestlers_club_dl
How can I extract the data behind wreslters_club (INFO1) and wrestlers_birthday (INFO2)?
Thanks for your help!

A:

Use following Css selector and find_next_sibling(text=True)
    import requests
    from bs4 import BeautifulSoup

    res=requests.get("https://swisswrestling.ch/wrestlers?id=91")
    soup=BeautifulSoup(res.text,'lxml')
    print(soup.select_one('span.text-danger:nth-of-type(1)').find_next_sibling(text=True).strip())
    print(soup.select_one('span.text-danger:nth-of-type(2)').find_next_sibling(text=True).strip())

Output:
RC Willisau Lions
29 (1990)