What type of soundproof setup would I need to have band practice without bothering the neighbors?

Question: I need to be able to play at loud volumes any time day or night.
Is it necessary to have a house, or can I accomplish this in a condo or townhouse?
If I need a stand alone house, how far must it be from the neighbors, assuming it's soundproofed properly?
What would the cost be of the soundproofing?
Comment: As alephzero writes, much better to spend your "soundproofing" money on renting space that is appropriate. Storage facilities in my area have stopped renting to bands (leading to a local crisis in band practices, actually), but those might be good places to look at, besides the obvious of practice spaces designed specifically for this purpose.
Comment: Practice spaces I've tried are not ideal for practicing or writing because I can hear all the other bands playing.  Hence building a home studio.
Answer: While sound proofing can be very effective, sound can be very easily transmitted through air and solid like walls or floors.
So in a condo you may be able to sound proof your walls to limit the sound to neighbours, but as anyone who has ever lived above a neighbour knows, your floor will transmit a lot of sound.
A detached house will be much better, as you have no-one below or above you and you can sound proof the walls.
But even better would be a basement - where will sound go? The earth around the basement will absorb pretty much everything.
Your question about how far you'd need to be and how much it would cost is not really answerable without more data on the volume you plan on producing, the tolerance of your neighbours l, etc. Sound proofing companies give quotes on decibel reduction for each of their acoustic products so you'd need to look at what volume sound you would be producing, and at what frequencies, and then decide what solution would suit you.
Comment: While this is mostly good advice, it **is** possible to put numbers to a project like this. One would look at the SPL of the intended sound, the tolerable SPL of sound on the other side of the barrier(s) in question, and then design for a specific STC (sound transmission class) to achieve the desired reduction. Since every situation is different, the numbers in the design rarely perfectly match the real world, but with a little over engineering, design goals can be achieved.
Answer: If you are serious about this, you need to spend a LOT of money. You really need to build a "room within a room", with the floor mounted on a very soft foundation such as flexible airbags, so there is no vibration transmitted through the structure of the house.  Then you can think about soundproofing the walls, floor, and ceiling of the inner room to stop sound transmission through the air.
You can't have any windows in the inner room, because they transmit lots of sound. You also need to stop sound escaping through the ventilation and air conditioning.
Even in a basement room, the sound will be transmitted very efficiently through the structure of the building to the above-ground rooms and the outside world, unless you use a similar soundproofing technique.
Unless you have a budget of say $10,000, you are unlikely to achieve your objective of playing "at loud volumes any time day or night".
Whether you can do this sort of building work in a property that you don't own is a legal question not a technical one - but and I expect the answer would usually be "no".
You may be better off doing a long-term deal with a local recording studio, or rent some space in building intended for small workshops, etc where there is unlikely to be anyone complaining about noise at night.
For example, I play (mostly classical) acoustic piano in a conventional UK brick-built detached house, with (nominally "soundproof") double glazed windows, and the playing is perfectly audible outside the house - in fact sometimes people have stopped to listen. It would be also be audible inside neighbouring houses if their windows (or mine) were open.
Comment: And if I built this room within a room, how far away would I have to be from my next door neighbor so that they wouldn't hear any noise if I'm playing at 2:00am when they're trying to sleep?
Comment: Somehow I didn't see this answer before I wrote mine, but I'll leave mine up despite the overlap in case it is helpful. @Brian we really can't answer specific questions because the details matter and the variables are manifold. You'd have to go through a specific assessment process of taking measurements and doing a lot of research to come up with the answers. Regarding doing this work, I've never seen a rental agreement (and I've signed many) that would allow even basic modifications, so i'm pretty sure ownership is a must.
Comment: @Brain 2 AM (and similar times) are extremely tricky, because everything gets very silent. So even with great sound-proofing that works fine during the day, night is another matter entirely.
Answer: Let's just say you want to play as loud as you would in a concert. A little googling turns up 110 to 120db being a pretty standard range for concert volumes.
The city of Binghamton, NY, USA conveniently posts their noise ordinance as a helpful chart. I'm not sure how representative these are, but they limit levels of sound in multi-unit buildings to 45db at night.
45db is the same volume as a bird call, or about conversation volume.
So you would need to get your rehearsal space sound reduction about 65db.
At Lowe's you can pick up QuietRock drywall, which is 47-52 db noise reduction for $52.50/sheet. It's not recommended for ceilings, or presumably floors, and you'd probably need two layers. Depending on your room size, that would add up, and a soundproof door/windows will be more expensive.
Bear in mind also that depending on how the ordinance is written in your community or the rules your landlord/HOA imposes, soundproofing may not matter - you may not be allowed to actually make that much noise.
A house in the country, far away from the neighbors, is your best bet.
Caveat Emptor: I've never built a soundproof room. I've used a lot of poorly soundproofed ones though.
Comment: So if I want to live in a house in the suburbs or city, there's no amount of soundproofing that can achieve this?  I'd need to move to the country?
Comment: @Brian - it's certainly possible, but the amount of renovation you'd have to do, the likely legal issues, and comfort of the finished space are all factors to consider. In a rural environment, changes to the space for soundproofing would be minimal, so the cash could be spent on equipment or a more comfortable space, rather than special acoustically absorbent materials.
Answer: It really depends on what you mean by "loud volumes", what would be acceptable to your neighbors, and what the pre-existing situation of the dwelling you intend to inhabit is. Your question isn't really answerable with specifics.
In my experience as a musician in apartments, townhomes, and single family homes, you can either buy the right dwelling and play at the right time(s), or you can spend huge amounts of money to mitigate sound transmission.
If you have a full rock band going with a live drummer and amplifiers and all, you can definitely play in a full basement (not on a slope with an outside entrance in the back or something) of a detached house that is 10 - 20 feet from the nearest neighbor during the daytime. You definitely cannot play in a townhouse or condo at full band levels, at least not without a lot of expensive work that might not be successful.
In the case of the condo, I'd say there's almost no chance. You'd have to have high ceilings (12 feet would be good) and approval from the condo association for some serious construction work, and you'd be left with greatly reduced living area and you'd basically destroy the value of the condo and/or you'd have to pay to tear it all out again and rebuild the original interior before you could sell it (unless you found another musician to buy).
A town house is the edge case where it might be doable and make sense. My parents own a town house that they could have bough with an unfinished basement and the basement was designed with 12 foot ceilings. What could be made to work would be a room within a room:

Finish the walls and ceiling with some combination of resilient channel, green goo, and layers of gypsum board. Bring out all electrical and HVAC so they can be extended to the inner room, while also working to mitigate sound transmission through those channels.
Build an interior room on risers (hence the need for high ceilings). Minimum transmission would be achieved with offset studs, an air gap inside the interior walls, and some combination of resilient channel/green goo/gypsum board layers/etc. as above.
Power and ventilation would be extended from the outer room to the inner room in the right way, meaning it would comply with code for safety reasons while also being designed to minimize transmission. More or less, the inner room should be airtight, and power and ventilation require holes to be made in the interior room, so they have to be handled carefully.
The interior room would have a special door, and if the basement can be finished with another such door outside the interior room (opening in opposite directions) that would be ideal.

For there to be reasonable assurance of success before spending a lot of money on a project like this, you'd have to hire an experienced acoustic architect, collect a lot of data, attempt to determine the STC of the existing construction, and design carefully to ensure the goals are met. Overall, this would cost a lot of money, and might be difficult to finance, since it doesn't really add value to the house - it takes away. Modifications that no one but you wants are always detractors from home value.
Now, in a single-family home (detached) with a full basement, you get a lot more built-in sound proofing. If you can find one with an unfinished basement and high ceilings, then you can do a partial project like the one above and get some good success. Finish the ceiling and walls of the basement as above, and then instead of building a full room within a room, build a second, dropped ceiling. For underground basements, the major avenue of sound transmission is through the ceiling and then through the walls of the upper floors, so mitigating ceiling transmission is huge.
Because of the costs and difficulties involved in modifying a structure, it's much, much better to choose a different structure instead. So rather than working on design goals and saving up money, your best course of action is probably to spend that time and money on finding a job farther out in the suburbs, buying a single family home as far out as possible, and paying for and dealing with a longer commute. Of course, the longer the commute, the less time you have to play music.
Answer: To add to the other answers let me share some practical ideas I have learned over the years from the days when I used to build homes and build out office space.  These ideas will help you reduce considerably reduce the volume of any sound transmitted outside of your practice space, regardless of where you set it up.
Sound travels through the air.  It dissipates with distance.  Obviously the farther you are from a neighbor, the less problem you have with them hearing your 2 AM practice sessions.  A home that is a long way from the nearest neighbor is ideal.  Of course you might not want to live in the boondocks.
With attached housing (such as in a condo or townhome) where you have common walls, or in a neighborhood of detached homes where the homes are close together - you obviously have less distance.  But let's examine how sound travels through walls in order to understand how to mitigate it.
The sound vibrations actually hit a wall and set up vibrations in the wall at the same frequency.  These vibrations transmit the sound to the other side of the wall.  The ability of any particular wall to transmit sound to the other side of it are dependent upon the material the wall is constructed of (as well as other factors).
Not all the sound will go through the wall.  Some will reflect back and some could be absorbed by the material in the wall.  One way to reduce the amount of sound transmitted through a wall is to create a gap between two sides of the wall.  In other words - a typical wall in a home will consist of wood or metal studs with drywall (sheetrock is a common brand) attached to both sides of the studs.  If you instead attach the drywall to different studs, less sound is transmitted by the studs from the drywall in one room to the drywall in the other room.  In other words you need an air space where there are no common studs between the two layers of drywall so the studs themselves no longer serve as a conduit to help pass the sound from one side of a wall to the other.
Two things that can reduce the sound transmitted through a wall are reflection and absorption.  The stiffer the wall - the less it will vibrate and therefore the less it will tend to transmit sound to the other side.  Concrete or hard tile for example will tend to reflect more sound than it allows to pass through it.  That's why in a garage with a concrete floor or a room with a tile floor and no rug, the sound echos back so readily.
If you had a home with a basement, the concrete walls would reflect far more sound than they allowed to pass through and any underground portion of the basement would not allow any transmission through the wall itself because if any did pass through the concrete wall it would be absorbed by the earth on the other side.
Absorption can also reduce the amount of sound that passes through a wall or reflects back off of it. The reason it is quieter in a room with stuffed furniture, heavy curtains and rugs or carpeting - is that all of those soft surfaces tend to absorb some of the sound waves.
You can add insulation inside a wall (or between a floor and ceiling) to help absorb some of the sound.  Also you can line the walls with something that will help absorb some of the sound - such as acoustical foam sold for use in recording studios.  It not only reduces reflection, it will also reduces transmission through any wall to which it is affixed.

