text:
Q: How to pass string to Beacon alte I copied and edit this code in order to pass string by ALTEBeacon, but I can only see two characters for example String name = "Paulo" And I only see "Pa". I do not understand why. I used this method code.
 if (Build.VERSION.SDK_INT >= 21) {
        // Call some material design APIs here
        device.setText("supported");
        // new code
        String stringToTransmit = "Paulo";
        byte[] stringToTransmitAsAsciiBytes = stringToTransmit.getBytes(StandardCharsets.US_ASCII);
        Beacon beacon = new Beacon.Builder()
                .setId1(MY_MATCHING_IDENTIFIER.toString())
                .setId2(Identifier.fromBytes(stringToTransmitAsAsciiBytes, 0, 5, false).toString())
                .setId3("2")
                .setManufacturer(0x0118)
                .setTxPower(-59)
                .setDataFields(Arrays.asList(new Long[] {255l}))
                .setBluetoothName(Identifier.fromBytes(stringToTransmitAsAsciiBytes, 0, 5, false).toString())
                .build();

               BeaconParser beaconParser = new BeaconParser()
                .setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25");
        BeaconTransmitter beaconTransmitter = new BeaconTransmitter(getActivity(), beaconParser);

        beaconTransmitter.startAdvertising(beacon);
    }

and I recover with this code
for (Beacon b:beacons) {
                    //new

                        String receivedString = null;

                       // byte[] bytes = b.getId2().toByteArray();
                       byte[] bytes = b.getId2().toByteArray();
                        receivedString = null;

                        try {
                            receivedString = new String(bytes, 0, bytes.length, "ASCII");

                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

}

A: The code attempts to store the string "Paulo" into the AltBeacon Id2 field.  The problem is that ASCII encoding uses one byte for each character, and the Id2 field is only two bytes long.  Therefore, the field only has room for two characters.  This is why you only see "Pa".


text:
Q: How does one find the number of distinct solutions $(x, y)$ of $Y^2=X^3+1$ over a $\mathrm{GF}(p)$? Given the equation $Y^2=X^3+1$ over the finite field $\mathrm{GF}(p)$, how does one find the number of solution pairs $(x, y)$ that satisfy the equation?
For example, in $\mathrm{GF}(2)$ and $\mathrm{GF}(3)$, there are 2 solutions and 3 solutions respectively: $(0, 1), (1, 0)$ for the former and $(0, -1), (1, 0), (-1, 0)$ for the latter.
In the other primes, those of the form $p \equiv 2 \pmod{3}$, cubing is a multiplicative automorphism and therefore one can easily show that there is exactly $p$ distinct pairs $(x, y)$ with $x, y$ in $\mathrm{GF}(p)$.
What about for other primes? What kind of techniques/methods/theorems can be used to find the number of solutions without brute forcing it for a given $p \equiv 1 \pmod{3}$?

A: The equation describes the elliptic curve "36a1". The modular form coefficients of it is the OEIS sequence A000727. The number of solutions is $p-2x$ using the unique solution to $p=x^2+3y^2$ where $x\equiv 1 \pmod {3}$ and $y>0$ if $p\equiv 1\pmod{3}$ else $p$. More details are in the sequence entry including a reference to Exercise 47.2 in Silverman's A Friendly Introduction to Number Theory.

A: Let $g$ a generator of $\mathbb{F}_p^\times$. Define the cubic character $\chi_3(g^a) = \zeta_3^a,\chi_3(0)=0$ and the trivial character $\chi_0(x) = 1_{x \in \mathbb{F}_p^\times}$. Then $$\frac{1}{3}(\chi_3(x)+\overline{\chi_3(x)}+\chi_0(x)) = 1_{x \in (\mathbb{F}_p^\times)^3}$$
Define the Jacobi sum
$$J(\chi,\chi) =\sum_{x\in \mathbb{F}_p} \chi(x)\chi(1-x)=\sum_{x\in \mathbb{F}_p} \chi(ax)\chi(1-ax)=\chi(a)^2\sum_{x\in \mathbb{F}_p} \chi(x)\chi(a^{-1}-x), \quad a \in \mathbb{F}_p^\times$$
Thus
$$\sum_{y \in \mathbb{F}_p} 1_{y^2-1 \in (\mathbb{F}_p^\times)^3} = \frac{1}{3} \sum_{y \in \mathbb{F}_p} (\chi_3(y^2-1)+\overline{\chi_3(y^2-1)}+\chi_0(y^2-1))$$
$$ =\frac{1}{3}( \chi_3(2^{-1})J(\chi_3,\chi_3)+\overline{ \chi_3(2^{-1})J(\chi_3,\chi_3)}+J(\chi_0,\chi_0))$$
If $p \equiv 1 \bmod 3$ then $\mathbb{F}_p$ contains a 3rd root of unity so $x^3 = c$ has $0$ or $3$ solutions.
Therefore, together with $J(\chi_0,\chi_0))=\sum_{y \in \mathbb{F}_p^\times} 1_{1-y \in \mathbb{F}_p^\times} = p-2$,
the point at $\infty$ and the 2 solutions $y^2-1= 0$ we find
$$\# E(\mathbb{F}_p) = 1+2+3 \sum_{y \in \mathbb{F}_p^\times} 1_{y^2-1 \in (\mathbb{F}_p^\times)^3} = p+1+\chi_3(2^{-1})J(\chi_3,\chi_3)+\overline{ \chi_3(2^{-1})J(\chi_3,\chi_3)}$$

A: In this case for $p\equiv1\pmod 3$, there is a formula in terms of Jacobi
sums. This can be found in the book of Ireland and Rosen. It is
$$p+J(\rho,\chi)+\overline{J(\rho,\chi)}$$
where $\rho$ and $\chi$ are quadratic and cubic characters of $\Bbb F^\times$. This Jacobi sum can be expressed in terms of the representations
of $p$ in the form $a^2+ab+b^2$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Set no. of copies in a System.Windows.Controls.PrintDialog For what I searched so far, I could not find a way to preset the number of copies in a System.Windows.Controls.PrintDialog, which is the one used in WPF. I cannot fallback or use another one because I need the PrintVisual method that only this class offers (afaik)
Unless there is another way, I'm thinking of doing a for loop and call the dialog.PrintVisual() method for the number of desired copies.I have not tested yet, but I'm quite sure it should work. My question: Is this the correct way of doing it?

A: You're looking for dialog.PrintTicket.CopyCount.
Docs.


text:
Q: How to control position of startup predicate in the execution plan For two last statements of the code below produce actual execution plan. You can see that startup predicate on @Par1 is placed in a different position that completely changes the actual number of rows that come from test_fn1 function. I need to control this behaviour.
create or alter function dbo.test_fn1(@Par1 varchar(100), @Par2 varchar(1))
returns @t table(item varchar(100))
as
begin
  insert into @t (item) select value from STRING_SPLIT(@Par1, @Par2);
  return
end
GO
create or alter function dbo.test_fn(@Par1 varchar(100), @Par2 varchar(100))
returns table
as
return (
  select s.*
    from dbo.test_fn1(@Par2,';') x
    inner join sys.objects s on s.name = x.item
    where @Par1 = 'CASE1'
)
GO
create or alter function dbo.test_fnx(@Par1 varchar(100), @Par2
   varchar(100))
returns table
as
return (
  select s.*
    from sys.objects s
    inner join dbo.test_fn1(@Par2,';') x ON s.name = x.item
    where @Par1 = 'CASE1'
)
GO
declare @Par1 varchar(100), @Par2 varchar(100)
select @Par1 = 'CASE2', @Par2 = 'test1;test2'

select * from dbo.test_fn(@Par1, @Par2)
select * from dbo.test_fnx(@Par1, @Par2)

Below is the proper plan where startup predicate makes the query does not work on any data.

Here is the plan that show wrong behaviour of placing startup predicate. In both cases we start from the same function and only order in T-SQL is changed.

Tested on SQL Server 2016 SP2.
Is there any whitepaper or documentation on how SQL Server is placing startup predicates?

A:
Is there any whitepaper or documentation on how SQL Server is placing startup predicates?

No, not that I've ever seen. They don't get written about all that much. The one time I blogged about them, I did a lot of head scratching.
Now, I have an answer -- it's not guaranteed to always work. It's playing some tricks on the optimizer that you can learn more about by watching Query Tuning Mastery: Clash of the Row Goals, a talk by Adam Machanic.
With that out of the way, we can control to some degree where the optimizer decides to stick predicates by using TOP.
Function rewrite 1:
In this one, the WHERE clause appears inside the CROSS APPLY.
CREATE OR ALTER FUNCTION dbo.test_erik ( @Par1 VARCHAR(100), @Par2 VARCHAR(100))
RETURNS TABLE
AS
    RETURN (   SELECT s.*
               FROM   sys.objects AS s
               CROSS APPLY
                      (   SELECT TOP (2147483647) *
                          FROM   dbo.test_fn1(@Par2, ';') AS x
                          WHERE  s.name = x.item
                          AND    @Par1 = 'CASE1' ) AS ca );
GO

Function rewrite 2:
In this one, the WHERE clause appears outside the CROSS APPLY.
CREATE OR ALTER FUNCTION dbo.test_erikx ( @Par1 VARCHAR(100), @Par2 VARCHAR(100))
RETURNS TABLE
AS
    RETURN (   SELECT s.*
               FROM   sys.objects AS s
               CROSS APPLY
                      (   SELECT TOP (2147483647) *
                          FROM   dbo.test_fn1(@Par2, ';') AS x
                          WHERE  s.name = x.item ) AS ca
               WHERE  @Par1 = 'CASE1' );
GO

You can see the resulting plans here.
In plan 1, the startup expression predicate appears inside by the TOP:

In plan 2, it appears outside.

If you want the Startup Expression Predicate to act as a constant scan, try this:
CREATE OR ALTER FUNCTION dbo.test_erik_filter ( @Par1 VARCHAR(100), @Par2 VARCHAR(100))
RETURNS TABLE
AS
    RETURN (
               SELECT ca.*
               FROM (
                     SELECT TOP (1) 1 AS n
                     WHERE @Par1 = 'CASE1'
                    ) AS x
               CROSS APPLY
                (
               SELECT     s.*
               FROM       sys.objects AS s
               INNER JOIN dbo.test_fn1(@Par2, ';') AS x
                   ON s.name = x.item
               ) AS ca

         );
GO

If we run two different test cases, the plans will be slightly different:
DECLARE @Par1 VARCHAR(100), @Par2 VARCHAR(100);
SELECT @Par1 = 'CASE2', @Par2 = 'test1;test2';

select * from dbo.test_erik_filter(@Par1, @Par2)

GO

DECLARE @Par1 VARCHAR(100), @Par2 VARCHAR(100);
SELECT @Par1 = 'CASE1', @Par2 = 'test1;test2';

select * from dbo.test_erik_filter(@Par1, @Par2)

GO

Looking at the live query plans (here are the regular ones), there are a couple early important differences.
No rows come out of this, which means the start up expression isn't true.

Rows will flow out of this one, because it does.

Remember that data flows from right to left in a query plan. Putting the filter further towards the left side of the plan has no advantage for doing less work.
Aaron Bertrand discusses a similar issue with regular filters here:

*

*Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
As an aside, if your real-life code doesn't just select from system tables/views, you should consider adding the SCHEMABINDING attribute to it, which could aid in filter placement.
Hope this helps!

A: A good friend of mine Grzegorz (Stasiek) Domański found the solution that makes the query check startup predicate at first. Here is the code (similar to Erik solution).
 create or alter function dbo.test_fn1(@Par1 varchar(100), @Par2 varchar(1))
 returns @t table(item varchar(100))
 as
 begin
   insert into @t (item) select value from STRING_SPLIT(@Par1, @Par2);
   return
 end
 GO
 create or alter function dbo.test_fn(@Par1 varchar(100), @Par2 varchar(100))
 returns table
 as
 return (
   select sx.*
   from (select top 1 null x) a
   cross apply(
     select s.*
       from dbo.test_fn1(@Par2,';') x
       inner join sys.objects s on s.name = x.item
   ) sx
   where @Par1 = 'CASE1'
 )
 GO
 create or alter function dbo.test_fnx(@Par1 varchar(100), @Par2
    varchar(100))
 returns table
 as
 return (
   select sx.*
   from (select top 1 null x) a
   cross apply(
     select s.*
       from sys.objects s
       inner join dbo.test_fn1(@Par2,';') x ON s.name = x.item
   ) sx
   where @Par1 = 'CASE1'
 )
 GO
 declare @Par1 varchar(100), @Par2 varchar(100)
 select @Par1 = 'CASE2', @Par2 = 'test1;test2'

 select * from dbo.test_fn(@Par1, @Par2)
 select * from dbo.test_fnx(@Par1, @Par2)

Here are the execution plans. Marked places are the moments of startup predicate checks. And these are actual plans so no records are considered as long as startup predicate is false. And that is we expected to have.


text:
Q: How to exclude something from forEach on discord.js so I am in discord.js and was making a command, which would kick everybody from the server. The thing is, I wanted to kick everyone except me, and I don't know how to do that, nor did I find any tutorial on it. Here is my code:
bot.on("message", async message => {
    if(message.content.startsWith(`${prefix}gone`)) {
      message.guild.members.cache.forEach(member => member.ban())
    }

}
)

I would love is someone would help. Thank you in advance+

A: Try something like this:
const MY_USER_ID = 'your user id'
bot.on("message", async message => {
  if(message.content.startsWith(`${prefix}gone`)) {
    message.guild.members.cache.forEach(member => {
      if (member.id !== MY_USER_ID) {
        member.ban()
      }
    })
  }
})

A: In your .forEach() loop you need to add a check to see if the member has the same ID as you so you could do this two ways:
Either by making the bot ignore the user who typed in the command:
message.guild.members.cache.forEach(member => {
  if (member.id !== message.author.id) member.ban()
})

Or if you want to just make it not ban you specifically then:
message.guild.members.cache.forEach(member => {
  if (member.id !== 'USER_ID') member.ban()
})

You can also write those checks inside of a .filter() like so:
message.guild.members.cache.filter(member => member.id !== 'USER_ID').forEach(member => member.ban())


text:
Q: How to refresh training in chatterbot bot in python? I made a simple chatbot using chatterbot library and python. The way I trained it is, I made it read a few text files containing chat examples, and it learns how to reply to messages based on those training examples. The problem I am facing is - Even if I erase the contents of the training text files, and run the application, the chatbot still behaves in the same manner as before, i.e. it's memory doesn't get refreshed. I tried starting a new file and copy pasted the same code and changed the name of the program, but it still doesn't help. How do I solve this problem? Here is the code for reference:
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer

import os

bot = ChatBot('trialBot')

bot.set_trainer(ListTrainer)

#directory containing training text files
mainDir = 'C:\\Users\\xyz\\Desktop\\trainfiles\\'

for _file in os .listdir(mainDir):
    chats = open(mainDir + _file, 'r').readlines()
    bot.train(chats)

while True:
    request = raw_input('You: ')
    response = bot.get_response(request)

    print('Bot: ' + str(response))

A: It sounds like you might want to use an in-memory database so that the content is only persisted as long as the chat bot is running.
bot = ChatBot(
    'trialBot',
    database_uri=None
)

Setting database_uri to None will cause the chat bot to use a Sqlite database that is stored in-memory so store the knowledge that it is trained with. As a result, you will have a fresh database to work with each time you run your program.


text:
Q: Solve $ \sum_{k = 1}^{ \infty} \frac{\sin 2k}{k}$ Solve $$ \sum_{k = 1}^{ \infty} \frac{\sin 2k}{k}$$
I first tried to use Eulers formula
$$ \frac{1}{2i} \sum_{k = 1}^{ \infty} \frac{1}{k} \left( e^{2ik} - e^{-2ik}  \right)$$
However to use the geometric formula here, I must subtract the $k=0$ term and that term is undefinted  since $1/k$. I also end up with something that diverges in my calculations and since $\sin 2k$ is limited the serie should not diverge.

A: The summation is as follows:
\begin{align}
S &= \sum_{n=1}^{\infty} \frac{\sin(2an)}{n} = \frac{1}{2i} \, \sum_{n=1}^{\infty} \frac{ e^{2ai n} - e^{- 2ai n}}{n} \\
&= - \frac{1}{2i} \left( \ln(1 - e^{2ai}) - \ln(1 - e^{-2ai}) \right) \\
&= - \frac{1}{2i} \ln\left( \frac{1 - e^{2ai}}{1 - e^{- 2ai}} \right) = - \frac{1}{2i} \ln\left( - \frac{e^{ai}}{e^{-ai}} \cdot \frac{\sin(a)}{\sin(a)} \right) \\
&= - \frac{1}{2i} \ln\left( - e^{2ai} \right) = - \frac{1}{2i} \left( \ln(e^{- \pi i}) + \ln(e^{2ai}) \right) \\
&= - \frac{1}{2i} \left( - \pi i + 2ai \right) = \frac{ \pi - 2a}{2}.
\end{align}
This provides
\begin{align}
\sum_{n=1}^{\infty} \frac{\sin(2an)}{n} = \frac{ \pi - 2a}{2}.
\end{align}

A: For finite non-zero $a,$
$$\sum_{k=1}^\infty\frac{e^{2iak}}k=-\ln(1-e^{2ia})$$
$$1-e^{2ia}=-e^{ia}(e^{ia}-e^{-ia})=-e^{ia}[2i\sin(a)]$$
$$\ln(1-e^{2ia})=\ln(e^{i(a+2m\pi)})+\ln2+\ln(-i)+\ln[\sin(a)]$$
$$=i(a+2m\pi)+\ln2-\frac{i\pi}2+\ln[\sin(a)]$$
as $-i=\cos\left(\frac\pi2\right)+i\sin\left(\frac\pi2\right)=e^{i\dfrac\pi2}$ and where $m$ is any integer
Hope you can take it home from here setting $a=1,-1$ one by one


text:
Q: Saving ~1kk chars text to MySQL On a remote server I'm saving text (967 537 characters) from textarea to MySQL database, column with type of TEXT.
Only around 63 748 characters are saved.
Also, in phpMyAdmin I'm getting the following error when doing UPDATE:
Warning: #1265 Data truncated for column 'content' at row 1

Since I don't have access to change config files myself, it would be good to know what should be changed to fix this problem before I request for it.
Versions:
PHP 5.2.14
MySQL 5.0.96
Apache 2.2.12

MySQL config:
max_allowed_packet = 52428800
net_buffer_length = 8192

PHP ini:
post_max_size = 32M

Apache:
suhosin.post.max_value_length = 1000000

On localhost, everything works just fine.