Acoustic Foam Panel.
To reduce transmission from a common wall or outside wall to your neighbor next door, you can build a second wall (ideally with no windows but beware of fire codes) just inside the existing outside wall.  Use fiberglass insulation batts behind thick drywall and attach acoustical foam to the inside (band side). Be sure your new wall does not contact the existing wall.
Building codes and common sense mandate a window or door through which an adult could easily exit the room in the case of fire.  If you must have a window in your second parallel wall, keep it at the minimum required size for fire egress and cover it with foam and heavy fabric in a manner that permits removal in an emergency.
To reduce transmission from the ceiling to the floor above, you could install a suspended ceiling with acoustic tile.  You could also attach acoustic foam to the ceiling. If you are finishing an unfinished basement, first put insulation under the floor above the basement (ceiling of basement) and then put in a suspended ceiling.
If all of this sounds overwhelming and none of your bandmates are willing to buy a home out in the country with no close neighbors, you might want to look at other alternatives for silent band practice such as the ones covered in this question on Music Stack Exchange - Should I use JamHub or Mixer and Headphone Amp for silent band practice?
Comment: Ok, so if I followed these directions in a condo, how much noise would make it through to the neighbors trying to sleep next door?  What about in a stand alone house in the burbs, 25 feet from a neighbor?
Comment: Standalone house wins by a longshot with far less sound attenuation needed.  The degree of sound attenuation you can achieve in an attached dwelling would depend on the money you could spend and if you could get permission from a landlord if renting.  Since the modifications would take place inside and not be visible to neighbors, no approval from the HOA should be required.  With enough material and proper construction, you can get close to sound proof.  But sound proof is almost impossible so some sound will escape.  If the only factor to consider was sound mitigation - detached wins.
Answer: This is going to be EXPENSIVE!  And, even in a detached house, several hundred feet away from the nearest neighbour, "loud volumes at any time day or night" are going to be classed as a nuisance.
Stay where you are, play more quietly and use headphones.  You need to practice your music, not continually test your PA system.


Why is 1 == '1\n' true in Javascript?

Question: The same goes for '1\t' (and probably others).
if (1 == '1\n') {
  console.log('Equal');
}
else {
  console.log('Not Equal');
}

Comment: because `Number('1\n')` is `1`, use `===` if you want a strict comparison.
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Answer:
The equality operator(==) converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

1 is of type Number hence '1\n' is converted to Number first then comparison takes place!
And Number() constructor will convert the string('1\n') to 1 :-
Number('1\n') === 1
In Strict equality using ===, Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal.
Hence 1 === '1\n' will be expressed as false
Answer: As said before if you compare number == string, it will automatically try to convert the string to a number. the \n and \t are simply whitespace characters and therefore ignored.
This and similar behaviour can be rather confusing leading to situations like this:

(Picture taken from: https://www.reddit.com/r/ProgrammerHumor/comments/3imr8q/javascript/)
Comment: I knew the difference between == and ===. What I did not know, however, is that white spaces are ignored during the conversion of ==.

Why is 1 == '1\n' true in Javascript?


What does $b$ does not divide $a$ mean?

Question: Given a statement like $b$ divides $a$ means there exists some integer $k$ such that $a = b\cdot k$, does that mean if $b$ does not divide $a$, then there are integers $q$ and $r$ such that $a = q\cdot b +r$ for $0<r<b$ according to the division algorithm?
Am I assuming too much here?
EDIT: Let me also clarify that I am assuming $a,b\in\mathbb{Z}$ and both are positive.
Comment: Yes, what you say is a correct interpretation of "$b$ does not divide $a$" *for integers $a$ and $b$*.  You could also have phrased it other ways such as $a\not\equiv 0\pmod{b}$, $a$ is not a multiple of $b$, there does not exist any $k$ such that $a=bk$, for all integers $k$ one has $a\neq bk$, etc...
Comment: Depends. Are $a$ and $b$ integers and is $b$ positive?
Comment: Yes, $a$ and $b$ are integers and $b$ is positive.
Answer: Yes. There's a simpler representation.
To say $b$ does not divide $a$ means that $b$ is not a factor of $a$. That is, if you try to do the division, you'll have leftovers - the remainder $r$.
Answer: What you've said is true. That said, depending on what class you're taking (I assume this is for a class), you might need to prove that $r$ can be chosen such that $0 < r < b$, and that the existence of such an $r$ implies that $b\nmid a$ (it depends how detailed you're expected to be).
Comment: I am using this fact to prove a different statement. What I would like to show is that if the order of an element b, does not divide the order of an element a, then the order of a*b is larger than the order of a. I just wanted to get the context behind "does not divide" correct.
Answer: No.
Consider the case $b=-5$ and $a=9$. Then we say $b\nmid a$ because there is no integer $k$ with $a=bk$. But you cannot find $q,r$ with $a=qb+r$ and $0<r<b$, simply because the second condition cannot be fulfilled.
Comment: Because this is actually about orders of elements within an abelian group G, it is assumed that $b$ and $a$ are both positive integers.

What does $b$ does not divide $a$ mean?


Error (org.codehaus.mojo) when adding persistence to Maven-Java-project?

Question: When adding persistence to my Maven-Java-project I can successfully build and compile ("Clean and Build Project" in Netbeans, I suppose it does mvn site) the project, but I won't be able to start it afterwards ("Run Project" in Netbeans).
I have been trying around for some time without success. For instance I have tried to delete the org.codehaus.mojo plugin in the pom.xml though there was no changement in my success.
Does anyone know this problem? Is there any wrong configuration with my settings for the MySQL database? Or is there an error in the pom.xml? Or in the persistence.xml?
Error from NetBeans IDE:
cd /home/myuser/NetBeansProjects/mavenglasses; JAVA_HOME=/home/myuser/jdk1.7.0_51 /home/myuser/netbeans-7.4/java/maven/bin/mvn "-Dexec.args=-jar ${basedir}/target/mavenglasses-1.0.jar" -Dexec.executable=/home/myuser/jdk1.7.0_51/bin/java org.codehaus.mojo:exec-maven-plugin:1.2.1:exec
Running NetBeans Compile On Save execution. Phase execution is skipped and output directories of dependency projects (with Compile on Save turned on) will be used instead of their jar artifacts.
Scanning for projects...

------------------------------------------------------------------------
Building mavenglasses 1.0
------------------------------------------------------------------------

--- exec-maven-plugin:1.2.1:exec (default-cli) @ mavenglasses ---
Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes
    at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVerifier.java:240)
    at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier.java:193)
    at java.util.jar.JarVerifier.processEntry(JarVerifier.java:264)
    at java.util.jar.JarVerifier.update(JarVerifier.java:218)
    at java.util.jar.JarFile.initializeVerifier(JarFile.java:345)
    at java.util.jar.JarFile.getInputStream(JarFile.java:412)
    at sun.misc.JarIndex.getJarIndex(JarIndex.java:137)
    at sun.misc.URLClassPath$JarLoader$1.run(URLClassPath.java:674)
    at sun.misc.URLClassPath$JarLoader$1.run(URLClassPath.java:666)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.misc.URLClassPath$JarLoader.ensureOpen(URLClassPath.java:665)
    at sun.misc.URLClassPath$JarLoader.<init>(URLClassPath.java:638)
    at sun.misc.URLClassPath$3.run(URLClassPath.java:366)
    at sun.misc.URLClassPath$3.run(URLClassPath.java:356)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:355)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:332)
    at sun.misc.URLClassPath.getResource(URLClassPath.java:198)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:358)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 0.850s
Finished at: Sun Feb 23 02:29:03 CET 2014
Final Memory: 6M/105M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project mavenglasses: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Full persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="GlassesPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>com.treasury.mavenglasses.Hund</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/glasses?zeroDateTimeBehavior=convertToNull"/>
      <property name="javax.persistence.jdbc.password" value="mypwd"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
    </properties>
  </persistence-unit>
</persistence>

Full pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.treasury</groupId>
    <artifactId>mavenglasses</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <name>mavenglasses</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <mainClass>com.treasury.mavenglasses.MainApp</mainClass>
    </properties>

    <organization>

        <name>Your Organisation</name>
    </organization>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <id>unpack-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>unpack-dependencies</goal>
                        </goals>
                        <configuration>
                            <excludeScope>system</excludeScope>
                            <excludeGroupIds>junit,org.mockito,org.hamcrest</excludeGroupIds>
                            <outputDirectory>${project.build.directory}/classes</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <id>unpack-dependencies</id>

                        <phase>package</phase>
                        <goals>
                            <goal>exec</goal>
                        </goals>
                        <configuration>
                            <executable>${java.home}/../bin/javafxpackager</executable>
                            <arguments>
                                <argument>-createjar</argument>
                                <argument>-nocss2bin</argument>
                                <argument>-appclass</argument>
                                <argument>${mainClass}</argument>
                                <argument>-srcdir</argument>
                                <argument>${project.build.directory}/classes</argument>
                                <argument>-outdir</argument>
                                <argument>${project.build.directory}</argument>
                                <argument>-outfile</argument>
                                <argument>${project.build.finalName}.jar</argument>
                            </arguments>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <bootclasspath>${sun.boot.class.path}${path.separator}${java.home}/lib/jfxrt.jar</bootclasspath>
                    </compilerArguments>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>eclipselink</artifactId>
            <version>2.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
            <version>2.5.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.29</version>
        </dependency>
    </dependencies>
</project>

Comment: I can only guess but the error message shows the direction: `Exception in thread "main" java.lang.SecurityException: Invalid signature file digest for Manifest main attributes` so not maven is the problem the calling process. I assume you are starting a java process via exec-maven-plugin:exec ? Without the full pom and configuration it's hard to guess what's wrong.
Comment: I have just added the full pom.xml.
Is there some misconfiguration in it?
Comment: Have you tried to call it manually?
Comment: What do you mean exactly? Do you mean like "mvn site" + java -jar myfile.jar?
Answer: I had a similar problem in NetBeans recently and found a fix now. The problem first started when I added an EntityClass and had NetBeans automatically add the persistence unit, etc.
The problem seems to be caused by the persistence unit adding files to your projects META-INF folder which will use a different technique to calculate the jars signature, or something like that.
To remove these files, add this after the exec-maven-plugin in your pom:
<plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>truezip-maven-plugin</artifactId>
            <version>1.2</version>
            <executions>
                <execution>
                    <id>remove-RSA-and-SF-files</id>
                    <goals>
                        <goal>remove</goal>
                    </goals>
                    <phase>package</phase>
                    <configuration>
                        <fileset>
                            <directory>${archive}/META-INF</directory>
                            <includes>
                                <include>**/*.RSA</include>
                                <include>**/*.SF</include>
                                <include>**/*.DSA</include>
                            </includes>
                        </fileset>
                    </configuration>
                </execution>
            </executions>
</plugin>

you also need to add the archive variable, which points to your .jar file:
<archive>target/projName-1.0-SNAPSHOT.jar</archive>

and finally add to your run task in nbactions.xml:
<goal>org.codehaus.mojo:truezip-maven-plugin:1.2:remove</goal>

just before:
<goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>

Hope that helps!
Comment: See also: ["Invalid signature file" when attempting to run a .jar](http://stackoverflow.com/questions/999489/invalid-signature-file-when-attempting-to-run-a-jar) ... This *worked* for me for a **non-JavaFX** project.  Passing it along, in case someone finds the variation that works with **JavaFX**.
Comment: @Andrey .. You might want to watch my question on this topic: http://stackoverflow.com/questions/25842559/valid-jar-signature-for-javafx-projects
Comment: Have the same problem, but solution you describe here not working for me.
BUILD FAILURE
Could not find goal 'remove' in plugin org.codehaus.mojo:exec-maven-plugin:1.2
Comment: Strange, have you defined the goal in your pom.xml?
Comment: Hi @Andrey no, not working for my my **JavaFX** project either.  I did notice that the Netbeans JavaFX POM file uses "classes/" in the final build file, you can see the .SF, etc files in "target/classes/META-INF/" ... Using this information, the TrueZip plugin did at least _find_ the files using:   `${project.build.directory}/classes/META-INF`.  However no gainful result, I still get the "Invalid Signature..." error. w.


Resgatar valor do banco de dados com React JS

Question: Estou tentando resgatar uma informação do banco de dados mas não consigo transferi-la para texto. Estou usando fetch para buscar, no console.log a informação aparece, mas no html não.
import "./styles.css";
import "../../../css/csstables.css"
import NavBar from '../../../components/NavBar';
import SideBar from '../../../components/SideBar';
import { useParams } from 'react-router-dom';

const UsersEdit = () => {

    const {id} = useParams();
    const [userResgatado, setUserResgatado] = useState([]);

    useEffect(()=>{
        fetch(`http://localhost:5000/users/${id}`,{
            method: 'GET',
            headers: {
                'Content-Type': 'aplication/json',
            },
        })
        .then(resp => resp.json())
        .then(data => {
            setUserResgatado(data)
            console.log(data)
        })
        .catch (err => console.log(err))
    }, [id])

    return (
        <>
        <NavBar />

                <SideBar />

Teste {userResgatado.usuario_email}

        </>
    )
}

export default UsersEdit;

O problema é ali no userResgatado, que não estou conseguindo puxar a informação. Mas no console aparece, segundo imagem anexada. Desde já, obrigado.
Answer: Creio que o problema é que você está salvando os dados dentro de um Array e depois o chamando como se fosse um objeto.
Ao fazer o console.log de data, note que ele mostra um Array com length == 1.
Dessa forma, você pode melhorar a maneira que armazena userResgatado ou, simplesmente colocá-lo na tela usando userResgatado[0].usuario_email.
Comment: Evite agradecer e cumprimentar nas publicações pois aqui no [pt.so] são considerados ruído de comunicação. Boas respostas são descritivas, detalhadas e diretas. Ofereça o máximo de informações possíveis sobre a solução, aqui os usuários não podem (nem querem) ficar conversando. Veja [Que tipo de comportamento é esperado dos usuários?](http://pt.stackoverflow.com/help/behavior), [Saudações e Agradecimentos](http://pt.meta.stackoverflow.com/q/846/137387) e [Como se portar ao perguntar/responder?](http://pt.meta.stackoverflow.com/q/38/137387).


user login screen is gone after using panels

Question: I've been trying to login with /user, /?q=user, and /?q=user/login but when I load the pages I can only see my header and nothing else.
This is likely because in the process of trying to learn how to use panels I somehow turned it off.  The default node variant was the first I created, where I put basic header information (site name, slogan, navigation) in the header, body content in the middle, and regular footer content in the footer with the new node-template variant.  As I recall I disabled this page/variant after I realized it applied it to every page and messed up a different system page.  Even though I disabled it and it was fine last time i was on the site, it seems to be back.
Is there any easy way to fix this?  Is there any thing I cut paste into a php file to load my user login block so i can at least get back into my site?
Comment: Have you tried disabling your panels module?
Answer: Used drush to disable panels ( drush dis panels).
Thanks to 4life for the suggestion.  (i don't know why it won't let me credit him with the answer on here)


Finding the general solution of the given linear homogeneous differential equation.

Question: The question is quite simple but I am having doubt :-
 I am asked to find out the general solution of the differential equation
 $(D^2- 4)y=0$ where $D=\frac{dy}{dx}$.
If I want to use hyperbolic function then I have its general solution to be
$y(x)= a \cosh 2x + b \sinh 2x$ where $a$ and $b$ are constants.
Alternatively can I write the solution to be $y = ae^{2x}+ b e^{-2x}$ ? i.e using distinct and real roots $-2$ , $2$ ?
What relation does these two solution possess?
Answer: Remember $\cosh x=\frac{e^{x}+e^{-x}}{2}$ & $\sinh x=\frac{e^{x}-e^{-x}}{2}$
Yes, you can write the general solution of $(D^2-4)y=0$ as follows
$$y=C.F.(\text{complementary function}) +P.I. (\text{particular integral})$$
$$C.F.=ae^{2x}+be^{-2x}$$
since the particular integral is $0$. hence, the solution is
$$y=ae^{2x}+be^{-2x}+0$$$$=ae^{2x}+be^{-2x}$$


Estimation of a process

Question: I have this process to estimate:
$x_t - x_{t-1} = \lambda(\gamma-x_{t-1}+\varepsilon_{t-1})+\varepsilon_t-\varepsilon_{t-1}$
but as far I can see it is unidentified. Any suggestions how to estimate it?
Answer: It is trivial to re-write the process
$$x_t - x_{t-1} = \lambda(\gamma-x_{t-1}+\varepsilon_{t-1})+\varepsilon_t-\varepsilon_{t-1}$$
as an $ARMA(1,1)$ process with drift,
$$x_t = \lambda \gamma +(1-\lambda)x_{t-1}  + \big( \varepsilon_{t}-(1-\lambda)\varepsilon_{t-1}\big)$$
but the equality of the AR and the MA coefficients is crucial here.
I will write $ \phi  \equiv 1-\lambda$ so the process is
$$x_t = \lambda \gamma +\phi x_{t-1}  + \big( \varepsilon_{t}-\phi\varepsilon_{t-1}\big)$$
$$\implies (1-\phi L)x_t = (1-\phi L)\gamma + (1-\phi L) \varepsilon_{t}$$
where $L$ is the lag operator. Since the term $(1-\phi L)$ is common throughout, the above process is equivalent to
$$x_t = \gamma +  \varepsilon_{t}$$
i.e. a white-noise with drift.
This is the case of "redundant parametrization". As Hamilton p. 60 notes "any value of $\phi$ will describe the data equally well". So indeed estimation attempts will get into trouble, but, also, the appearance of $\lambda$ is artificial, it does not represent anything related to the Data Generating Mechanism, and so there is no point in trying to estimate it.
Of course if the specific parametrization is only postulated, testing whether the process can be characterized as white noise will also tell us whether it is useful to go into $ARMA(1,1)$ estimation: if the white-noise behavior is rejected then this is also evidence against the assumed equality of the AR and MA coefficients.
Comment: I thought about ARMA rapresentation but lambda affects also the constant term..
Comment: @Marco My answer clearly shows that the $\lambda$ coefficient is wiped out from all places in the relation.
Comment: Yep but without The lag operator in The constant $\gamma(1-\phi)$
Comment: You are right it is The same..
Comment: There is not methodological issue with applying the lag operator to a constant (it just leaves it unaffected): $$(1-\phi L)\gamma = \gamma - \phi  L\gamma = \gamma - \phi \gamma = \gamma - (1-\lambda)\gamma = \lambda \gamma$$
Comment: You are perfectly right, I did not think to apply The trick of The lago operator to The constant. Need to retake a look to Hamilton . thank you very much. Bests

Estimation of a process


What instrument is an "alto" string part in a score?

Question: In the music score below, the bottom five parts seem to be string parts. We think the first two are violins, the last is string bass, and the second-last is cello. But what is the third-last? Is it a viola? We understand the clef is an older-style C-clef (alto or viola clef).
Answer: Yes, Alto = Viola.  It's the French name for the instrument, and the score shown is a part of 'Carnival of the Animals' by  the French composer Camille Saint-Saëns.
https://en.wikipedia.org/wiki/The_Carnival_of_the_Animals#XII_%22Fossiles%22_(Fossils)
The other instrument names are easily recognisable.  Note that  Bb Clarinet is 'Clarinette en SIb'.  The French write the scale as do, ré, mi, fa, sol, la, si, do rather than C, D, E, F, G, A, B, C.   In German it would be "Klarinette in B'.  In Germany, 'B' is 'Bb', 'H' is 'B'.  Apart from confusing foreigners, this has the advantage of letting German composers write fugues based on 'BACH'.
Alto clef is the standard clef for viola music.  A particularly high passage might move into treble clef.  But mostly they live in alto clef.
Comment: Don't the French still use the mediaeval "ut" for *do*?
Answer: Yes it is a part written for a viola. Because of its range the alto clef is standard choice for viola in all types of music.
Here is an orchestral example from Verdi's overture to II Signor Bruschino (from the textbook Instrumentation and orchestration) where the viola is marked Va.


Creating a rss feed in Symfony

Question: I'm trying to create a RSS feed in Symfony.
I've added the following route :
rss_every_content:
  url:    /rss/all
  param: { module: content, action: index, sf_format: rss }
  requirements:
    sf_method: [get]

And I created a file called indexSuccess.rss.php in module/content/templates/ :
test message

But when I go to the url mysite/rss, all I get is an empty page ! No content at all, not even the debug toolbar... Help ! What is going on ?
Answer: I had the same problem as you. I noticed that sf_format: xml with indexSuccess.xml.php seems to work as long as you specify the RSS XML tag at the top like:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<channel>
    <title>RSS Example</title>
    <description>This is an example of an RSS feed</description>
    <link>http://www.domain.com/link.htm</link>
    <lastBuildDate>Mon, 28 Aug 2006 11:12:55 -0400 </lastBuildDate>
    <pubDate>Tue, 29 Aug 2006 09:00:00 -0400</pubDate>

    <item>
        <title>Item Example</title>
        <description>This is an example of an Item</description>
        <link>http://www.domain.com/link.htm</link>
        <guid isPermaLink="false">1102345</guid>
        <pubDate>Tue, 29 Aug 2006 09:00:00 -0400</pubDate>
    </item>

</channel>
</rss>

From http://www.rss-tools.com/rss-example.htm
It's a hack but I can't see how else to do it.
Answer: By default, RSS format is not supported by a symfony application, but you can add these lines in your factories.yml:
all:
  request:
    param:
      formats:
        rss: application/rss+xml

All request with $sf_format = rss will by responded with MimeType application/rss+xml
Answer: Controller Method
//------------------------latest 10 RSS FEED----------------------------------
    public function generateRssFeedsAction()
    {
     $em = $this->getDoctrine()->getManager();
     $newsObj = $em->getRepository('CrossOverAppUserBundle:News')->findlatestNewArticle($page_number=1, $limit=10);
     $response = new Response($this->renderView('CrossOverAppUserBundle:News:rss_feed.xml.twig',array('news'=>$newsObj)));
     $response->headers->set('Content-Type', 'application/xml; charset=utf-8');
     return $response;
    }

Twig Templete
{% autoescape %}
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        {% for entry in news %}
            <article_id>{{ entry.id }}</article_id>
            <article_name>{{ entry.newsTitle }}</article_name>
            <description>{{ entry.newDescription }}</description>
            <article_createdby>{{ entry.user.firstName }}</article_createdby>
            <article_createdat>{{ entry.createdAt|date("d-m-Y H:i:s") }}</article_createdat>
             <article_image></article_image>

        {% endfor %}
    </url>
</urlset>
{% endautoescape %}

Comment: Could you add some explanations?

Creating a rss feed in Symfony


Directly computing a matrix representation with respect to 2 bases

Question: I want to find the representation of a linear transformation with respect to two new bases.
Given linear transformation:
$$
L(at + b) = \begin{bmatrix}
 3b-a\\
2a + b
\end{bmatrix}
$$
With:

$S_1 = (1,t)$ as standard basis of $P_1$ and $T_1$ being the standard basis of $\mathbb{R}^2$.

$S_2 = (3t + 5, t + 2)$ as another basis of $P_1$ and $T_2 = \left(\begin{bmatrix} -1 \\ -1\end{bmatrix}, \begin{bmatrix} 2 \\ 1\end{bmatrix}\right)$ of $\mathbb{R}^2$.

I know the way to do it using an augmented matrix (image linked):
$$L(3t+5) = \begin{bmatrix}12 \\ 11\end{bmatrix} \\ L(t+2) = \begin{bmatrix}1 \\ 4\end{bmatrix}$$
$$
\left[\begin{array}{cc|c|c}
-1&2&12&5\\
-1&1&11&4
\end{array}\right] \\
\left[\begin{array}{cc|c|c}
-1&2&12&5\\
0&-1&-1&-1
\end{array}\right] \\
\left[\begin{array}{cc|c|c}
-1&0&10&3\\
0&-1&-1&-1
\end{array}\right] \\
\left[\begin{array}{cc|c|c}
1&0&-10&-3\\
0&1&1&1
\end{array}\right] \\
$$
resulting in $$
\boxed{\begin{bmatrix}-10 & -3 \\ 1 & 1\end{bmatrix}}
$$

However, I tried using $Q^{-1}AP$ to solve this: $Q$ is ${Q_{T_{1} \gets T_{2}}}$ and P is ${P_{S_{1} \gets S_{2}}}$. I should get the same answer as what I did above using what I did before, but I get something completely different.
Here's what I tried:
$$
A = \begin{bmatrix}-1&3\\2&1\end{bmatrix} \\
P_{S_1 \gets S_2} = \begin{bmatrix}5&2\\3&1\end{bmatrix} \\
Q_{T_1 \gets T_2} = \begin{bmatrix}-1&2\\-1&1\end{bmatrix} \\
Q^{-1} = \begin{bmatrix}1&-2\\1&-1\end{bmatrix} \\
\implies Q^{-1}AP = \begin{bmatrix}1&-2\\1&-1\end{bmatrix}\begin{bmatrix}-1&3\\2&1\end{bmatrix}\begin{bmatrix}5&2\\3&1\end{bmatrix}
$$

Is there something I am doing wrong?
EDIT: Include what my attempt at the 2nd method was.
Comment: Welcome to MSE. I suggest that you edit your question, adding to you what you have tried using the second method.
Comment: @JoséCarlosSantos Thanks for the welcome. I just updated the post with what I tried.
Comment: Just converted the attempt to MathJax, you can take a look. Next time, you can use the same syntax (if necessary, copy and paste the elimination matrix syntax) to MathJax your attempt rather than write it. It helps in searchability of your post, posts with MathJax get more attention.
Answer: Of course that there is something wrong; you got two different answers, and therefore (at least) one of the approaches must be wrong. In your case, it's the second one. You have used the matrix $\left[\begin{smallmatrix}-1&3\\2&1\end{smallmatrix}\right]$, whereas it should have been $\left[\begin{smallmatrix}3&-1\\1&2\end{smallmatrix}\right]$. You can check that$$\begin{bmatrix}-1&2\\-1&1\end{bmatrix}^{-1}\begin{bmatrix}3&-1\\1&2\end{bmatrix}\begin{bmatrix}5&2\\3&1\end{bmatrix}=\begin{bmatrix}-10&-3\\1&1\end{bmatrix},$$which is the answer that you got through the first method.


How to find Fourier series coefficients on interval $[\pi, 3\pi]$

Question: Given that $f(x) = x^2$,
$$f(x) \sim \frac{a_0}{2}+\sum_{n=1}^\infty\bigl(a_n \cos(nx)+b_n \sin(nx)\bigr)$$
on the interval $[\pi,3\pi]$.
I need to find $a_n$ and $b_n$; I just want to check that I am correct in saying that
$$a_n = \frac{1}{\pi} \int_\pi^{3\pi} x^2\cos(nx)\,\mathrm{d}x,$$
$$b_n = \frac{1}{\pi} \int_\pi^{3\pi} x^2\sin(nx)\,\mathrm{d}x.$$
From there, I would just need to evaluate the integrals using integration by parts.
Any help is much appreciated.
Comment: Replace $x$ with $x+2\pi$, and change the interval to $[-\pi,\pi]$. Once you find the series, replace $x$ with $x-2\pi$
Comment: Yes, that will work fine. For formatting, use an online LaTex editor e.g. https://latexeditor.lagrida.com/ and put the commands between dollar symbols $. After a while you will learn the syntax you use often
Answer: You are indeed correct, and using integration by parts to compute the integrals is a good way to go.


Evaluating $\lim_{x \to -∞} \frac{\sqrt[3]{2+3x}}{\ln(1-x)}$

Question: $$\lim_{x \to -∞} \frac{\sqrt[3]{2+3x}}{\ln(1-x)}$$
This looks like an indetermination of the form $\frac{-∞}{∞}$, so we apply l'Hospital:
$$\frac{x-1}{(2+3x)^{2/3}}$$
However now, the denominator is undefined. How do we proceed?
I asked this question: Is $\lim_{x \to -∞} (2+3x)^{2/3}$ positive or negative?
but nobody agreed in the answers.
Comment: Sigh, why the downvotes..
Comment: The expression in your title differed from the one in the text, until a few seconds ago. That is probably the reason for the downvote. Note that the downvote is not mine. It was difficult to edit the question, since it was not completely clear that that the title was the wrong expression.
Comment: I understand. Care to help nonetheless? @RoryDaulton
Comment: I think it is better to substitute $-x$ by $u\to +\infty$ and use $\sqrt[3]{-x} = -\sqrt[3]{x}$. However, I don't see that your denominator is undefined.
Answer: (Previous answer deleted, due to a change in the question.)
Your denominator is not undefined.
$$(2+3x)^{2/3}=\sqrt[3]{(2+3x)^2}$$
which is well-defined and non-negative for all $x$. You can continue your calculations with another round of L'Hopital:
$$\begin{align}
\frac{x-1}{(2+3x)^{2/3}} &\to \frac{1}{\frac 23(2+3x)^{-1/3}\cdot 3}\\[2 ex]
 &= 2(2+3x)^{1/3}
\end{align}$$
As $x\to-\infty$, we get $2+3x\to-\infty$ and $\sqrt[3]{2+3x}\to-\infty$, thus the entire expression tends to minus infinity, which is your final answer.
This is confirmed numerically. My evaluations of $f(x)$ slowly but surely become more negative, with $f(-1000000)\approx -19.2779$. Each additional zero on $x$ increases the magnitude of $f(x)$ by a factor of a little less than two.
Answer: The denominator is perfectly defined as long as $x \ne - \frac 2 3$, but this is not a problem, since $x \to -\infty$ means that $x$ goes "downwards" "past" $-\frac 2 3$ i.e it stays in some neighbourhood $(-\infty, a)$ of $-\infty$, and you are free to choose $a$ as you please, so just take it smaller than $-\frac 2 3$ and the denominator is fine.
Your approach is correct and you should continue by applying L'Hospital's rule one more time. Alternatively, if $t = -x$ (so that $t \to \infty$), write
$$\lim_{x \to -\infty} \frac{\sqrt[3]{2+3x}}{\ln(1-x)} = \lim_{x \to -\infty} \frac{-\sqrt[3]{-2-3x}}{\ln(1-x)} = \lim_{t \to \infty} \frac{-\sqrt[3]{-2+3t}}{\ln(1+t)} = - \lim_{t \to \infty} \frac{1+t} {(-2 + 3t)^{\frac 2 3}}$$
and, applying L'Hospital's theorem once more,
$$-\lim_{t \to \infty} \frac{1+t} {(-2 + 3t)^{\frac 2 3}} = -\lim_{t \to \infty} \frac 1 {3 \frac 2 3 (-2 + 3t)^{-\frac 1 3}} = -\frac 1 2 \lim_{t \to \infty} (-2 + 3t)^{\frac 1 3} = -\infty .$$


How can be decoder of VAE represent probability distribution p(x|z) eventhough we directly get image as output

Question: How can be decoder of VAE represent probability distribution p(x|z) eventhough we directly get image as output. Also if my current understanding is right than we get same image for same value of z sampled by at bottleneck of VAE than how is decoder probabilistic.
Answer: The decoder represents a multidimensional probability distribution.
If your "reconstruction loss" (the negative log-likelihood term) is the mean squared error, or variants thereafter, the decoder represents a multivariate Gaussian distribution.
This form implies a constant diagonal covariance (which is not usually estimated, and is assumed to be the same for every sample).
Then, the 'output' is the mean of such a distribution (which completely parametrizes a multivariate Gaussian with assumed known covariance)
If you optimize instead for "cross-entropy loss" (the Bernoulli negative loglikelihood), then the decoder represents a Bernoulli distribution.
In this case, the 'output' is the probability of a single trial (i.e., being 1 instead of 0).

Theoretically, you could sample from the decoder (see Is the output of a variational autoencoder meant to be a distribution that can be sampled, or a sample directly?), since it is a conditional distribution.


Reverse Easing Method (solve for x)

Question: I'm a programmer who could use some help reversing an easing method:
<code>public static float easeInExpo(float start, float end, float value){
    end -= start;
    return end * Mathf.Pow(2, 10 * (value / 1 - 1)) + start;
}
</code>
The method takes a start and end variable and a value. The value is then eased based on an exponential function.
$\text{value} = \text{dist} \times (10((x/1)-1))^2 + \text{start}$
I am trying to reverse it so that the original value is produced with the input of the eased value.
What I have so far is:
$x = \left.\sqrt{\frac{\text{value}+\text{start}}{\text{dist}}}\right/10+1$
This doesn't seem to work. How would you reverse this method?
Edit: It seems that I got it all wrong. What must be solved is $\text{value} = \text{dist}(2^{10((x/1)-1)}) + \text{start}$
Comment: Assume dist is given, which is equal to the end variable minus the start variable. Edit: It seems that I got it all wrong. What must be solved is value = dist(2^(10((x/1)-1))) + start
Comment: Why do you have $(x/1)$ instead of $x$?
Answer: start=$a$
end=$b$
value=$x$
eased value=$y$
So $$y=(b-a)2^{10(x-1)}+a$$
Hence $$x=1+\frac{1}{10}\log_2\frac{y-a}{b-a}$$
Comment: Actually, there was a mistake with the given formula. I've updated the question. Any help would be greatly appreciated.
Comment: @Abdulla You need the value of $x$   ,  given $y$ right??
Comment: Thanks a lot for the help Saurabh, I managed to find a solution to the problem: x = 1 + ln(y-a)/10*ln(2). I haven't tested it yet but I'm assuming it's correct.
Comment: @Abdulla Aren't you missing _dist_ ?
Comment: I wouldn't know why this is the case. However, I've used http://www.mathway.com to solve the problem and the answer's working as intended.
Answer: For the new problem:
$\text{value} = \text{dist}(2^{10((x/1)-1)}) + \text{start}$
$\text{value} = \text{dist}(2^{10(x-1)}) + \text{start}$
$\frac {\text{value - start}}{\text{dist}}=2^{10(x-1)}$
$\log_2(\frac {\text{value - start}}{\text{dist}})=10(x-1)$
$(\log_2(\frac {\text{value - start}}{\text{dist}}))/10+1=x$

Reverse Easing Method (solve for x)


Mostrar opções para personalizar orçamento

Question: Preciso mostrar ao usuário a possibilidade de personalizar um orçamento, mas não estou conseguindo mostrar as opções, funciona somente a primeira, estou usando esse código dentro de um while php.
O que tenho é isso:
O HTML
<!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>

<form>

      Equipamento Analitico E.T.A

  <input type="checkbox" name="opcao" value="1" class="personalizar">
  Sim

        <input name="Sistema Supervisório" type="checkbox" value="Sistema Supervisório" />
          Sistema Supervisorio

        <input name="Analisador de PH" type="checkbox" value="Analisador de PH" />
          Analisador de PH

        <input name="Monitor de Coagulante" type="checkbox" value="Monitor de Coagulante" />
          Monitor de Coagulante

        <input name="Turbidímetro de Entrada" type="checkbox" value="Turbidímetro de Entrada" />
          Turbidímetro de Entrada

        <input name="Leitura de Vazao Via IHM" type="checkbox" value="Leitura de Vazao Via IHM" />
          Leitura de Vazao Via IHM

        <input name="Analisador de Cloro" type="checkbox" value="Analisador de Cloro" />
          Analisador de Cloro

        <input name="Analisador de Fluor" type="checkbox" value="Analisador de Fluor" />
          Analisador de Fluor

        <input type="checkbox" name="doseeta" value="1" class="dosadoras">
          Bombas Dosadoras

        <input name="Cloro" type="checkbox" value="Cloro" />
          Cloro

        <input name="Fluor" type="checkbox" value="Fluor" />
          Fluor

        <input name="Coagulante" type="checkbox" value="Coagulante" />
          Coagulante

        <input name="Acidulante (Acido)" type="checkbox" value="Acidulante (Acido)" />
          Acidulante (Acido)

        <input name="Alcalinizante (Soda)" type="checkbox" value="Alcalinizante (Soda)" />
          Alcalinizante (Soda)

</form>

$(document).ready(function(){

    $(".personalizar").click(function(evento){
        if ($(".personalizar").attr("checked")){
            $(".orcamento").css("display", "block");
        }else{
            $(".orcamento").css("display", "none");
        }
    });
});

$(document).ready(function(){
    $(".dosadoras").click(function(evento){
        if ($(".dosadoras").attr("checked")){
            $(".dose").css("display", "block");
        }else{
            $(".dose").css("display", "none");
        }
    });
});`

Como posso mostrar as opções?
Comment: Poste o HTML sob o qual o JavaScript está operando.
Comment: Precisa editar e deixar mais claro o que você está tentando fazer, de preferencia poste seu código php tambem
Comment: Como posto um conteúdo HTML? Não estou conseguindo realizar essa operação.
Comment: Para formatar código selecione ele e click no botão `{ }`
Answer: Use
if (this.checked) {

em vez de
if ($(".minhaClasse").attr("checked")){

Podia também usar o .prop("checked"), que é a solução actual/substituta do .attr() desde a versão 1.6.
Mudando isso o seu código já funciona: http://jsfiddle.net/7jGTJ/
$(document).ready(function () {

    $(".personalizar").click(function (evento) {console.log(1)
        if (this.checked) {
            $(".orcamento").css("display", "block");
        } else {
            $(".orcamento").css("display", "none");
        }
    });

    $(".dosadoras").click(function (evento) {
         if (this.checked) {
            $(".dose").css("display", "block");
        } else {
            $(".dose").css("display", "none");
        }
    });
});

Note que tinha duas vezes $(document).ready(){, eu simplifiquei para uma só.
Note também que no seu código não bejo onde esteja a carregar a biblioteca do jQuery. Não se esqueça de incluír este código dentro da tag :

Nota extra: pode ainda usar o $(this).is(':checked') mas este método é mais útil quando é preciso usar um seletor para encontrar o elemento. Aqui como já temos o this então javascript puro é o mais rápido e simples.
Obrigado @Bruno Augusto lembrar do .is()
Comment: Fantástico Sérgio, muitíssimo obrigado pela grande ajuda, funcionou corretamente.
Comment: Outra possibilidade que fica um pouquinho menos confusa pra quem programa JS "Orientado a Objeto" (aspas bem gigantescas aqui), seria usar *jQuery.is()* condicionando com o pseudo-seletor **:checked**, veja: http://jsfiddle.net/89Dym/
Comment: @BrunoAugusto, verdade. Neste caso não é pratico, mas juntei à resposta também. Obrigado.


Why are "continue" statements bad in JavaScript?

Question: In the book Javascript: The Good Parts by Douglas Crockford, this is all the author has to say about the continue Statement:

The continue statement jumps to the top of the loop. I have never seen a piece of code that was not improved by refactoring it to remove the continue statement.

This really confuses me. I know Crockford has some very opinionated views on JavaScript, but this just sounds entirely wrong to me.
First of all, continue does more than just jump to the top of a loop. By default, it also progresses to the next iteration. So isn't Crockford's statement just completely false information?
More importantly, I do not entirely understand why continue would even be considered to be bad. This post provides what seems to be the general assumption:
Why is continue inside a loop a bad idea?
Although I understand how continue may make code difficult to read in certain instances,  I think it is just as likely that it can make code more readable. For instance:
var someArray=['blah',5,'stuff',7];
for(var i=0;i<someArray.length;i++){
    if(typeof someArray[i]==='number'){
        for(var j=0;j<someArray[i];j++){
            console.log(j);
        }
    }
}

This could be refactored into:
var someArray=['blah',5,'stuff',7];
for(var i=0;i<someArray.length;i++){
    if(typeof someArray[i]!=='number'){
        continue;
    }
    for(var j=0;j<someArray[i];j++){
        console.log(j);
    }
}

continue isn't particularly beneficial in this specific example, but it does demonstrate the fact that it reduces the nesting depth. In more complex code, this could potentially increase readability.
Crockford provides no explanation as to why continue should not be used, so is there some deeper significance behind this opinion that I am missing?
Comment: "Mr. Crawford" didn't design the language.
Comment: The more I read about Crockford the less I respect his opinion. He seems to just be a cranky old gatekeeper with entirely irrational preferences of taste which he disguises as experience-honed wisdom.
Comment: Someone should write a book called "JavaScript: The Good Parts: The Good Parts". Frankly, I think a lot of advice in the original should be taken with a grain of NaCl, if not a wole salt mine.
Comment: @TylerH Can we mark Mr. Crockford as "primarily opinion-based"? lol
Comment: The keyword `continue` is a tool - use it where applicable. SOmetimes it's necessary, most times it isn't. The only time it's bad is when you didn't need to use it but were too lazy or sloppy to do it another way.
Comment: I had the same feeling and that's why I made my [post](http://stackoverflow.com/questions/30030033/continue-statement-confusion). What helped me is to just think of the word `hop` when using continue statements. I think Mr. Crawford used a poor word of choice here when designing the language :P

Especially since hop can apply the logic 'continue' behind it. If you hop over something you're usually continuing as well. Think of marathon track runners as a good analogy.
Comment: @rlemon Neither did Mr. Crockford.
Comment: @twiz Absolutely.
Answer: The statement is ridiculous. continue can be abused, but it often helps readability.
Typical use:
for (somecondition)
{
    if (!firsttest) continue;

    some_provisional_work_that_is_almost_always_needed();

    if (!further_tests()) continue;

    do_expensive_operation();
}

The goal is to avoid 'lasagna' code, where you have deeply nested conditionals.
Edited to add:
Yes, this is ultimately subjective. Here's my metric for deciding.
Edited one last time:
This example is too simple, of course, and you can always replace nested conditionals with function calls. But then you may have to pass data into the nested functions by reference, which can create refactoring problems at least as bad as the ones you're trying to avoid.
Comment: I'd also add that readability is subjective and while most people seem to like using continue, others may not.  For the same reason, people hate gotos, which are not inherently evil (only abuse of gotos is evil).
Comment: See my post [here](http://stackoverflow.com/questions/30030033/continue-statement-confusion). I think the word choice is just wrong, I think `hop` should of been a better word used. But it's too late now!
Comment: Using `continue` also allows reading code more in a *functional* style, for example: `for(a in b) { if (condition1) continue; if (condition2) continue; doSomething(); }` is similar to `b.filter(condition1).filter(condition2).forEach(a => ...);`
Comment: I find "continue" to be super unreadable. To me continue means "continue with the next line", which isn't what it does. What it does is "skip" or "jump" into the next iteration, so any of those words would be much better. Reading continue just confuses me.
Answer: Douglas Crockford may feel this way because he doesn't believe in assignment within a conditional. In fact, his program JSlint doesn't even let you do it, even though Javascript does. He would never write:
Example 1
while (rec = getrec())
{
    if (condition1(rec))
        continue;

    doSomething(rec);
}

but, I'm guessing he would write something like:
Example 2
rec = getrec();

while (rec)
{
    if (!condition(rec))
        doSomething(rec);

    rec = getrec();
}

Both of these work, but if you accidentally mix these styles you get an infinite loop:
Example 3
rec = getrec();

while (rec)
{
    if (condition1(rec))
        continue;

    rec = getrec();
}

This could be part of why he doesn't like continues.
Comment: @twiz: My point applies to `for` loops and `do` loops as well. Surely he believes in *some* kind of loop!
Comment: You may have a point, but I believe he also generally opposes `while` loops in the first place.
Comment: `rec = getrec();` appears twice, violating Don't Repeat Yourself.
Comment: @twiz as of his latest book, he uses `while (true) { ... }` when he is inclined to use a loop instead of a (preferred) recursive function.
Comment: @diachedelic What is his latest book? Just an updated version?
Comment: @twiz https://howjavascriptworks.com/
Comment: @diachedelic Thanks. I might have to give it a read, although I read the sample chapter and the "Heresy" section is probably one of the most arrogant things I have ever read. It's truly astounding. Crockford is obviously a smart guy, but I doubt I could be friends with him. haha
Comment: @twiz maybe...but everything he says there seems true to me
Answer: I am personally on the other side than the majority here. The problem is usually not with the shown continue patterns, but with more deeply nested ones, where possible code paths may become hard to see.
But even your example with one continue does not show improvement in my opinion that is justifiable. From my experience a few continue statements are a nightmare to refactor later (even for static languages better suited for automated refactoring like Java, especially when someone later puts there break too).
Thus, I would add a comment to the quote you gave:

Refactoring to remove continue statement inreases your further ability to refactor.

And inner loops are really good candidated for e.g. extract function. Such refactoring is done when the inner loop becomes complex and then continue may make it painful.
These are my honest opinions after working professionally on JavaScript projects in a team, there rules that Douglas Crockford talks about really show their merits.
Comment: I am not sure I know what you mean. Would you mind giving an example of where `continue` will become a "nightmare to refactor"?

Also, what do you mean by "extract function"? Is this a design pattern?
Comment: "extract function" (also can be googled under "extract method") is a refactoring technique to extract part of body of a function to a new separate function. Even the simple code in another answer here with 2 continue statements would need to be rewritten (to get rid of continue statements) in order to create a new function out of the body of the for loop. When you get bigger bodies with more nested continue statements, it takes a lot of time to clean up your code.
Answer: Continue is an extremely useful tool for saving computation cycles in algorithms. Sure, it can be improperly used but so can every other keyword or approach. When striving for performance, it can be useful to take an inverse approach to path divergence with a conditional statement. A continue can facilitate the inverse by allowing less efficient paths to be skipped when possible.
Answer: Actually, from all the analysis it seems:

If you have shallow loops - feel free to use continue iff it improves readability (also, there may be some performance gains?).
If you have deep nested loops (which means you already have a hairball to untangle when you re-factor) avoiding continue may prove to be beneficial from a code reliability standpoint.

In defense of Douglas Crokford, I feel that his recommendations tend to lean towards defensive programming, which, in all honesty seems like a good approach for 'idiot-proofing' the code in the enterprise.
Answer: Personally, I have never heard anything bad about using the continue statement. It is true that it could (most of the time) be easily avoided, but there is no reason to not use it. I find that loops can be a lot cleaner looking and more readable with continue statements in place.
Comment: So true. To add to your answer, the transpiler internally adds the equivalent of a `continue` statement onto the end of every loop in the generated assembly. So realistically, not only are continue statements not bad, in fact they are actually very good.


How to pass Secrets without hard-coding in cloud formation template/blueprint?

Question: We are having some secrets(external secrets), Not something which is return from cloud formation templates. In that case, we have to  pass that secrets in the cloud formation template/blueprint.
Is there any alternative rather than giving hardcoded secrets inside the CFN blueprint/template.
Answer: Usually you would use dynamic references:

When you use a dynamic reference, CloudFormation retrieves the value of the specified reference when necessary during stack and change set operations.

You could store your secrets in AWS Systems Manager Parameter Store  or AWS Secrets Manager, and the dynamic reference could retrieve them without needing to hard-code their actual values in the templates.
Comment: Actually we don't want to do it manually to store secrets in secrets manager. Is there any other solution. Like, can we collect all secrets in a file and then that file can be upload to the s3 bucket. Through s3 bucket can we update secrets to secrets manager ? Is that possible.
Comment: @PrashanthKanuka Yes, but this is something that you have construct yourself. There is no out-of-the-box mechanism for that in AWS.
Comment: I second the suggestion to store the secret/sensitive data in SSM/PS and just pass the name of the parameters around.  Then the code can lookup the values when it needs them.  Just make sure to cache the values in code, meaning don't call make parameter store calls every time the code wants to reference the value.
Answer: You can try adding the secrets in S3 and can provide that path in the AWS Secrets. In the CF template, you are not passing the secrets directly then.


Set of primitive recursive functions is not finitely generated

Question: Let $PR$ be the set of of [primitive recursive functions][1]. Given $X\subset PR$, let
$$
\hat X=\{ h(g_1(\vec x),\dots,g_k(\vec x)):k\in \mathbb{N}\wedge h,g_1,\dots,g_k\in X\},
$$
i.e. $\hat X$ is obtained from $X$ by taking compositions.
Fix $F\subset PR$ finite and let $I$ be the set of initial functions, i.e. $I$ consists of the unary successor function, the unary constantly $0$ function and all the projections. Define:
$$A_0=F\cup I$$
$$A_{n+1}=\hat{A_n}$$
$$A=\bigcup_{n\in\mathbb{N}}A_n$$
I'd like to show that $A\neq PR$.
In other words, the set of primitive recursive functions cannot be obtained from finitely many functions (plus the initial functions) just by taking compositions, i.e. the recursion part of definition is really necessary to get all the primitive recursive functions.
This is clearly not true if $F$ is not finite and just countable, since then we can just take $F=PR$, so $F$ being finite should play an important role.
Any hints?
EDIT: I've changed the question since the previous one was not very well formulated.
Comment: I may be being stupid, but don't the functions in your set $H$ only depend on at most a fixed prefix of the argument vector $\vec{x}$? I.e., as $F$ is finite, there is an $n$ such that no function in $F$ and hence in $H$ depends on $x_i$ for $i > n$.
Comment: You are using $n$ twice, I think for two different things. Are you assuming your functions $g$ in PR all have the form $g:\mathbb{R}^n\rightarrow \mathbb{R}$, for some fixed positive integer $n$?  It may also help to further illuminate/define the set PR.
Comment: @Michael There´s no constraint on the arity of primitive recursive functions, which go from $\mathbb{N}^n$ to $\mathbb{N}$ for different $n$. I've changed some of the notation, perhaps it´s more clear now? Plus I linked the definition of primitive recursive.
Comment: @RobArthan I think you're right.  I'll think about the problem some more to see if I can state it in a way that makes sense.
Answer: First, note that we can just do this in terms of one variable encodings of all the $g$'s, since if we find a majorizing function, we can lift it back to one which majorizes all the usual $g_i$'s.
Next we can define a function $G(x)$ which majorizes all the $g_i$'s via the primitive recursive
$$G(0) = \max_{i\leq k}(g_i(0)) + 1$$
and
$$G(n) = \max_{i\leq k}(g_i(n), G(n-1)) +  1$$
This definition also ensures that $G$ is increasing, so we have $x<y\implies G(x) < G(y)$, which allows composing this function to act well, as then
$$g_i(x) < G(x) \implies g_j(g_i(x)) < G(g_i(x)) < G(G(x))$$
and so on. Now we can define a primitive recursive function which majorizes all the elements in $\hat{X}$ via $F(1, x) = G(x)$ and
$$F(n,x) = G(F(n-1, x)) $$
Now, note that $F(n, x)$ majorizes all functions obtained via composing $n$ functions together. Also, since we've defined $\hat{X}$ inductively via compositon, every function in $\hat{X}$ is obtained by composing functions together $n$ times. Diagonalizing, we then get that $M(x) = F(x,x)$ is eventually greater than all the functions in $\hat{X}$ and we've found our majorizing function!


Error when creating a custom Twig filter

Question: I'm trying to create a custom Twig filter in Drupal 8. The goal is to use my custom filter in a template like so:
{{ a_variable|myfilter }}

I have created a custom module with 3 files:
MODULE.info.yml
MODULE.services.yml
src/TwigExtension/MyExtension.php

The MODULE.info.yml file contains the usual values.
The MODULE.services.yml file contains:
services:
  MODULE.twig_extension:
#   arguments: ['@renderer']  #  <-- Initial code (USELESS)
    class: Drupal\MODULE\TwigExtension\MyExtension
    tags:
      - { name: twig.extension }

The src/TwigExtension/MyExtension.php file contains:
namespace Drupal\MODULE\TwigExtension;

// use Drupal\Core\Template\TwigExtension;  // <-- Initial code (WRONG)

class MyExtension extends \Twig_Extension {
// class MyExtension extends TwigExtension {  // <-- Initial code (WRONG)

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('myfilter', array($this, 'myFilter')),
    ];
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'MODULE.twig_extension';
  }

  /**
   * Replaces all instances of "animal" in a string with "plant".
   */
  public static function myFilter($string) {
    return str_replace(array('animal'), array('plant'), $string);
  }

}