A: Use MEDIUMTEXT or LONGTEXT insead of normal TEXT. MEDIUMTEXT can contain 16,777,215 bytes, approximately 16MB, LONGTEXT can contain 4,294,967,295 bytes, so approximately 4GB.
LONGTEXT might be a bit large, so I guess MEDIUMTEXT will be sufficient.
EDIT:
This just came to my mind: If you have multiple pages that need to show all the time, there are better (and faster) things than a database. You could generate it into a plain HTML file (of even TXT if it's just that), and include it when and where you need it. This way you won't have a database taking up tons of space.

A: you should check type field limitation on :
http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html
TEXT type has maxlength < 2^16 (65536)

A: Type TEXT is too small (it can only hold up to around 64K, as you discovered). You can use MEDIUMTEXT to reach 16M, or LONGTEXT to get even more. Given storage requirements (one extra byte for every row), if there's the slightest risk of ever exceeding 16M, go with LONGTEXT.
But I think you should question why you are storing data in the DB. Unless it is an indirect requirement of the platform (e.g. it's easier to use an ORM, while file storage would need an ad hoc column data driver), or you want to make use of full text indexing functions, it might be more convenient to store data as separate files and only store the file name in the database (or you might use tablename_primarykeyvalue.html as file name, thus saving also file name storage requirements).
The "separate storage" method complicates data retrieval and backups. On the other hand, backups will be smaller and faster, disk usage will be lower, and if your security model allows it, you could allow direct access to the files bypassing the database altogether: for example if you're storing blog posts, you can retrieve them through AJAX, reducing database load and exploiting browser caching strategies (also, on some platforms, you can directly serve compressed files, thereby boosting speed and saving CPU).
This post Do very large fields have a negative effect on MySQL databases? advocates MySQL TEXT storage, but also presents some considerations on why you might not want to.
UPDATE

On localhost, everything works just fine.

Danger, Will Robinson! There's no way it can work on localhost, unless your development and production databases are not synchronized. I.e., you have MEDIUMTEXT on localhost and TEXT on the remote. So the question is, what else could be different between the two databases? While not related to your question, it's something you definitely want to check!


text:
Q: What "traffic flow" would be right in a transparent "squid + dansguardian" pfsense setup? My thought (I'm not sure if it's right):

*

*LAN interface traffic comes into port 80

*Destination port is redirected to 8080 (dans guardian)

*dansguardian outputs traffic to port 3128 (Squid)

*Squid outputs traffic out in WAN interface to port 80

A: Squid 3 build in pfSense is perfectly possible to use with any ICAP filtering server (see the list at http://www.squid-cache.org/Misc/icap.html). The good thing about ICAP it is a traffic interception and redirection done by Squid itself, you would not need to mess with firewall redirection rules. If I am not mistaken the transparent HTTP/HTTPS filtering may be supported with just several clicks in the web interface of pfSense.
As an example see http://sichent.wordpress.com/2014/02/22/filtering-https-traffic-with-squid-on-pfsense-2-1/.


text:
Q: Spaces not shown in HTML I have the following text stored in a MySQL database.

Test red bold text

In a page it is read and displayed as
$htmlText = ... gets the above html from the database

    <?php echo $htmlText;?>

and I get this:

When I click on the div it opens a modal window where the text can be edited using tinyMCE and here it displays without the spacing issue.

Why do I get the initial spacing problem and how can I work around it?

A: Add this CSS to the element containing the text:
element {
    white-space: pre-wrap;
}

MDN

Sequences of white space are preserved. Lines are broken at newline characters, at
, and as necessary to fill line boxes.

Stack Snippet:

div {
  white-space: pre-wrap;
}

  foo     bar          baz


text:
Q: How to display relational data in a React/Redux project? I have joined a project recently and I have to add some new features. But it's quite challenging when it's not your code. So the new feature is to display the name of a common friend or common friends. For now it only displaying the number of common friends via a variable common_friends_count.
The /friendships/ api is only returning the number, not a object.
{
  "uuid": "09f0e78d-774d-4e72-bd06-5f99ccd549f1",
  "user_uuid": "12370118-bc09-41a5-b9c1-75fe802fcc6d",
  "full_name": "John Doe",
  "picture_url": "https://ucarecdn.com/945fa78c-de6a-4caf-9b3f-9638ed2bb69b/",
  "friends_count": 2,
  "common_friends_count": 1
}

My question is : How can I return the name(s) via the common_friends_count number ? Any help is appreciated.
The project is created with redux saga but as far as i can see, there's nothing about the friendship that is connected to the redux store.
Thank you ! Let me know if you need more details :)


text:
Q: GL_CLAMP_TO_EDGE not available I've heard that GL_CLAMP is deprecated, but it seems like I don't have access to GL_CLAMP_TO_EDGE, which should be used instead. I can only use GL_CLAMP. I'm using Visual Studio 2012. How can I fix this?
I've checked my OpenGL version, and it's 3.1.0:
3.1.0 - Build 8.15.10.2418

A: To quote this answer

Microsoft hasn't updated their OpenGL headers/libraries for quite a
  while. To use newer features, you normally want to use GLEW or GLEE.

And this answer

To get access to OpenGL 1.2 or greater, you need to use the extension
  loading mechanism. I suggest you look ... look at GLEW or GLEE.

GL_CLAMP_TO_EDGE was introduced in version OpenGL 1.2


text:
Q: How to make awk produce columns I have a file with two columns. Each line in this file has a different size of words
awk '$5=$9' FS="#" OFS="\t" file1**

Tomato#Vegetable
Orange#Fruit
Cucumber#Vegetable
Sweat Potato#Fruit

This line of code makes it like this:
Tomato   Vegetable
Orange   Fruit
Cucumber   Vegetable
Sweat Potato    Fruit

I am trying to make this file be displayed like this:
Tomato          Vegetable
Orange          Fruit
Cucumber        Vegetable
Sweat Potato    Fruit

What am I doing wrong that does not give me this result?

A: With Unix / Linux you can use column to produce column output:
$ column -t -s '#' your_file
Tomato        Vegetable
Orange        Fruit
Cucumber      Vegetable
Sweat Potato  Fruit

To do it in awk you can read the file twice to get the max field length for each column. Once you do that, you can fix the field width with sprintf with the field width + pad value:
awk -F'#' -v pad=4 '
        FNR==NR {                    # FNR==NR means first file
            for (i=1;i<=NF;i++)      # find the max width of each field
                if(max[i]<length($i)) max[i]=length($i)
            next                     # next record of first file
            }
            {                        # Second file
                s=""                 # reset the buffer string
                for (i=1;i<=NF;i++)  # build the buffer field by field
                    s=s sprintf("%-*s%*s", max[i], $i, pad, "")
                print s              # print the buffer
            } '    your_file your_file

Prints:
Tomato        Vegetable
Orange        Fruit
Cucumber      Vegetable
Sweat Potato  Fruit

A: Another awk, that reads the file once, hashes the records to memory (expected that you have enough memory available) and format and outputs in the end:
$ awk -F\# '{                              # define record separator
    a[NR]=$1                               # store 1st field
    b[NR]=$2                               # store 2nd field
    m=((n=length($1))>m?n:m)               # figure out the max length of 1st field
}
END {                                      # in the end
    for(i=1;i<=NR;i++)                     # iterate stored fields
        printf "%-" m+4 "s%s\n",a[i],b[i]  # output
}' file

Output:
Tomato          Vegetable
Orange          Fruit
Cucumber        Vegetable
Sweat Potato    Fruit


text:
Q: python user input for finding leap year not printing I am trying to create a function that accepts a users input and tries to figure out whether the year is a leap year and later also accept the users day of year (i.e. 355) and turns it into which day of the year it is (and output December, 10 2018). But for now I am not sure why it will not output whether the year is True or False. I tried to use the int parameter to change the user input from a string to a number but I am not sure if that is where I went wrong.
 user_year = input('Enter year: ')
    val = int(user_year)
    def leap_year(val):
        if val % 400 == 0:
            print ("True")
        if val % 100 == 0:
            print ("False")
        if val % 4 == 0:
            print ("True")
        else:
            print ("False")

A: You're only defining the function leap_year but you're never calling it, below is an example where it actually gets called:
user_year = input('Enter year: ')
val = int(user_year)

def leap_year(val):
    if val % 400 == 0:
        print ("True")
    if val % 100 == 0:
        print ("False")
    if val % 4 == 0:
        print ("True")
    else:
        print ("False")

leap_year(val)

Also your indentation is a bit off, which causes it to not compile in the first place, but that could also be an error while copying to Stackoverflow.


text:
Q: Did Gandalf know the origin of "Glamdring"? I have few questions here:

*

*Did Gandalf know the origin of Glamdring? If so, how did he know it?

*Is it explained in the books how Glamdring made its way to a troll's treasure hoard or who had it before Gandalf?

A: Gandalf and the Dwarves (and Bilbo) were told about the origins of Glamdring, Orcrist and Sting by Elrond in Rivendell:

Elrond knew all about runes of every kind. That day he looked at the swords they had brought from the trolls' lair, and he said: "These are not troll-make. They are old swords, very old swords of the High Elves of the West, my kin. They were made in Gondolin for the Goblin-wars. They must have come from a dragon's hoard or goblin plunder, for dragons and goblins destroyed that city many ages ago. This, Thorin, the runes name Orcrist, the Goblin-cleaver in the ancient tongue of Gondolin; it was a famous blade. This, Gandalf, was Glamdring, Foe-hammer that the king of Gondolin once wore. Keep them well!"

Glamdring was therefore originally owned by Turgon, king of Gondolin, and the "Goblin-wars" were the battles of the Elves of Beleriand against Morgoth, most likely in the case the Battle of Unnumbered Tears, since it was the only time the Host of Gondolin came out to fight.
The only hint of its origin is given further in the text:

"Whence did the trolls get them, I wonder?" said Thorin looking at his sword with new interest.
"I could not say," said Elrond, "but one may guess that your trolls had plundered other plunderers, or come on the remnants of old robberies in some hold in the mountains of the North."


text:
Q: Declaring C Pointers - Why do we use * and not & My question is a simple one (I hope) about c syntax regarding pointer declaration. I am fully aware of how to declare a pointer, how its used and what the effects are, like as follows.
int *val_ptr;
int val =99;

val_ptr = &val;

However, what confuses me is why when we declare a pointer in C do we use the * Indirection (value of) operator? and not the & address of operator.  If we are declaring a pointer would it not make sense to do so with &, because we are declaring an address right? Example:
int & val_ptr;
int val =99;

val_ptr = &val;

I know it's incorrect but to my mind that would seem more intuitive. What is it I'm missing in my conception of the * operator.  I have not yet found a text book that gives me an explanation of why, they just show how. I know how, I would like to know why.
Thanks for reading.

A: The pointer declaration syntax tries to mimic pointer usage. When you have
int *ptr;

then *ptr is of the type int.

A: Declaration mimics use.  If you have a pointer to an integer and you want to access the pointed-to value, you dereference the pointer with the * operator, like so:
x = *p;

The type of the expression *p is int; therefore, it follows that the declaration of p should be
int *p;

A: When you write:
int *mypointer;

you can think, "I declare that (*mypointer) is an int" (i.e, "my pointer will reference an int"), like this:
int (*mypointer);

Look that now,
int (&mypointer);

has no sense. What are you saying? the "address of my pointer value is an int" (that's true, but it's not your point).

A: You can't use & operator to declare pointer in C. Standard doesn't allow this. When you declare pointer in C like:
int *val_ptr;

then * in the declaration is not the dereference (indirection) operator. But when this * comes in a statement then it performs indirection.


text:
Q: Displaying images in php using a table I am using this code but it is giving me errors. How do I display the images in a table using php?
echo ""."."	";

I am getting a syntax error, how can I fix this?
Thank You

A: You are using wrong double quotes, wrong single quotes and you are missing to escape one double quote and missing also a double quote in concatenation, so change to
echo ""."\""."	";


text:
Q: Origin of Fermi-Dirac distribution? I wanted to know what "problem" Fermi and Dirac wanted to solve with the Fermi-Dirac distribution in 1926? What was the context? What is the history behind this distribution?
I hope the question is understandable.

A: Looks like Fermi was trying to solve some problems of the old quantum theory, such as independence of the specific heat of a monoatomic ideal gas on the temperature (https://books.google.com/books?id=DQLNCwAAQBAJ&pg=PA82&lpg=PA82&dq=fermi+statistics+original+paper&source=bl&ots=I98ibTdpls&sig=tQ4vhlNwGQbE4fEB6Ym5CEQryHg&hl=en&sa=X&ved=0ahUKEwjk54DgteLQAhVp2IMKHZ5DBBoQ6AEIRTAH#v=onepage&q=fermi%20statistics%20original%20paper&f=false). By the way, Dirac's treatment of the statistics was not quite independent. He had read Fermi's article, but forgot about it. When Fermi wrote to Dirac about this issue, Dirac wrote him a letter with an apology. I read that in a book by Dirac. If there is interest, I'll try to find the reference.
EDIT(12/7/2016): Here's the reference: Dirac, The Origin of Quantum Field Theory // The Impact of Modern Scientific Ideas on Society, Dordrect, Holland, D. Reidel, 1981, pp.39-55 (see also information at https://cds.cern.ch/record/1177841?ln=en) I read the article in Russian translation


text:
Q: My piece of HTML won't display in my WebView in C#/XAML My application reads a RSS feed and display it in a list.  This mostly works:
var rssfeed = new RSSfeed();    // make instance to use
string s = await rssfeed.GetHttpStr(feedUrl);   // get feed as string
this.items = rssfeed.ParseRSS(s); // parse RSS into a list

(RSSfeed is a model of an item in the feed. s is the http response string.  ParseRSS is a method that converts the string, using the model, into an object.)
(To made this brief, I've excluded the code behind the methods.  If you want I can post has as well on request.)
The following loop will place each item into the ListView.
        foreach (var item in myItems)
        {
            var htmlSource = new HtmlWebViewSource
            {
                Html = @"" + item.Desc + ""
            };
            this.items.Add(new RSSItem
            {
                Title = item.Title,
                Link = item.Link,
                ID = item.Id,
                Desc = htmlSource.Html
            });
        }

Here is my XAML, inside my DataTemplate:
            <ViewCell>
                <Frame OutlineColor="Gray">
                    <StackLayout Margin="5" Padding="5">

                        <Grid RowSpacing="0" ColumnSpacing="0" Margin="0" Padding="0" BackgroundColor="Transparent">
                            <WebView Source="{Binding Desc}" />
                        </Grid>
                    </StackLayout>
                </Frame>
            </ViewCell>

(Apparently the WebView wrapped in a Grid doesn't require a Width/HeightRequest - is this true?  Is there another way to make it dynamically sized to the contents?)
The ListView shows fine (and most RSS fields) but my WebView is empty.  What do I need to display the "Desc" (a simple HTML image tag) in the WebView?

A: WebView.Source is a Uri not a string. If you want to view custom HTML content, you'll need to use the NavigateToString(html) method. Unfortunately, you can't bind to that either, but there's a workaround found here.


text:
Q: Scroll to top of the page on pagination pagechange w/o router interactions I am working on an application where we list some data, with ngb-pagination and don't use routing for the change, so we can't use scrollPositionRestoration which is router related.
My issue is that I'd like to move the current view(since pagination is on the bottom of the page) to be resetted to the top. I can't access the dom directly b/c of universal. So window.scrollTo is out.
What is a good and elegant way to achieve the goal i'd like?
router-scroll is out since no real routing happens
direct dom access is forbidden
The snipped would not make any difference to the issue. I just want to extend my existing current function that's called when pagination page-change happens.

A: You can check if code is executed on the client and call window.scrollTo only in that case. Not much elegance though.
import { PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

constructor(
  @Inject(PLATFORM_ID) private platform,
) {}

goToTop() {
  it (isPlatformBrowser(this.platform)) {
    window.scrollTo(...);
  }
}


text:
Q: store external web service in web.xml if I want to store a external web service url in the web.xml file, how I must proceed?, in this way?:
<service-ref>
<service-ref-name>PublicApiService</service-ref-name>
 <service-interface>
</service-interface>
<wsdl-file>
    http://nxxxx/example/Services/PublicApiService.wsdl
</wsdl-file>

What I should put on the service-interface if the web service is external?. I use eclipse
Thanks so much

A: You have to generate the client stubs of the service.
You can use ws-import for generating the client stubs:
wsimport -p your.package.name -s gen -d bin http://nxxxx/example/Services/PublicApiService.wsdl

This will generate the needed Java source files. Execute it in your project root dir.
After that you have to change your web.xml file:
<service-ref>
    <service-ref-name>PublicApiService</service-ref-name>
    <service-interface>
        your.package.name.PublicApiService
    </service-interface>
    <wsdl-file>
        http://nxxxx/example/Services/PublicApiService.wsdl
    </wsdl-file>
</service-ref>


text:
Q: Switch on system at a particular time from shutdown I am looking for a software which can power on my Windows 7 desktop at a particular time, say 5am. I tried Auto Shutdown and Poweron software, but for some reason it is not able to switch on the system.
If it is not possible to switch on automatically from Shutdown state, power on from hibernate state will do.

A: Motherboards these days will support wake up timers by the OS. WOL isn't necessary to implement this.
Go into Control Panel and Select Change plan settings next to the power plan you want use.
Select Change settings that are currently unavailable then look for set allow wake timers. Enable it.
Then you can go into Task Scheduler to wake your computer.
The tasks in Task Scheduler have an option to explicitly allow "wake the computer to run this task." Unfortunately, there is no way to find out what tasks currently have this checked.  There use to be a VBscript floating around that would do it, I'll have to dig that up later.

A: Some motherboards include this feature in their ROM-based setup program so it might be worth seeing if you can press a key to enter setup (often DEL, F2 or ESC) while the system is starting and have a look around.
If your motherboard or network adaptor supports 'Wake on Lan' (WOL) then you might be able to do this from your router; the How-to Geek has a bit on this:
http://www.howtogeek.com/70084/how-to-schedule-your-computer-to-wake-up-at-specific-times-with-dd-wrt/
If you have another PC that stays on you could schedule it to run a free WOL app (Google will help here) at the desired time.


text:
Q: Python define funct() "not defined" our class recently got into defining functions but I'm having trouble with a specific block of code. Upon running, my code yields a 'opChoose' is not defined. The traceback faults this line of code:
calc(opChoose,num1, num2)

The code below is the entirety of my code, only a few lines of code.
def greeting():
    print("Welcome to the calculator app!")

def menu():
    opChoose=int(input("1 for Addition, 2 for Subtraction, 3 for Multiplication, 4 for Division"))
    return opChoose

def numbers():
    num1=float(input("Enter your first value"))
    num2=float(input("Enter your second value"))
    return num1, num2

def calc(opChoose,num1, num2):
    if opChoose == "1":
        ans = num1 + num2

    elif opChoose == "2":
        ans2 = num1 - num2

    elif opChoose == "3":
        ans3 = num1 * num2

    elif opChoose == "4":
        ans4 = num1 / num2

    return ans, ans2, ans3, ans4,

def display(ans, ans2, ans3, ans4):
    if opChoose == "1":
        print(ans)

    elif opChoose == "2":
        print(ans2)

    elif opChoose == "3":
        print(ans3)

    elif opChoose == "4":
        print(ans4)

greeting()

menu()

numbers()

calc(opChoose,num1, num2)

display(ans,ans2,ans3,ans4)

I would try to simplify this code into a smaller block for you guys to troubleshoot but I simply don't know if the other bits of code is incorrect too, any help you guys could give me would be much appreciated, thanks!

A: You're doing the right thing in returning the value from the function menu() but you need to then assign that returned value to a variable to be able to pass it to the calc() function. Alternatively you can pass the function call directly to the calc() function itself.
Either this:
opChoose = menu()
calc(opChoose ,num1, num2)

or this:
calc(menu(),num1, num2)

Know that it is going to throw errors for the same reason on num1 and num2 but I think from the above you can solve that issue. Good luck and happy coding!

A: Here is a refactoring of your code.
def greeting():
    print("Welcome to the calculator app!")

def menu():
    opChoose=int(input("1 for Addition, 2 for Subtraction, 3 for Multiplication, 4 for Division"))
    return opChoose

def numbers():
    num1=float(input("Enter your first value"))
    num2=float(input("Enter your second value"))
    return num1, num2

def calc(opChoose,num1, num2):
    ans=0
    ans2=0
    ans3=0
    ans4=0
    if opChoose == 1:
        ans = num1 + num2
    elif opChoose == 2:
        ans2 = num1 - num2
    elif opChoose ==3 :
        ans3 = num1 * num2
    elif opChoose == 4:
        ans4 = num1 / num2
    return ans, ans2, ans3, ans4

def display(opChoose,ans, ans2, ans3, ans4):
    if opChoose == 1:
        print(ans)

    elif opChoose == 2:
        print(ans2)

    elif opChoose ==3:
        print(ans3)

    elif opChoose == 4:
        print(ans4)

greeting()
opChoose=menu()
num1, num2=numbers()
ans,ans2,ans3,ans4=calc(opChoose,num1, num2)
display(opChoose,ans,ans2,ans3,ans4)

*

*In your code you call menu() and other functions but you don't save the data they return. You need to assign to a variable for further processing or otherwise save the value.

*You created opChoose as int but you are comparing it with a string ("1") variable -- int 1 and "1" can never be the same.
a=1
if(a=="1"):
          print("this will never be printed")

A: Having the calculation return a lot of None variables for paths not taken seems like an ... odd design.  Perhaps look at this instead.
def greeting():
    print("Welcome to the calculator app!")

def menu():
    opChoose=int(input("1 for Addition, 2 for Subtraction, 3 for Multiplication, 4 for Division"))
    return opChoose

def numbers():
    num1=float(input("Enter your first value"))
    num2=float(input("Enter your second value"))
    return num1, num2

def calc(opChoose, num1, num2):
    # opChoose is an int; don't compare it to a string
    if opChoose == 1:
        ans = num1 + num2
    elif opChoose == 2:
        # The answer goes to the same variable in each case
        ans = num1 - num2
    elif opChoose == 3:
        ans = num1 * num2
    elif opChoose == 4:
        ans = num1 / num2

    return ans

# Very tempted to comment out this gratuitous verbosity
greeting()
# Capture the value from the function call
op = menu()
# Capture the values from the function call
n1, n2 = numbers()
# Capture the value from the function call
value = calc(op, n1, n2)
# No need for a separate function for this really
print(value)

I used different variable names in the main flow to emphasize that the variables inside the function calls are entirely different, and you cannot access variables inside a function from outside, or vice versa, without making additional explicit arrangements.
Making functions which do only one thing is a good idea in general, but perhaps this is still taking it a bit too far.  Functions which don't do anything useful in isolation are just obscuring the flow of the code.


text:
Q: Angular track by $index issue i'm using ng-repeat to render my html here is the code-snippet

        {{feed.title}}

         {{feed.link}}

This successfully sorts the list but gives an error ,Error:[ng-repeat dupes] . I saw the documentation and modified the ng-repeat line to be

i added track by $index , the error was resolved , but its not getting sorted now . Whats the solution so that the error gets resolved and the list gets sorted too ??

A: Try this: feed in feeds | orderBy:'title' track by $index"
Source: github


text:
Q: jQuery problem cloning/appending flash movie on IE8 I have a problem switching the content of a div using jQuery functions clone and append.
In a few words, I'm using two links to show and hide flash videos: link1 shows video1 and hides video2. Link2 shows video2 and hides video1.
Here's the code I have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

      <object width="300" height="225">
        <param name="movie" value="http://www.youtube.com/v/uv9RpD4bbNw?fs=1&hl=en_US&rel=0">
        </param>
        <param name="allowFullScreen" value="true">
        </param>
        <param name="allowscriptaccess" value="always">
        </param>
        <embed src="http://www.youtube.com/v/uv9RpD4bbNw?fs=1&hl=en_US&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="300" height="225"></embed>
      </object>

 View video in Spanish

      <object width="300" height="225">
        <param name="movie" value="http://www.youtube.com/v/HxBRdJCV8Os&hl=en_US&fs=1?rel=0">
        </param>
        <param name="allowFullScreen" value="true">
        </param>
        <param name="allowscriptaccess" value="always">
        </param>
        <embed src="http://www.youtube.com/v/HxBRdJCV8Os&hl=en_US&fs=1?rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="300" height="225"></embed>
      </object>

 View video in English

This is the closest thing I have done to make it work in IE. I would be easier just to use

But that doesn't work on IE: the hidden video keeps playing.
I thank you for all the ideas you want to share.
Best wishes.
Luis

A: You need to set the WMODE to 0 or transparent.  Fix'd:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

  <object width="300" height="225">
    <param name="movie" value="http://www.youtube.com/v/uv9RpD4bbNw?fs=1&hl=en_US&rel=0">
    </param>
    <param name="allowFullScreen" value="true">
    </param>
    <param name="allowscriptaccess" value="always">
    </param>
    <param name="wmode" value="transparent"></param>
    <embed src="http://www.youtube.com/v/uv9RpD4bbNw?fs=1&hl=en_US&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="300" height="225" wmode="transparent"></embed>
  </object>

 View video in Spanish

  <object width="300" height="225">
    <param name="movie" value="http://www.youtube.com/v/HxBRdJCV8Os&hl=en_US&fs=1?rel=0">
    </param>
    <param name="allowFullScreen" value="true">
    </param>
    <param name="allowscriptaccess" value="always">
    </param>
    <param name="wmode" value="transparent"></param>
    <embed src="http://www.youtube.com/v/HxBRdJCV8Os&hl=en_US&fs=1?rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="300" height="225" wmode="transparent"></embed>
  </object>

 View video in English


text:
Q: Parse arithmetic expression with javascript Is there a simple way, with javascript, to convert the following expression
e*((a*(b+c))+d)

into something like
multiply(e, add(multiply(a, add(b,c)), d))

The expression would be stored in a string. I'm open to any solution that will avoid me to write my own parser (library, buitl-in capabilities, ...)
EDIT: I should have precised that I don't actually want to use multiply and add functions, the purpose of this is to define my own function to replace multiply and add and perform custom operations on the variables

A: The expression you are trying to parse into an abstract syntax tree is a context-free expression. This means that you need a context-free grammar to be able to parse it. So let's create a parser.
To simplify the parsing we'll separate the lexical analysis phase. Hence the first thing we need is to create a lexer. Luckily there are a lot of handy lexer libraries available. We'll use the this one:
https://github.com/aaditmshah/lexer
So here's the lexical analyzer:
var lexer = new Lexer;

lexer.addRule(/\s+/, function () {
    /* skip whitespace */
});

lexer.addRule(/[a-z]/, function (lexeme) {
    return lexeme; // symbols
});

lexer.addRule(/[\(\+\-\*\/\)]/, function (lexeme) {
    return lexeme; // punctuation (i.e. "(", "+", "-", "*", "/", ")")
});

Next we create a parser. We'll use the following implementation of Dijkstra's shunting yard algorithm for parsing:
https://gist.github.com/aaditmshah/6683499
So here's the parser:
var factor = {
    precedence: 2,
    associativity: "left"
};

var term = {
    precedence: 1,
    associativity: "left"
};

var parser = new Parser({
    "+": term,
    "-": term,
    "*": factor,
    "/": factor
});

Finally we create a parse function as follows:
function parse(input) {
    lexer.setInput(input);
    var tokens = [], token;
    while (token = lexer.lex()) tokens.push(token);
    return parser.parse(tokens);
}

Now you simply call parse to get a parsed stream of tokens in postfix notation:
var output = parse("e*((a*(b+c))+d)");
alert(output.join(" "));               // "e a b c + * d + *"

The advantage of postfix form is that you can easily manipulate it using a stack:

*

*Push e onto the stack.

*Push a onto the stack.

*Push b onto the stack.

*Push c onto the stack.

*Pop b and c and push b + c onto the stack.

*Pop a and b + c and push a * (b + c) onto the stack.

*Push d onto the stack.

*Pop a * (b + c) and d and push a * (b + c) + d onto the stack.

*Pop e and a * (b + c) + d and push e * (a * (b + c) + d) onto the stack.

Similarly it's easy to create the output you want using stacks too. It the same steps. You only push different values back onto the stack for different operations.
See the demo: http://jsfiddle.net/d2UYZ/2/
Edit 1: I was so bored that I solved the problem for you:
var stack = [];

var operator = {
    "+": "add",
    "-": "subtract",
    "*": "multiply",
    "/": "divide"
};

parse("e*((a*(b+c))+d)").forEach(function (c) {
    switch (c) {
    case "+":
    case "-":
    case "*":
    case "/":
        var b = stack.pop();
        var a = stack.pop();
        stack.push(operator[c] + "(" + a + ", " + b + ")");
        break;
    default:
        stack.push(c);
    }
});

var output = stack.pop();

alert(output);

The output is (as you expect) the string "multiply(e, add(multiply(a, add(b,c)), d))". See the demo: http://jsfiddle.net/d2UYZ/4/
Edit 2: If you need to evaluate the expression you could do that easily too. All you need is a context mapping symbols to values and functions for each operator:
var stack = [];

var context = {
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4,
    "e": 5
};

var operator = {
    "+": function (a, b) { return a + b; },
    "-": function (a, b) { return a - b; },
    "*": function (a, b) { return a * b; },
    "/": function (a, b) { return a / b; }
};

parse("e*((a*(b+c))+d)").forEach(function (c) {
    switch (c) {
    case "+":
    case "-":
    case "*":
    case "/":
        var b =+ stack.pop();
        var a =+ stack.pop();
        stack.push(operator[c](a, b));
        break;
    default:
        stack.push(context[c]);
    }
});

var output = stack.pop();

Thus the expression e*((a*(b+c))+d) becomes 5*((1*(2+3))+4) which evaluates to 45. See the demo: http://jsfiddle.net/d2UYZ/6/

A: You cannot do this with eval as has been suggested, because you would not be able to use your custom add and multiply functions that way. You could parse out all of the operators with regular expressions, but it would not be easy.
You would have to make sure you got the order of operations correct, and break it into many steps.
The basic logic of it would be:

*

*Define your add and multiply functions.

*Define a function that takes a string of numbers and operators (without parentheses) and splits it into binary operations (ie. '1 + 7' or '5 * 3') with regular expressions, that can be passed to your add and multiply functions. This would have to be done recursively, following your desired order of operations for your custom math, in other words, if you get '5 + 3 * 2' you will have parse out '3 * 2' and evaluate that before using its result to add to 5 (assuming your order would be multiply first).

*Define a function that looks for parentheses and recursively finds the innermost set and passes it to function 2 above to be evaluated.

*Pass your input string to function 3 above and hope that you got all of the recursive logic and regular expressions correct.

A: I think the better way is define your own functions like this:
multiply = function(a, b) {
    return a *  b;
}

add = function(a, b) {
    return a +  b;
}

This examples is limited to only two numbers, but it can be scaled using arguments.
Fiddle


text:
Q: Can I share a crystal between two AT89S52? Is this method correct? I have a project which I will need two 8051 microcontroller on a board.
I want to reduce its size and cost, so I tried to use one crystal for two microcontroller, but just connect them parallel doesn't work.
One of my friend said that I can try connect normally on one of the chip (chip A), and short the xtal2 from chipA to xtal1 from chipB.
(Not connecting anything on the xtal2 from chipB)
Is this the right way to do it? Do I need to change any code?
I've tried but I failed, so I need some suggestion.

A: You can connect XTAL2 (clock OUT) of the master chip (the one with the crystal) to XTAL1 (clock IN) of the slave chip and leave XTAL2 (clock OUT) on the slave chip open.
This should work if the chips are close together. If you are running them over a distance a buffer from the XTAL2 output of the master would be a good idea.
Or (better) use a crystal oscillator rather than a raw crystal and drive both chips with the external clock (XTAL1 and each, leave XTAL2 open on both). Pretty cheap, guaranteed stable and start-up and good drive capability.
The code would not change, assuming the clock frequency is the same as what the programs were designed for.
Edit: You should slightly reduce the load capacitor on the XTAL 2 line to account for the increased capacitance of the second input. 5pF is about right. Not important if you don't care about the exact clock frequency.

A: I have used the following circuit to share one crystal between two devices -- not a microcontroller, but two UART expanders which internally have a similar clock circuit with XTAL1 and XTAL2 leads.

The lines on the left are simply the power and ground for the 74HC04 chip.  VCC is 3.3V in this case.  As you can see, the second HC04 gate drives the XTAL1 line(s), while the XTAL2 lines are left unconnected.  Because of the HC04, this circuit has more of a capability to drive multiple devices than simply connecting the same crystal to the XTAL1 lead of each one.
I have left off the frequency of the crystal, and the value of the capacitors (typically 22pf) off of the circuit, since they will be dependent on whatever you are already using.


text:
Q: I need to add date translations for taglib fmt:formatDate I need to translate my application to multiple languages, including Tongan and Samoan. These are not valid Locale objects, so when I try to use things like the taglib fmt:formatDate, it just shows up in English.
I have translations, but I don't know how to tell formatDate how to use them. I could make my own taglib, but I don't want the overhead and maintenance nightmare of replacing all existing tags with a new one (very large application).
Any suggestions?

A: I think I just found the answer:
Format date in JSP for unsupported Locale
Which states:
If using Java 6, APIs have been exposed to allow you to add localization support to locales that are not supported by the JRE itself. See the "Local sensitive services" section in the following link for a brief overview: http://www.oracle.com/technetwork/articles/javase/i18n-enhance-137163.html
An alternative option is to build your own custom tag which uses custom resource bundles to display the month in the correct language.


text:
Q: Windows Phone 7.5 / 8 push notifications and PhoneGap we developed a mobile application with PhoneGap. So far it runs fine with WinPhone, iOS, Android and Firefox OS.
We now want to add Push notifications to the app. Basically we can choose which server backend to use. Since the project is already JS-heavy (ember.js) we started with Node.js and are using node-apn and node-gcm to send notifications to iOS and Android.
Is it even possible to have a PhoneGap application register with the MPNS? So far it seems to me that only native C# Applications can register with their server as a valid endpoint (the node.js plugin for MPNS requires this endpoint to send notifications).
It seems Pushwoosh's phonegap plugin works for windows phone, but only with their service. Or did I misread something there?
The reason we wanted to have a self controlled notification server is to push notifications to Firefox OS. None of the push-services seem to support this OS yet.
Any thoughts on this topic are welcome, thx in advance.
Cheers
Tom

A: The Cordova Push Notifications Plugin added support for Windows Phone 8 recently.
With this plugin, you can now receive and handle Push Notifications on Android, iOS and Windows Phone 8 devices conveniently.


text:
Q: Tile/grid movement in Java (2d game) I just started game-making. I did follow a tutorial on Youtube from CodeNMore, but I do not like the pixel-based movement system. I wanted to make a grid-based movement system, but I couldn't work out how can I do this.
I am not advanced enough to read some1 else code and understand how it works, that's why i ask you guys!
My tiles are 64x64, so what I do is change x value by 64. It doesn't help me because my character starts to teleport all the 64 pixels at once instead of moving smoothly pixel by pixel for 64 pixels (tile size). I tried using for-loops, timers, and thread.sleep, but it didn't really help me.
//Activate both of the movement methods.
public void move() throws InterruptedException {

    if (!checkEntityCollisions(xMove, 0f)) {
        moveX();
    }
    if (!checkEntityCollisions(0f, yMove)) {
        moveY();
    }

    System.out.println("Pos x: " + x + "\n Pos y: " + y);

}

//MOVEMENT METHOD

public void moveX() throws InterruptedException {
    timer += System.currentTimeMillis() - lastTime;
    lastTime = System.currentTimeMillis();

    if (xMove > 0) { // MOVING RIGHT

        int tx = (int) (x + xMove + bounds.x + bounds.width) / Tile.TILEWIDTH;

        //Checks for collisions
        if (!collisionWithTile(tx, (int) (y + bounds.y) / Tile.TILEHEIGHT)
                && !collisionWithTile(tx, (int) (y + bounds.y + bounds.height) / Tile.TILEHEIGHT)) {

            //tileSize = 64
            x += tileSize;

        } else {
            x = tx * Tile.TILEWIDTH - bounds.x - bounds.width - 1;
        }

    } else if (xMove < 0) { //MOVING LEFT

        int tx = (int) (x + xMove + bounds.x) / Tile.TILEWIDTH;

        if (!collisionWithTile(tx, (int) (y + bounds.y) / Tile.TILEHEIGHT)
                && !collisionWithTile(tx, (int) (y + bounds.y + bounds.height) / Tile.TILEHEIGHT)) {

            x -= tileSize;

        } else {
            x = tx * Tile.TILEWIDTH + Tile.TILEWIDTH - bounds.x;
        }
    }

}

//Graphics code:
private Display display;
private int width, height;

public String title;
public boolean running = false;

private Thread thread;

private BufferStrategy bs;
private Graphics g;

//STATES
private State gameState;
private State menuState;

//INPUT
private KeyManager keyManager;

//CAMERA
private GameCamera gameCamera;

//Handler
private Handler handler;

//GAME ENGINE
public Game(String title, int width, int height) {

    this.height = height;
    this.width = width;
    this.title = title;
    keyManager = new KeyManager();

}

public void init() {

    display = new Display(title, width, height);
    display.getFrame().addKeyListener(keyManager);
    Assets.init();

    gameCamera = new GameCamera(this, 0, 0);
    handler = new Handler(this);

    gameState = new GameState(handler);
    menuState = new MenuState(handler);
    State.setState(gameState);
}

public void tick() {

    keyManager.tick();

    if (State.getState() != null) {
        State.getState().tick();
    }
}

public void render() {

    bs = display.getCanvas().getBufferStrategy();
    if (bs == null) {
        display.getCanvas().createBufferStrategy(3);
        return;
    }
    g = bs.getDrawGraphics();

    //Clear Screen
    g.clearRect(0, 0, width, width);

    //Draw here!
    if (State.getState() != null) {
        State.getState().render(g);
    }

    //End Drawing
    bs.show();
    g.dispose();
}

public void run() {
    init();

    int fps = 60;
    double timePerTick = 1000000000 / fps;
    double delta = 0;
    long now;
    long lastTime = System.nanoTime();

    while (running) {

        now = System.nanoTime();
        delta += (now - lastTime) / timePerTick;
        lastTime = now;

        if (delta >= 1) {
            tick();
            render();
            delta--;
        }

    }
    stop();
}

public int getWidth() {
    return width;
}

public void setWidth(int width) {
    this.width = width;
}

public int getHeight() {
    return height;
}

public void setHeight(int height) {
    this.height = height;
}

public KeyManager getKeyManager() {
    return keyManager;
}

public GameCamera getGameCamera() {
    return gameCamera;
}

public synchronized void start() {

    if (running) {
        return;
    }
    running = true;
    thread = new Thread(this);
    thread.start();
}

public synchronized void stop() {
    if (!running) {
        return;
    }
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

}


text:
Q: Python Script for Art Museum Installation intermittently locks up, Removing Thermal Camera Sensor read function seems to work? I have a python script for an installation in an art museum that is meant to run continuously playing sounds, driving an LED matrix, and sensing people via OpennCV and a thermal camera.
Each of the parts of the script work and all of them work together but randomly the script locks up and I need to restart it.  I want to script to not lock up so no one has to reset it during the exhibition.
I have the code running on a spare Raspberry Pi and a spare LED matrix and it continues to cycle through fine.  The only changes that I made were commenting out the start of a thread to check the IR sensor and a call to a function to get the max temp from the sensor.
To be clear, if I leave these bits of code in the script runs fine 1 -3 or sometimes 10 times.  But it seems to lock up in the first "state" when IRcount = 0
I am stuck.  Any help is greatly appreciated.
```
#!/usr/bin/python
import glob
import queue
import sys
import pygame
import cv2
import random
import math
import colorsys
import time
from rpi_ws281x import *
from PIL import Image
import numpy as np
import threading
global thresh

sys.path.insert(0, "/home/pi/irpython/build/lib.linux-armv7l-3.5")
import MLX90640 as mlx

currentTime = int(round(time.time() * 1000))
InflateWait = int(round(time.time() * 1000))
minTime = 6000
maxTime = 12000
lineHeight1 = 0
lineHue1 = float(random.randrange(1,360))/255

# IR Functions

# Function to just grab the Max Temp detected. If over threshold then start
# the sequence, if not stay in state 0
def maxTemp():
  mlx.setup(8) #set frame rate of MLX90640

  f = mlx.get_frame()

  mlx.cleanup()

  # get max and min temps from sensor
  # v_min = min(f)
  v_max = int(max(f))
  return v_max

# Function to detect individual people's heat blob group of pixels
# run in a thread only at the end of the script
def irCounter():
    img = Image.new( 'L', (24,32), "black") # make IR image

    mlx.setup(8) #set frame rate of MLX90640

    f = mlx.get_frame()

    mlx.cleanup()

    for x in range(24):
        row = []
        for y in range(32):
            val = f[32 * (23-x) + y]
            row.append(val)
            img.putpixel((x, y), (int(val)))

    # convert raw temp data to numpy array
    imgIR = np.array(img)

    # increase the 24x32 px image to 240x320px for ease of seeing
    bigIR = cv2.resize(depth_uint8, dsize=(240,320), interpolation=cv2.INTER_CUBIC)

    # Use a bilateral filter to blur while hopefully retaining edges
    brightBlurIR = cv2.bilateralFilter(bigIR,9,150,150)

    # Threshold the image to black and white
    retval, threshIR = cv2.threshold(brightBlurIR, 26, 255, cv2.THRESH_BINARY)

    # Define kernal for erosion and dilation and closing operations
    kernel = np.ones((5,5),np.uint8)

    erosionIR = cv2.erode(threshIR,kernel,iterations = 1)

    dilationIR = cv2.dilate(erosionIR,kernel,iterations = 1)

    closingIR = cv2.morphologyEx(dilationIR, cv2.MORPH_CLOSE, kernel)

    # Detect countours
    contours, hierarchy = cv2.findContours(closingIR, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    # Get the number of contours ( contours count when touching edge of image while blobs don't)
    ncontours = str(len(contours))

    # Show images in window during testing
    cv2.imshow("Combined", closingIR)

    cv2.waitKey(1)

#initialize pygame
pygame.init()
pygame.mixer.init()
pygame.mixer.set_num_channels(30)
print("pygame initialized")

# assign sound chennels for pygame
channel0 = pygame.mixer.Channel(0)
channel1 = pygame.mixer.Channel(1)
channel2 = pygame.mixer.Channel(2)
channel3 = pygame.mixer.Channel(3)
channel4 = pygame.mixer.Channel(4)
channel5 = pygame.mixer.Channel(5)
channel6 = pygame.mixer.Channel(6)
channel7 = pygame.mixer.Channel(7)
channel8 = pygame.mixer.Channel(8)
channel9 = pygame.mixer.Channel(9)
channel10 = pygame.mixer.Channel(10)
channel11 = pygame.mixer.Channel(11)
channel12 = pygame.mixer.Channel(12)
channel13 = pygame.mixer.Channel(13)
channel14 = pygame.mixer.Channel(14)
channel15 = pygame.mixer.Channel(15)
channel16 = pygame.mixer.Channel(16)
channel17 = pygame.mixer.Channel(17)
channel18 = pygame.mixer.Channel(18)
channel19 = pygame.mixer.Channel(19)
channel20 = pygame.mixer.Channel(20)
channel21 = pygame.mixer.Channel(21)
channel22 = pygame.mixer.Channel(22)
channel23 = pygame.mixer.Channel(23)
channel24 = pygame.mixer.Channel(24)
channel25 = pygame.mixer.Channel(25)
channel26 = pygame.mixer.Channel(26)
channel27 = pygame.mixer.Channel(27)
channel28 = pygame.mixer.Channel(28)

# load soundfiles
echoballs = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/echo balls FIX.ogg")
organbounce = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/ORGAN BOUNCE fix.ogg")
jar = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/jar whoop fix.ogg")
garland = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/GARLAND_fix.ogg")
dribble= pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/dribble.ogg")
cowbell = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/cowbell fix.ogg")
clackyballs = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/clacky balls boucne.ogg")
burpees = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/burpees_fix.ogg")
brokensynth = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/broken synth bounce.ogg")
woolballs = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/wool balls in jar FIX.ogg")
wiimoye = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/wiimoye_fix.ogg")
warpyorgan = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/warpy organ bounce#.2.ogg")
vibrate = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/vibrate fix.ogg")
turtlesbounce = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/turtles fix.ogg")
timer = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/timer.ogg")
tape = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/tape fix.ogg")
tambourine = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/TAMBOURINE.ogg")
springybounce = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/springy bounce.ogg")
smash3 = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/smash fix.ogg")
bristle2 = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/BRISTLE FIX.ogg")
blackkeys = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/black keys FIX.ogg")
zipper = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/zipper.ogg")

presatisfactionsweep = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/pre-satisfaction sweep .ogg")
satisfaction = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/SATISFACTION.ogg")
altsatisfaction = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/alt_satisfaction_trimmed.ogg")
solosatisfaction = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/SOLO_SATISFACTION.ogg")
print("sound files loaded")

# initializing sounds list
soundsList = [echoballs, organbounce, zipper, jar, garland, dribble, cowbell, clackyballs, burpees, brokensynth, woolballs,
       wiimoye, warpyorgan, vibrate, turtlesbounce, timer, tambourine, springybounce, smash3, bristle2, blackkeys, zipper       ]

IRcount = 0 # define initial state for main loop
pygame.display.set_mode((32, 8))
print("pygame dispaly open")

# LED strip configuration:
LED_COUNT      = 256      # Number of LED pixels.
LED_PIN        = 18      # GPIO pin connected to the pixels (18 uses PWM!).
#LED_PIN        = 10     # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).
LED_FREQ_HZ    = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA        = 10      # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 100     # Set to 0 for darkest and 255 for brightest
LED_INVERT     = False   # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL    = 0       # set to '1' for GPIOs 13, 19, 41, 45 or 53

# Define functions which animate LEDs in various ways.

# PNG to LED function used to shuffle througfh folders of numbered PNGs exported
# from animations created
def pngToLED (strip, pngfile):
    RGBimage = Image.open(pngfile).convert('RGB')
    np_image = np.array(RGBimage)
    colours = [Color(x[0],x[1],x[2]) for rows in np_image for x in rows]
    colours2d = np.reshape(colours, (32, 8), order='F')
    colours2d[1::2, :] = colours2d[1::2, ::-1]
    pic = colours2d.flatten('C')
    for i in range( 0, strip.numPixels(), 1 ):# iterate over all LEDs - range(start_value, end_value, step)
        strip.setPixelColor(i, int(pic[ i ]))
    strip.show()

def colorWipe(strip, color,wait_ms=10):
    """Wipe color across display a pixel at a time."""
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, color)
    strip.show()
    time.sleep(1)

def theaterChase(strip, color, wait_ms, iterations=10):
    """Movie theater light style chaser animation."""
    for j in range(iterations):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i+q, color)
            strip.show()
            time.sleep(wait_ms/1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i+q, 0)

def wheel(pos):
    """Generate rainbow colors across 0-255 positions."""
    if pos < 85:
        return Color(pos * 3, 255 - pos * 3, 0)
    elif pos < 170:
        pos -= 85
        return Color(255 - pos * 3, 0, pos * 3)
    else:
        pos -= 170
        return Color(0, pos * 3, 255 - pos * 3)

def rainbow(strip, wait_ms=20, iterations=1):
    """Draw rainbow that fades across all pixels at once."""
    for j in range(256*iterations):
        for i in range(strip.numPixels()):
            strip.setPixelColor(i, wheel((i+j) & 255))
        strip.show()
        time.sleep(wait_ms/1000.0)

def rainbowCycle(strip, wait_ms=20, iterations=5):
    """Draw rainbow that uniformly distributes itself across all pixels."""
    for j in range(256*iterations):

        for i in range(strip.numPixels()):
            strip.setPixelColor(i, wheel((int(i * 256 / strip.numPixels()) + j) & 255))
        strip.show()
        time.sleep(wait_ms/1000.0)

def theaterChaseRainbow(strip, wait_ms=90):
    """Rainbow movie theater light style chaser animation."""
    for j in range(256):
        for q in range(3):
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i+q, wheel((i+j) % 255))
            strip.show()
            time.sleep(wait_ms/1000.0)
            for i in range(0, strip.numPixels(), 3):
                strip.setPixelColor(i+q, 0)

# Plasma LED Function from Root 42
def plasmaLED (plasmaTime):
    h = 8
    w = 32
    out = [ Color( 0, 0, 0 ) for x in range( h * w ) ]
    plasmaBright = 100.0
    for x in range( h ):
        for y in range( w ):
            hue = (4.0 + math.sin( plasmaTime + x ) + math.sin( plasmaTime + y / 4.5 ) \
                + math.sin( x + y + plasmaTime ) + math.sin( math.sqrt( ( x + plasmaTime ) ** 2.0 + ( y + 1.5 * plasmaTime ) ** 2.0 ) / 4.0 ))/8
            hsv = colorsys.hsv_to_rgb( hue , 1, 1 )
            if y % 2 == 0: #even
                out[ x + (h * y)] = Color( *[ int( round( c * plasmaBright ) ) for c in hsv ] )
            else: #odd
                out[ (y * h) + (h -1 -x) ] = Color( *[ int( round( c * plasmaBright ) ) for c in hsv ] )
    for i in range( 0, strip.numPixels(), 1 ):# iterate over all LEDs - range(start_value, end_value, step)
        strip.setPixelColor(i, out[ i ]) # set pixel to color in picture
    strip.show()

# variables for plasma
plasmaTime = 5.0 # time
plasmaSpeed = 0.05 # speed of time

# thread for IRcounter function
class TempTask:

    def __init__(self):
        self.ir_temp = 0
        self.lock = threading.Lock() #control concurrent access for safe multi thread access
        self.thread = threading.Thread(target=self.update_temp)

    def update_temp(self):
        while True:
            with self.lock:
                self.ir_temp = irCounter()
            time.sleep(0.1)

    def start(self):
        self.thread.start()

# Millis timer count function
def CheckTime( lastTime,  wait):
  if currentTime - lastTime >= wait:
    lastTime += wait
    return True
  return False

# Main program logic follows:
if __name__ == '__main__':

    # not currently starting the trhead because program is locking up without it
    # want to figure out initial problem first
    #start thread
    #task = TempTask()
    #task.start()

    # Create NeoPixel object with appropriate configuration.
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
    # Intialize the library (must be called once before other functions).
    strip.begin()

    print ('Press Ctrl-C to quit.')

    try:
        while True:
            currentTime = int(round(time.time() * 1000))

            if IRcount == 0:

                #random solid color
                colorWipe(strip, Color(random.randint(60,255), random.randint(60,255), random.randint(60,255)))

                # use random.sample() to shuffle sounds list
                shuffledSounds = random.sample(soundsList, len(soundsList))
                if pygame.mixer.Channel(0).get_busy() == False: channel0.play(shuffledSounds[0],loops = -1)
                thresh = 0
                '''
                # the threshold check below is the only thing I have taken out of
                # Program on my test Raspberry Pi.  It seems to not lock up without it
                # not sure why this would be a problem.

                thresh = int(maxTemp())
                print (thresh)
                if thresh >= 27:
                  InflateWait = int(round(time.time() * 1000))
                  print (thresh)
                  IRcount = 1
                  print("Threshold Temp Detected: Begin Sound Sequence")
                else:
                  IRcount = 0
                  '''
                if CheckTime(InflateWait,random.randint(minTime, maxTime)):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)

            elif IRcount == 1:
                LEDimages = glob.glob("/home/pi/ruff-wavs/Crystal_Mirror/*.png")
                for LEDimage in sorted(LEDimages):
                  pngToLED (strip, LEDimage)
                if pygame.mixer.Channel(1).get_busy() == False:
                  channel1.play(shuffledSounds[1],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)

            elif IRcount == 2:
                LEDimages = glob.glob("/home/pi/ruff-wavs/Mercury_Loop/*.png")
                for LEDimage in sorted(LEDimages):
                  pngToLED (strip, LEDimage)
                if pygame.mixer.Channel(2).get_busy() == False:
                  channel2.play(shuffledSounds[2],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)

            elif IRcount == 3:
                LEDimages = glob.glob("/home/pi/ruff-wavs/Pink_Lava/*.png")
                for LEDimage in sorted(LEDimages):
                  pngToLED (strip, LEDimage)
                if pygame.mixer.Channel(3).get_busy() == False:
                  channel3.play(shuffledSounds[3],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)

            elif IRcount == 4:
                LEDimages = glob.glob("/home/pi/ruff-wavs/Horiz_Mosaic/*.png")
                for LEDimage in sorted(LEDimages):
                  pngToLED (strip, LEDimage)
                if pygame.mixer.Channel(4).get_busy() == False:
                  channel4.play(shuffledSounds[4],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)

            elif IRcount == 5:
                plasmaLED()
                plasmaTime = plasmaTime + plasmaSpeed  # increment plasma time
                if pygame.mixer.Channel(5).get_busy() == False:
                  channel5.play(shuffledSounds[5],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)

            elif IRcount == 6:
                LEDimages = glob.glob("/home/pi/ruff-wavs/Radio_Loop/*.png")
                for LEDimage in sorted(LEDimages):
                  pngToLED (strip, LEDimage)
                if pygame.mixer.Channel(6).get_busy() == False:
                  channel6.play(shuffledSounds[6],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)

            elif IRcount == 7:
                LEDimages = glob.glob("/home/pi/ruff-wavs/Star_Loop/*.png")
                for LEDimage in sorted(LEDimages):
                  pngToLED (strip, LEDimage)
                if pygame.mixer.Channel(7).get_busy() == False:
                  channel7.play(shuffledSounds[7],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1

            elif IRcount == 14:
                plasmaLED()
                plasmaTime = plasmaTime + plasmaSpeed  # increment plasma time
                if pygame.mixer.Channel(14).get_busy() == False:
                  channel14.play(shuffledSounds[14],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)
                  print (thresh)

            elif IRcount == 15:
                plasmaLED()
                plasmaTime = plasmaTime + plasmaSpeed  # increment plasma time
                if pygame.mixer.Channel(15).get_busy() == False:
                  channel15.play(shuffledSounds[15],loops = -1)
                  waitTime = random.randint(minTime, maxTime)
                if CheckTime(InflateWait,waitTime):
                  InflateWait = int(round(time.time() * 1000))
                  IRcount += 1
                  print(IRcount)

            elif IRcount == 16:
                # random color theater chase increment random ms to speed up with sounds
                theaterChase(strip, Color(random.randint(1,255), random.randint(1,255), random.randint(1,255)), random.randint(40,50))
                pygame.mixer.fadeout(45000)
                if pygame.mixer.Channel(22).get_busy() == False:
                  channel22.play(presatisfactionsweep)
                IRcount = 17
                print(IRcount)
                print("sweep end start")

            elif IRcount == 18:
                 # random color theater chase increment random ms to speed up with sounds
                theaterChase(strip, Color(random.randint(1,255), random.randint(1,255), random.randint(1,255)), random.randint(30,40))
                if pygame.mixer.Channel(22).get_busy() == False:
                    pygame.mixer.stop()
                    channel23.play(satisfaction)
                    IRcount = 19
                    print(IRcount)
                    print("Play Satisfaction Sount")

            elif IRcount == 19:
                rainbowCycle(strip, 5)
                if pygame.mixer.Channel(23).get_busy() == False: IRcount = 0

    except KeyboardInterrupt:
       colorWipe(strip, Color(0,0,0), 1)
       pygame.mixer.stop()
       pygame.quit()
```

Update 1 - Suspected Function(s)
When I left the script run overnight and came to the exhibit in the morning it would be stuck in the 1st state IRcount = 0 The only things that happen in that state is the maxTemp() function to get the max temp, the LED color wipe function to cycle colors.
When I would come in in the morning it would be stuck, playing a single sound from pygame, as it should, but it would not be cycling colors.  I removed the maxTemp() from my test Pi and it has been working fine.
    def maxTemp():
          mlx.setup(8) #set frame rate of MLX90640

          f = mlx.get_frame()

          mlx.cleanup()

          # get max and min temps from sensor
          # v_min = min(f)
          v_max = int(max(f))
          return v_max

Update # 2
I thought that the thread might be the problem so I commented out the thread start call.  That is why I made the simpler maxTemp() function to see if that would work better than the thread.  So when I was using the max temp then the thread wasn't being called.
I don't understand threads very well.  Is it possible to have the max temp variable update continuously and have the simple OpenCV numPy manipulations running continuously?  That would be ideal.  When I originally added the thread it seemed to stop after a few cycles.
I do not have a join on the thread. I know threads don't "restart" but do I need to call it again as the state machine starts again?
    # not currently starting the thread because program is locking up without it
        # want to figure out initial problem first
        #start thread
        #task = TempTask()
        #task.start()

Update #3
I Uploaded new code that eliminated the duplicate functions.  Everything is handled in the thread temp.task now.  That seems to work fine.  I also put the github suggestion of polling the thermal sensor if the image is a duplicate but that has not happened.
I left the program run over night and when I came in in the morning it was locked up.  The SD card is set to read only mode.  I ssh'd into the pi. I have my auto start python script in /etc/profile
It seems to start the script each time I log into ssh.  When I logged in this morning to see if the pi was still up it game an out of memory error.
```
Traceback (most recent call last):
  File "/home/pi/ruff-wavs/shufflewavdemo.py", line 210, in <module>
    altsatisfaction = pygame.mixer.Sound("/home/pi/ruff-wavs/sounds/alt_satisfaction_trimmed.ogg")
pygame.error: Unable to open file '/home/pi/ruff-wavs/sounds/alt_satisfaction_trimmed.ogg'
OSError: [Errno 28] No space left on device

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.5/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/usr/local/lib/python3.5/dist-packages/virtualenvwrapper/hook_loader.py", line 223, in <module>
    main()
  File "/usr/local/lib/python3.5/dist-packages/virtualenvwrapper/hook_loader.py", line 145, in main
    output.close()
OSError: [Errno 28] No space left on device
-bash: cannot create temp file for here-document: No space left on device

Could that be because it is in read only mode?

I used this script to switch from writable to read only and back.
[https://github.com/JasperE84/root-ro][1]

  [1]: https://github.com/JasperE84/root-ro

A: I suspect the issue is that you're accessing the mlx device both in the main thread via maxTemp() as well as in the irCounter() thread. The fact that it works when you take out the maxTemp call, and that that call happens in the if IRcount == 0: state supports this.
I would add the maxTemp functionality to the irCounter thread, so that accessing it from only a single thread; and update a global variable (protected by a lock) with the maxTemp results if you need to retain this functionality.


text:
Q: Print sql rows with no fixed columns I have a mysql table called MYTABLE and a sample follows from this table.
COL1  COL2  COL3  COL4  COL5   COL6   COL7   COL8   COL9   COL10
25     32
12     34    22
7
35     10    5     12
2      13    47     3     66

Assume that this table has lots of columns and rows but as you see not all column cells are filled.
I use the following code to create a html table with results from this table:
$query = "SELECT * FROM MYTABLE";

$result = mysql_query($query);

$tableresult = "
";

$row = mysql_fetch_array($result);

while($row = mysql_fetch_array($result)) {
  $tableresult .= "
" . $row['COL1'] . "	" . $row['COL2'] . "	" . $row['COL3'] . "
";

}

$tableresult .= "
";
echo $tableresult;

First of all, if I want my final printed table in $tableresult to look like the MySQL table is this the right syntax? When I mean right syntax, I mean the same visual format as the SQL table.
And the main issue is that I need to create rows with columns till a column in SQL table has null value.At this example, the creation of the table should stop at COL5 because all rows don't have data after.
Thank you in advance!


text:
Q: Compartir facebook Include PHP Tengo un dos botones para compartir contenido de una página web (uno de fb y uno de tw).

estoy utilizando inlcude para repetir el contenido en todas las páginas <?php include 'share.php';?>. El problema es que facebook me pide una url específica para cada página, ¿cómo puedo lograr esto si include solo me permite repetir contenido? Hay forma de detectar la url según la página en donde me encuentre?. Con Twitter no hay problema (lo detecta automáticamente).

Comparte:

            Facebook

            Twitter

A: Si dejas la URL vacía (el parámetro u), entonces Facebook automáticamente tomará la URL de la página en la que esté el botón de compartir.
Así por ejemplo, el siguiente código abrirá una ventana con la URL de la página que lo contiene:

  Facebook

Si prefieres escribir una URL, entonces deberías mirar esta otra pregunta de SOes, en la que se explica lo que buscas: ¿Cómo obtener la URL completa en PHP?


text:
Q: Crash when building C++ program in Visual Studio with "Use Link Time Code Generation" enabled, only for x64 platform I have two C++ Visual Studio (16.5.0 Preview 2.0) projects: a library and an application that uses it. The library project produces four .lib files (for x86/x64 and release/debug), which the other statically links against. The application was until recently working fine in all configurations. Then recently I modified the library and rebuilt the .libs, and now when I build the application for x64 with "Use Link Time Code Generation" enabled, it crashes at runtime with an (apparently impossible) access violation. Note that the x86 build works with or without LTCG, and the x64 build works without it ("No Whole Program Optimization"). I've tried clean builds of both solutions and double-checked that I'm linking against the correct .lib.
This probably isn't a lot to go on, but does anyone have an inkling what the issue could be? Could VS's LTCG somehow cause the linker to use the old code?


text:
Q: Informal Equivalents of Mathematica "Set" and "SetDelayed" How would one distinguish between what is meant by Mathematica's "Set" and "SetDelayed" functions in informal mathematical notation? Is there a way to make this distinction any any reasonably standard formal logics? Also, how is informal mathematical notation and formal logic notation related to Mathematica's use of variables like 'x_'?  Here is the relevant part of the Mathematica documentation:
http://reference.wolfram.com/mathematica/howto/CreateDefinitionsForVariablesAndFunctions.html

A: Since Mathematica is fundamentally a rewriting system, we can use the concept of a Normal Form to address your question.
We can formalize the behavior of Mathematica this way to get at your question. Consider two sets of rewrite rules, which will store all the rules you enter into Mathematica. In the first set, which we'll call Eager, all the right-hand sides of the rules are rewritten immediately to their respective normal forms. In the second set, however, which we'll call Lazy, no such rewriting takes place. The correspondence with Mathematica is that Eager is the default, including the Set command and the read-eval-print loop; SetDelayed corresponds with Lazy.
Following the example in the Mathematica documentation, entering y = 4 at the prompt puts the rewrite rule $y \rightarrow 4$ into the Eager set:
Eager = $\{y \rightarrow 4\}$,
Lazy = $\{\}$
Entering z := y^2 at the prompt puts the rule $z \rightarrow y^2$ into the Lazy set:
Eager = $\{y \rightarrow 4\}$,
Lazy = $\{z \rightarrow y^2\}$
Entering z at the prompt causes z to be rewritten to its normal form using the union of Eager and Lazy.
$z \Rightarrow 16$
Now if we enter y = 3 at the prompt, the rule that's already there is replaced:
Eager = $\{y \rightarrow 3\}$,
Lazy =  $\{z \rightarrow y^2\}$
So entering z again causes it to be rewritten to its normal form:
$z \Rightarrow 9$
The logic underlying this example is equational, that is, first-order logic with functions and equality. In this setting, rewrite rules are simply equations with a preferred direction.
As for variables like x_, I don't see anything corresponding in rewrite rules to this kind of notation. My guess is that this formalism is designed to inhibit the default Mathematica evaluator, since if we already have x = 3 and type the following into Mathematica....
f[x] := x^2
... we'd get
f[3] := x^2
...which is clearly not what we want. Rewrite systems avoid this problem by not usually making constant bindings like x = 4 into rewrite rules. This is necessary since it's important to be able to rewrite the left-hand sides of rewrite rules into their normal forms, not just the right-hand sides.

A: QUESTION 1: How would one distinguish between what is meant by Mathematica's "Set" and "SetDelayed" functions in informal mathematical notation?
Set vs. SetDelayed
f[x_] = Expand[x^2]
x^2
{f[3], f[3.5], f[x + 1]}
{9, 12.25, (x+1)^2}
f[x+1] is not expanded because that was evaluated when f was defined.
Also Set is evaluated once for certain definitions.
r1 = Random[];
{r1, r1, r1}
{0.937245,0.937245,0.937245}
SetDelayed is evaluated each time.
r2 := Random[];
{r2, r2, r2}
{0.687744,0.629629,0.732141}
Clear["`*"]
f[x_] := Expand[x^2]
Notice when you evaluate this expression, there is no output.  That's because the rhs is held until the function f  is evaluated.
{f[24],f[x + 2],f[(h - 4)^3]}
{576, x^2+4 x+4, h^6-24 h^5+240 h^4-1280 h^3+3840 h^2-6144 h+4096}
Now everything works because Expand is evaluated after f gets its input.
QUESTION 3:  Also, how is informal mathematical notation and formal logic notation related to Mathematica's use of variables like 'x_'?
The underscore is what Mathematica uses to show input variables.  It is used with Set and SetDelayed.  Even f[x_] is evaluated without :=.
f[x_]
x_^2
The human mind knows that the x in f(x) is the input.  Computers don't unless you tell them.
QUESTION 2: Is there a way to make this distinction any any reasonably standard formal logics?
I have never seen it.  The human mind would always evaluate like a SetDelayed definition, wouldn't it?
Here's a link to the notebook.  Hope this helps.


text:
Q: Having issue displaying JSP page in Spring-MVC I am having issue to display jsp page in Spring-MVC.
This is a basic hello world Spring-MVC with Gradle and IntelliJ CE:
I get the following error page:

Here is my build.gradle:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE")
    }
}

plugins {
    id 'java'
}

group 'com.helloct'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-serving-web-content'
    version =  '0.1.0'
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'

    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    compile("org.springframework.boot:spring-boot-devtools")

    compile("org.springframework.boot:spring-boot-starter")
    compile("org.springframework:spring-jdbc")
    compile("com.h2database:h2")

    compile("com.fasterxml.jackson.core:jackson-databind")

    compile('javax.servlet:jstl')
    compile('org.apache.tomcat.embed:tomcat-embed-jasper')

    compile 'javax.servlet.jsp:javax.servlet.jsp-api'

    testCompile("junit:junit")
}

the The view resolver file:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "hello")
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

The controller page:
@Controller
public class JSPController {
    @GetMapping("/jspPage")
    public String home(){
        return "jspPage";
    }
}

The jsp page location:

Content of the application.properties file:
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

Using the default template engine, the page displays correctly but using jsp, it doesn't work
Log error:
https://hastebin.com/lijekesoti.apache
NOTE: I know Thymleleaf is the recommanded template for Spring but I want work with JSP for some reason

UPDATE
After reading this post with the help of paulsm4 answer, removing the following line:
compile("org.springframework.boot:spring-boot-starter-thymeleaf")

and removing the view resolver file solved my issue.

A: It turns out that it's non-trivial to get JSPs to work with Spring Boot. It also turns out that there are significant changes between Spring Boot 1.x (which most of the tutorials for Spring Boot/JSP were written to) and Spring Boot 2.x.
I found these resources helpful:

*

*Navin Reddy: Web App Using Spring Boot

*MKYong: Spring Boot Hello World Example – JSP
I got JSP working with both Spring Boot 1.x and 2.x, with both Maven and Gradle.  My project is here on GitHub:

*

*https://github.com/paulsm4/HelloSpringBoot/tree/master/test7
These are the highlights of what I needed to do:

*

*I created my starter project with Eclipse STS.
It was important to specify "War" packaging (vs. the default "Jar")

*I added the following dependencies in my build.gradle:
dependencies {
  compile('org.springframework.boot:spring-boot-starter-web')
  compile('javax.servlet:jstl')
  compile('javax.servlet:javax.servlet-api')
  compile('org.apache.tomcat.embed:tomcat-embed-jasper')
  compile('org.webjars:bootstrap:4.1.0')
  testImplementation('org.springframework.boot:spring-boot-starter-test')

It turns out that 'tomcat-embedded' need NOT be specified (it's included in spring-boot-starter-web by default).
But it also turns out that Embedded Tomcat won't process JSPs unless you explicitly include tomcat-embed-jasper.
Don't specify a "thymeleaf" dependency - it will conflict with "jasper".

*As per other tutorials, I added these lines in my application.properties:
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

I added also added these lines to my root class:
@SpringBootApplication
public class Test7Application extends SpringBootServletInitializer {
   ...
   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
      return application.sources(Test7Application.class);
   }

   public static void main(String[] args) {
      SpringApplication.run(Test7Application.class, args);
   }

*Unfortunately, "other tutorials" frequently say to create folder src/main/webapp/WEB-INF/jsp/.  This will NOT work.
Instead, I put my test.jsp file in folder src/main/resources/META-INF/resources/WEB-INF/jsp.
These links explain why:

*

*Spring Boot JSP 404

*Why spring boot 1.5.3 jar does not recognise jsp files in src/main/resources/META-INF/resources/

*At this point, I was successfully able to display both static and .jsp pages with Spring Boot.
I hope that helps!