My initial code got following error: "Call to a member function generateFromRoute() on a non-object in /core/lib/Drupal/Core/Template/TwigExtension.php on line 224".
But I have now corrected the code following lauriii's answer and it works perfectly!
Comment: Hm, I have checked mine implementation and all seems fine. Are yo usure the error comes from your extension? Maybe you are calling bad function in twig somewhere? Try to switch to some core theme and call your function n there.
Comment: http://leopathu.in/content/create-custom-twig-filter-drupal-8 This article explained well about the custom twig filter with the example and also you could download the sample code from the page.
Comment: It was a subtle error, replacing `TwigExtension` with `\Twig_Extension`. ;-)
Answer: The problem in the code above is that your Twig extension class is extending the internal Drupal Twig extension class. That breaks the Twig extensions added by Drupal core and that's why you are getting the error.
To fix this, you should make your Twig extensions extend Twigs internal Twig extension class. Your class should be defined like this:
class MyExtension extends \Twig_Extension {

After making that change, you can also remove arguments set for that class from the MODULE.services.yml
Comment: Awesome, it works! Thank you so much, lauriii. I will update my original code to reflect your answer.
Comment: Strange... My initial code was modeled after that found in the `twig_extension_test` core module.
Comment: There is a patch pending to fix twig_extension_test. Test modules are not always the best examples unfortunately.
Answer: the above sample is still off.. (ie: the 'arguments' clause in .services does seem to be needed)
take a look at
/core/modules/system/tests/modules/twig_extension_test
to model a twig filter and function from!
Comment: follow up:  for whatever reason...  the twig_extension_test seems to only works when viewed under an /admin path...
Answer: it seems we need to use \Twig_Extension class more directly.
MODULE.services.yml

services:
  MODULE.twig.filters:
    arguments: ['@renderer']
    class: Drupal\MODULE\TwigExtension\HexToRgb
    tags:
      - { name: twig.extension }

/src/TwigExtension/HexToRgb.php

/**
 * @file
 * Contains Drupal\MODULE\TwigExtension.
 */

namespace Drupal\MODULE\TwigExtension;

/**
 * A Twig extension (filter) converts hex color to rgb.
 */
class HexToRgb extends \Twig_Extension {

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters() {
    return array(
      new \Twig_SimpleFilter('hexToRGB', [$this, 'hexToRGB'], ['is_safe' => ['html']]),
      new \Twig_SimpleFilter('rangeToPercent', [$this, 'rangeToPercent'], ['is_safe' => ['html']]),
    );
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'MODULE.twig.filters';
  }

  /**
   * convert 3 or 6 char hex color to comma seperated RGB colors
   */
  public static function hexToRgb($hex=000000) {
    $r = $g = $b = FALSE;
    $hex = str_replace("#", "", $hex);

    if(strlen($hex) == 3) {
      $r = hexdec(substr($hex, 0, 1).substr($hex, 0, 1));
      $g = hexdec(substr($hex, 1, 1).substr($hex, 1, 1));
      $b = hexdec(substr($hex, 2, 1).substr($hex, 2, 1));
    } else {
      $r = hexdec(substr($hex, 0, 2));
      $g = hexdec(substr($hex, 2, 2));
      $b = hexdec(substr($hex, 4, 2));
    }

    $rgb = array($r, $g, $b);

    return implode(",", $rgb);
  }

  /**
   * convert range (0 to 100) to a percent with 2 decimals
   */
  public static function rangeToPercent($range=0) {
    return round(($range/100), 2);
  }

}

Comment: `arguments: ['@renderer']` is unnecessary because the `\Twig_Extension` class has no constructor.
Answer: I was having a ton of issues with this on a site and I think I finally tracked down the problem: it was using twig/twig: ^3.
Here is code for a twig FUNCTION that works with twig/twig 2
my_module/src/TwigExtension/MyModuleInputTwigExtension.php:
<?php

namespace Drupal\my_module\TwigExtension;

/**
 * Custom Twig extension to format my field.
 */
class MyModuleInputTwigExtension extends \Twig_Extension {

  /**
   * {@inheritdoc}
   */
  public function getFunctions() {
    return [
      new \Twig_SimpleFunction('format_hours_msg', [$this, 'formatMsg'], ['is_safe' => ['html']]),
    ];
  }

  /**
   * Formats a string for proper output.
   *
   * @param string $string
   *   The input string.
   *
   * @return string
   *   The formatted string.
   */
  public function formatMsg($string) {
    // string formatting code  for $string
    return $string;
  }
}

my_module.services.yml:
services:
  my_module.function:
    class: Drupal\my_module\TwigExtension\MyModuleInputTwigExtension
    tags:
      - { name: twig.extension }

But when I tried to use a similar method with /Twig_SimpleFilter or even /Twig_SimpleFunction and whatnot on the other site, it threw:

Uncaught Error: Class "Twig_Extension" not found in /var/www/docroot/modules/custom/my_module/src/TwigExtension/MyModuleInputTwigExtension

When I removed the /TwigExtension/ from the routing file, it threw:

Service 'my_module.twig_extension' for consumer 'twig' does not implement Twig\Extension\ExtensionInterface.

Here is code for a twig FILTER that works with twig/twig 3:
my_module/src/TwigExtension/MyModuleInputTwigExtension.php:
<?php

namespace Drupal\my_module\TwigExtension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

class MyModuleTwigExtension extends AbstractExtension {

  public function getFilters() {
    return [
      new TwigFilter('to_https', [$this, 'toHttpsFilter']),
    ];
  }

  public function toHttpsFilter($url) {
    // Check if the URL starts with 'http:' or 'https:' and replace it with 'https:'
    $url = preg_replace('/^(http:|https:)?/', 'https:', $url);

    return $url;
  }
}

I've also see the return line for getFilters() look like this:
'to_https' => new TwigFilter('to_https', [$this, 'toHttpsFilter']),

my_module.services.yml:
services:
  my_module.twig_extension:
    class: Drupal\my_module\TwigExtension\MyModuleTwigExtension
    tags:
      - { name: twig.extension }

Answer: Try https://www.drupal.org/project/twig_extender . Add a plugin system for custom twig functions and filters


Conditions In evets in wpf (XMAL)

Question: I need to change the height of tabcontrol.
How can I use condition in XAML?
In case of height 180- I need to do change the height to 30
In case of height 30- I need to do change the height to 180

            <EventTrigger RoutedEvent="Button.Click" SourceName="btnOpenState">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation
                                Storyboard.TargetName="tbViews"
                                Storyboard.TargetProperty="Height"
                                From="30" To="181" Duration="0:0:1"
                                AutoReverse="False" RepeatBehavior="1x" />
                        </Storyboard>
                    </BeginStoryboard>

Answer: You can use binding and an IValueConverter to do this.  (Note that you don't need to set From in the Storyboard if the target is already set to that value.)
To="{Binding ElementName=tbViews,Path=Height,Converter={StaticResource HeightConverter}}"

Here HeightConverter should implement IValueConverter, returning for the conversion ((double)value < 180) ? 180 : 30.

Conditions In evets in wpf (XMAL)


R - Importing a text file which includes information in header lines above the main data table

Question: I'd like to import a text file which contains a table of results with two 'header' lines of text above it. The contents of the header lines needs to be included as extra columns in the resulting data.frame.
In the following example text file, the Region and Month lines are the header lines, and the remainder of the file is the results table.
Region  South Africa
Month   July
Sepal.Length    Sepal.Width Petal.Length    Petal.Width Species
1   5.1 3.5 1.4 0.2 setosa
2   4.9 3   1.4 0.2 setosa
3   4.7 3.2 1.3 0.2 setosa

needs to become a data.frame which includes columns for Region and Month:
wanted.df<-structure(list(Sepal.Length = c(1, 2, 3), Sepal.Width = c(5.1,
4.9, 4.7), Petal.Length = c(3.5, 3, 3.2), Petal.Width = c(1.4,
1.4, 1.3), Species = c(0.2, 0.2, 0.2), Region = c("South Africa",
"South Africa", "South Africa"), Month = c("July", "July", "July"
)), row.names = c(NA, -3L), class = c("spec_tbl_df", "tbl_df",
"tbl", "data.frame"))

I've managed to do it by creating two data.frames, one containing the header info, the second containing the result table and then merging them, but this seems to me a bit ungainly:
#Create data frame from first two lines of text (the header)
header <- scan('example.txt', nlines = 2, what = character(),sep = "\n")
header.df<-data.frame((sapply(header,function(x){str_split(x, "\t")})),stringsAsFactors=FALSE)
colnames(header.df) <- as.character(header.df[1,])
header.df<-header.df[-1,]

#Create data frame from first remainder of the file which contains the results table
results.df<-read_tsv('example.txt',col_names = T,skip=2)

#helper column added to both data frames for merging
results.df$helper.col<- "match"
header.df$helper.col<-"match"
df.example<-inner_join(results.df,header.df, by = "helper.col", copy = FALSE)
wanted.df<-select(df.example,-helper.col)

Is there a more elegant way?
Comment: How do you know "South Africa" is one word and not separate words? Or do you know there is always going to be only two columns in header ?
Comment: @RonakShah - It seems to be a tab separated file (OP uses `read_tsv()` and splits the header info on `\t`).
Comment: @RonakShah, yes, it is a tab separated file (and the number of columns in the header is fixed).
Answer: Assuming @H 1's comment is correct that it is a tab-separated file. We can do
df1 <- read.table('example.txt', nrows = 2, sep = "\t")
df2 <- data.frame(matrix(df1$V2, ncol = nrow(df1), dimnames = list(NULL, df1$V1)))
df3 <- read.table(text = 'example.txt', skip = 2, header = TRUE)
cbind(df3, df2)

#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species       Region Month
#1          5.1         3.5          1.4         0.2  setosa South Africa  July
#2          4.9         3.0          1.4         0.2  setosa South Africa  July
#3          4.7         3.2          1.3         0.2  setosa South Africa  July

Answer: I would do it in this way:
header <- readLines('file.txt', n = 2)
header <- stringi::stri_split_regex(header, '\\W+', n = 2)

dat <- read.table('file.txt', skip = 2, stringsAsFactors = FALSE)
for(i in header){ dat[ i[1] ] <- i[2] }

# > dat
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species       Region Month
# 1          5.1         3.5          1.4         0.2  setosa South Africa  July
# 2          4.9         3.0          1.4         0.2  setosa South Africa  July
# 3          4.7         3.2          1.3         0.2  setosa South Africa  July


Problem with Node module on website

Question: Please bear with me on this one, as I am a complete newbie with Drupal, and am helping out a client on this one, so am trying to relay the problem they are having.
It appears that they are having trouble with a Node module, this module is used to add events and sell tickets to these events.
Currently when a new event is added by 'admin' it is only viewable by admin, so anonymous users can't see any see any events events. We think it has something to do with permissions or a between some modules, but as a say not really understanding the product i'm struggling to get to the bottom of it.
One of our developers also thinks that it could be something relating to a field used in the event, and user doesn't have access to read this field (permissions).
It seems that for each there is a diferent permision filed in permisions section in admin panel.
Has anyone had this trouble before? Any help, ideas or even questions on this very  welcome. We may have to get someone in to finish this job off.
I may also have most of this backwards, so please ask if you need anymore info, or what I should look at and I can supply this straight back to you.
Thanks for the patience :)
Answer: There are a number of permissions that could be affecting this.
First off, node permissions.  The most important one here is 'access content,' so make sure anonymous users can do that. After that, they can be set up so different users in different roles can create, delete and/or edit nodes.
Given that they aren't trying to do any of this, I doubt it's related to these node permissions, so let's go drill down a granularity level and look at permissions on fields in the nodes themselves.  Here, permissions can be set on edit and view.  Given they aren't trying to edit a node, just look at it, I'd look at the view permissions.
Assuming 'admin' is uid 1, s/he can do anything, so look for fields that aren't viewable by the more casual user/role.  Somewhere in there as you surmised above is the field that this module needs to show itself.  (Oh, also, if you are using imagecache, make sure its permissions are set up as well)
Comment: Hi Jimajamma, whats your background? would you be able to help us out of a tight spot?
Comment: If you're at 01******8696 I can certainly give you a call and see if I can help out over the phone talking you through some of the admin screens and such but much more than that, even though I know I am a good guy, I wouldn't trust just anyone from the interwebs (lol) inside my system :)
Comment: Ha, completely agree, I and getting the whole system moved today onto a new server. As soon as this has been done I will go over your pointers and maybe have to contact you over the next few days...

Problem with Node module on website


C# Decode base64 Zlib string with Ionic.Zlib

Question: I'm trying to decode a compressed string inside an XML without any success:
Basically I want to decode and get back the decoded string.
This is the xml node with my compressed data:
<data encoding="base64" compression="zlib">
   eJztmNkKwjAQRaN9cAPrAq5Yq3Xf6vVIbQJjEZR+nDwQZScrwztoORECLySBcIgZ7nc2y4KfyWDLx+Jb9nViNgDEwY+KioAXUgQN4+zpoCMwPmQAtoAx2CLFbA2oDEo9+hwG8DnIDtF/2K8ks086Tw2zH0uyMv7HcRr/6/EvvhnsPrsrxwX7rwU/0ODig/eV3mh3N1ld8eraWPaX6+64s9McesfrqcHfg1MpoifxcVEWjukyw+9AtFPl/I71pER3Of6j4bv7HI54s+MChhqLlPdZ/P3qMmFuo5h5NnTOhjM5tReN2yT51n5/v7J3F0vi46fk+ne7aX0i9l6If7mpufTX3f5wsqv9TAD2fJLT9VrTn7UeZnM5tR+v0LMQOHXwFnxe2/warGFRWf8QDjOLfP
  </data>

Because of Unity and Mono (the env I'm working on) I can't use System.IO.Compression.
so that I'm implementing Ionic.Zlib.
This is the syntax:
public static string DecodeBase64Gzip(string input)
{
  byte[ ] ZlibBuffer = Convert.FromBase64String(input);
  MemoryStream comp = new MemoryStream(ZlibBuffer);
  Stream zlib = new Ionic.Zlib.ZlibStream (comp, Ionic.Zlib.CompressionMode.Decompress);
  return new System.IO.StreamReader (zlib, System.Text.Encoding.UTF8).ReadToEnd();
}

For sure I'm doing some mistake because as output i get an empty string.
I tryied also in that way:
public static string DecodeBase64Zlib(string input)
    {
        byte[ ] ZlibBuffer = Convert.FromBase64String(input);
        return ZlibStream.UncompressString (ZlibBuffer);
}

But with the same result (empty string...)
Have you some advice? Thanks in advance!
Answer: "This is the xml node with my compressed data".  How did you compress the data?  It is messed up somehow.  After base64 decoding (which by the way does not terminate properly), the data starts with a valid zlib header, but that is followed by invalid deflate data.
Comment: Hi Mark. The tmx (xml!) file is compressed from another software, following these rules: https://github.com/bjorn/tiled/wiki/TMX-Map-Format#data  As I told before the compression is done with zlib and the encoding is base64. I don't get any header or other exception.
Comment: I don't know how, but the data you provided is not what is described.  The zlib stream is corrupted, and the base64 string is not complete.  You should verify that you are extracting the data correctly, and that there is no error in your cut and paste into the question.


to prove that a particular element is a central element

Question: If $x$ to $x^n$ is an automorphism of $G$. Show that for all $x\in G$, $x^{n-1}$ is a central element of $G$.
I am not really sure how to go about the proof so I am looking for some clue on how to go about it.
Answer: Hint: $x^{n-1}y^n = x^{-1}x^ny^n=x^{-1}(xy)^n= (yx)^nx^{-1}=y^nx^nx^{-1}=y^nx^{n-1}$.
Answer: Let $ g, x\in G$, we want to prove that $x^{n-1}g=gx^{n-1}$. Since $y$ to $y^n$ is an automorphism in $G$, we can assume without loss of generality, that there is $y\in G$ such that $y^n=g$.
Now, since $y$ to $y^n$ is an automorphism in $G$,
$$ x^ny^n=(xy)^n \,\,\textrm{ and }\,\, y^nx^n=(yx)^n$$
So
$$ x^{n-1}y^n=y(xy)^{n-1} \,\,\textrm{ and }\,\, y^nx^{n-1}=(yx)^{n-1}y$$
But $y(xy)^{n-1}$ and $(yx)^{n-1}y$ are exactly the same product of $x$ and $y$, so we have $ x^{n-1}y^n= y^nx^{n-1}$.


Spinner not getting populated with the given string array

Question: I have to make an android app. It is about counting Bunks for college students.
So I want to make it like this:
Spinner 1 has
Select Branch

ME
CE
IT
EE

Select semester
1st
2nd
3rd
4th
etc.
Now if student is selecting ME and 3rd semester, then his 3rd semester Subjects should come
like:
Enter Bunks of Subject:
ABC1: EditText
ABC2: EditText
ABC3: EditText
ABC4: EditText
ABC4: EditText
and this input by user should come to logic of percentage of attendance, and answers should come on another page with same subject name.
Can anyone help me please?
EDIT
My Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

Comment: This is your assignment for marks, and you're just asking other people to do it? Start the project, work on it yourself, and come back with specific questions that show you've tried to learn on your own.
Comment: You want how to make and populate a spinner??...and depending on the item selected on the spinner show respective forms...if so, i can paste the code i am using for my app
Comment: please give more information so someone can help you.
Comment: NONO .. m not asking for readymade codes .. i want Help.. I am new here...

See what i ve done until now..
Answer: XML for spinner:
<Spinner
android:id="@+id/city_spinner_iWant"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="@string/citySpinner"
android:textColor="@color/white"
android:textSize="20dp" />

in code, set the adapter to populate the spinner with requires items (in your case branches):
String[] city_array = new String[]{"London", "Newyork", "Paris"};

ArrayAdapter<String> cityArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,city_array);

city_spinner = (Spinner) findViewById(R.id.city_spinner_iWant);
city_spinner.setAdapter(cityArrayAdapter);

Then to show forms depending on the item selected in the spinner:
city_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> adapter, View v,int i, long lng) {

selected_city = adapter.getItemAtPosition(i).toString();
Toast.makeText(getApplicationContext(), selected_city, 1000).show();

//conditions depending on selected_city (in your case selected branch)
}
public void onNothingSelected(AdapterView<?> arg0) {

//no need to impement this
}
});

Comment: yes ive done the same.. took paths as  string array..
can you please tell me how to post my code here? so can show you!
its showing me no charcter left
Comment: how to add options? in spinner
Comment: click edit under your question ----> paste the code ----> select it and press Ctrl+k ----> save changes
Comment: what do you mean by options??
Comment: My Main.xml
Comment: I mean that string "London, Newyork, Paris" its not showing in spinner
Comment: Sir can u please see this

https://docs.google.com/file/d/0B8kSGDgP5vndeTJwaFprQ1dOcEE/edit

goto file and download
Comment: Yes adapter & all.. but its showing me error.. please download that file.. its done by me
Comment: or atleast the log cat....what error exactly is it??....null pointer exception or something like that
Comment: look, i don't know what your code is, but i just tried the code i pasted....and it worked as expected


Django List Displays Out of Order

Question: I have a django list that I use {% regroup ranked_matches by rank as ranked_matches %} to sort in the template however there is one value that is always out of order. I've gone into the db and changed it several times however this value is always out of order. Can anyone shed any light as to what might be causing this?
Also I realize I've posted very little code, I'm not sure what is relevant here. Thanks.
EDIT:
I just noticed I'm having a similar issue but here the alphabetical sort for another list is off for only one value. I've gone into the django admin and if I try sorting by the column in question it sorts properly there. This makes me believe that it is not an issue with the value stored in the db.
Comment: Is this value a field in your model? Is it a `BooleanField`, `CharField`, etc. or a related field like `ForeignKey`?
Answer: {% regroup ... %} will organize lists by your grouper, but it will not sort the resulting list by the grouper.
If you have a list of dictionaries, consider using the dictsort filter together with the regroup tag.
Otherwise, your can first regroup your list, then sort using dictsort, and finally regroup again. The second regroup will need a grouper that can handle the output generated by the first regroup.
https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#grouping-on-other-properties
Comment: Or just sort in your view rather than your template.

Django List Displays Out of Order