Php JavaScript Form Popup

Question: I am trying to have my script be able to use a popup to enter one of the textboxes, which works, but when I go to calculate the values it does not calculate them. I think it has something to do with the form id, but I do  not know specifically what to change.

<?php
$emitter = 0;
$rings = 0;
$wave = 0;
$gls = 0;
$tiles = 0;
$fov = 0;
if(isset($_POST['calculate']))
{
    $rings = $_POST['rings'];
    $wave = $_POST['wave'];
    $emitter = $_POST['emitter'];
    $gls = round(22 * sin($wave / ($emitter / tan ($emitter / 4))), 2);
    $tiles = round(5 * $rings, 2);
    $fov = round((90 / M_PI) * $gls * (sqrt(9) / 4) * $rings, 2);
}
?>

        <title>Field of View Calculator</title>

<form id="frm1 method="post" action="Test_Calculator.php" enctype="multipart/form-data">

Field of View

        Input
        Intermediate Variables
        Output

        Number of Rings <input type="text" name="rings" value = "<?php echo $rings; ?>" size="30">
        Grating Lobe Separation <input type="text" name="gls" value = "<?php echo $gls; ?>" size="30">
        Field of View <input type="text" name="fov" value = "<?php echo $fov; ?>" size="30">

        Wavelength <input type="text" name="wave" value = "<?php echo $wave; ?>" size="30">
        Number of Tiles <input type="text" name="tiles" value = "<?php echo $tiles; ?>" size="30">

        Emitter Space<input id="email1" type="text" name="emitter" value = "<?php echo $emitter; ?>" size="30">
        <input id="email" onclick="resetPassword()" type="text" name="email" placeholder="Search Value" />

        Static Values

        <textarea name="content" cols="80" rows="15"></textarea>

        <input type="submit" name="calculate" value="Calculate">

</form>

Comment: Maybe not related You are missing a double quote `id="frm1` should be `id="frm1"`
Answer: <form id="frm1 method="post"

should be
<form id="frm1" method="post"

missing one "
and
Intermediate Variables

should be
Intermediate Variables

has extra " after align
Hope this helps
Comment: Glad to help. Simple mistake can cost you hours and a lot of headaches.

Php JavaScript Form Popup


Unexpected Warning using Enum Functional API - PyCharm Bug

Question: Using the Functional API example given in documentation 8.13.12. I get the following Warning (using python 3.6). The code does work in the console but I'd rather not have warnings upon my code inspection. What am I doing wrong? And how can I get rid of the warning?
<code>from enum import Enum
Animal = Enum('Animal', 'ANT BEE CAT DOG')
</code>

Unexpected argument(s) Possible callees: Enum.new(cls: Enum, value) object(self: object) less... (Ctrl+F1)
  Inspection info: Reports discrepancies between declared parameters and actual arguments, as well as incorrect arguments (e.g. duplicate named arguments) and incorrect argument order. Decorators are analyzed, too
Comment: Just found this in jetbrains bugtacker, some users claim the bug has been going since late 2015.... :(  https://youtrack.jetbrains.com/issue/PY-17877
Comment: Can not reproduce.  Are you sure this isn't just some stupid PyCharm garbage?  Python itself doesn't try to do a static inspection like that.
Comment: This is a PyCharm issue.  Please file a bug with them to include proper `Enum` support.
Comment: Yes I'm using PyCharm, but I don't use another editor. Anyway, I wasn't expecting the error and it's both frustrating and confusing. I can't understand what I'm doing wrong. Using latest PyCharm Community 2018.3.2.
Answer: The bug was fixed in PyCharm 2020.1.


FetchType = Lazy and optional = false not working in JPA

Question: I am using many to one mapping in my account entity
@ManyToOne(fetch = FetchType.LAZY,optional = false)
    @JoinColumn(name = "CONTACT_ID", referencedColumnName = "CONTACT_ID", nullable = false)
    private Contact Contact;

In my DAO I am retrieving the data:
entitymanager.createQuery("SELECT v FROM Account v").getResultList();

Though I am using optional = fasle and fetchType = Lazy. I see that it is running all queries and retrieving referenced table data.
I am using spring boot. Below is my Entitymanager configuration
@Configuration
@EnableTransactionManagement
public class DatabaseConfig {

  @Autowired
  private Environment env;

  @Autowired
  private DataSource dataSource;

  @Autowired
  private LocalContainerEntityManagerFactoryBean entityManagerFactory;

  @Bean
  public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    /*dataSource.setDriverClassName(env.getProperty("db.driver"));*/
    dataSource.setUrl(env.getProperty("db.url"));
    dataSource.setUsername(env.getProperty("db.username"));
    dataSource.setPassword(env.getProperty("db.password"));
    return dataSource;
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean entityManagerFactory =
        new LocalContainerEntityManagerFactoryBean();

    entityManagerFactory.setDataSource(dataSource);
    entityManagerFactory.setPackagesToScan(env.getProperty("entitymanager.packagesToScan"));
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    entityManagerFactory.setJpaVendorAdapter(vendorAdapter);
    Properties additionalProperties = new Properties();
   // additionalProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    additionalProperties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
   // additionalProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    additionalProperties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    entityManagerFactory.setJpaProperties(additionalProperties);
    return entityManagerFactory;
  }

  @Bean
  public JpaTransactionManager transactionManager() {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(entityManagerFactory.getObject());
    return transactionManager;
  }

  @Bean
  public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
  }

In application.properties
hibernate.hbm2ddl.auto: update
hibernate.dialect: org.hibernate.dialect.Oracle12cDialect
hibernate.show_sql: true

Comment: How do you have configured your persistence.xml?
Comment: I am using spring boot so have configured in the java configuration class.I have updated my question with the details
Comment: Possible duplicate of [How to serialize only the ID of a child with Jackson](https://stackoverflow.com/questions/17542240/how-to-serialize-only-the-id-of-a-child-with-jackson)
Answer: Try this:
Use @JsonIgnore where you have given relationship between two entities.

@JsonIgnore : as Spring Data REST will ignore fields or getters that
  are marked up with @JsonIgnore annotations.
Comment: I want to get the contact_id but I don't want to get entire contact entity.
Comment: @JsonManaged or something like that


If an abelian group has subgroups of relatively prime orders r and s(which are cyclic), there exists a subgroup of order rs?

Question: Task is:

Let $G$ be an abelian group and let $H$ and $K$ be finite cyclic subgroups with $|H| = r$ and $|K| = s$.
Show that if $r$ and $s$ are relatively prime then $G$ contains a cyclic subgroup of order $rs$.

I'm thinking about how to solve this.
My intuition is that because the orders are coprime and the groups are cyclic, the generators must be $r$ and $s$, by Lagrange's theorem. That would mean that the elements of the groups are distinct and since the group is abelian, we can simply count the pairs, giving us a group of $rs$ order.
Is this correct?
Comment: Instead of saying generators must be $r$ and $s$, I think you wanted to say the order of the generators of the respective subgroups are $r$ and $s$. Your thought process is fine, but you have to prove things that you are claiming, for example why would the elements necessarily be distinct in $H$ and $K$.
Comment: Note that $H\cap K$ must be trivial.
Answer: Hint: How many any elements does $\{ hk : h \in H, k \in K \}$ have? Note that $hk=h'k'$ iff $h^{-1}h'= k(k')^{-1}$ and $h^{-1}h'= k(k')^{-1} \in H \cap K$.
Comment: |H| * |K|, iff elements are distict. The "distinct" part is what im having troubles proving.
Comment: @Hristmar, see my edited hint
Answer:
generators must be $r$ and $s$

The above statement does not make much sense since $r$ and $s$ are not the group elements. You mean to say "generators must be $x$ and $y$ where $x$ and $y$ are the elements of order $r$ and $s$."

Your idea is correct. You would, however, need to prove that $\langle x, y\rangle$ does indeed have order $rs$. To do this, you would need to show that if
$$x^a = y^b$$
for $0 \le a < r$ and $0 \le b < s$, then it is forced that $a = 0 = b$.
This will then tell you that the set $\{x^ay^b \mid 0 \le a < r,\;0 \le b < s\}$ has cardinality no less than $rs$. (Why?)

Alternately, you could try to show that the element $xy$ itself has order $rs$. (The proof will be almost identical to the above one.) Then, you can simply consider the subgroup $\langle xy\rangle$.

EDIT: Details on how to prove that $a = 0 = b$ claim.
We can note that $x^a \in H$ and $y^b \in K$. Since the two elements are assumed to be equal, we see that $x^a \in H \cap K$.
However, note that $H \cap K$ is a subgroup of $H$ and of $K$. (Why? Show that the intersection of subgroups is again a subgroup.)
Thus, the order of $H \cap K$ must divide that of $H$ and $K$. This gives us that $|H\cap K| = 1$ and thus, its only element is the identity. Thus, $x^a = 1 = y^b$. Conclude.
Comment: Since the subgroups have order r and s, $x^a$  for some xEH must generate the entire subgroup H, since H has no non-trivial proper subgroups. Hence $x^a = y^b$ cannot be correct for anything other than $a=id=b$ as the orders of the subgroups are coprime. Hence the elements are distict and the number of pairs is rs. Am i correct?
Comment: Why does $H$ have no nontrivial proper subgroups? Consider $G = \Bbb Z/8 \Bbb Z$, $x = \bar{2}$. Then $H \cong \Bbb Z/4 \Bbb Z$ and your claim is incorrect
Comment: I had assumed r and s were prime, which is not necessarily true. My bad.
Comment: Since you know Lagrange's theorem, I have edited and added more details on how to prove the claim using that.
Comment: I understand the answer ! Thank you!
Comment: Great! :) $\phantom{padding}$


How to add a collection(list etc) param in prepared statement cursor

Question: So I am using asyncpg prepared statement and executing query. I am passing positional arguments in my query.
Currently, I pass stmt.cursor(params[0], params[1]) but what if I don't know how many arguments are being passed so wanted to pass a list or something to this method. How can I achieve this in this case?
My current code:
async def execute_ps(dsn):
    conn = await asyncpg.connect(dsn)

    sql_query = """select * from table1 where id = $1 and name=$2"""
    params = [var1, var2]
    stmt = await conn.prepare(sql_query)

    result = []

    try:
        async with conn.transaction():
            async for record in stmt.cursor(params[0], params[1]): # want to pass list here
                print(record)
                result.append(record)
    except Exception as e:
        print("exception: {}", e)

    if conn is None:
        await conn.close()

    return result

Answer: My bad. I found out it has to be using *. I am new to python so didn't get it at the first thought!
async for record in stmt.cursor(*params)


How to replace special character, and then store that into a shell variable?

Question: I'm doing some script shell work, and I'm not entirely sure what I'm doing wrong. The code
#!/bin/bash

IFS='
'
sed s/"$1"/"$2"/g "$3" > "$3.updated"
mv "$3.updated" $3

Is a shell script named "sub1". Sub1 is passed three variables; a string to be replaced ($1), a string which replaces it ($2), and the name of the file ($3). I am attempting to modify the above code so that if the character to be replaced is a "special character", (like * or / or .), I can replace it into a 'safe' version (i.e "*" if the character was a *)
My code is as follows.
#!/bin/sh
IFS='
'

"$1" = $target
sed 's/*//*/g' "$target" > "$newtarget"
"$1" ="$newtarget"
sed s/"$1"/"$2"/g "$3" > "$3.updated"
mv "$3.updated" $3

However, when the following command is entered to test my code (./sub2 * x testcase2), testcase2 merely containing the text "test*test", I get the following errors.
 ./sub2: 5: ./sub2: 252225688.dat: not found
 ./sub2: 6: ./sub2: cannot create : Directory nonexistent
 ./sub2: 7: ./sub2: 25225688.dat: not found

I'm very confused as to the reasoning behind these errors; 252225788.dat isn't called in my code (though it is in the same directory as my sub2 script), so I have no clue why that would even be a problem. I opened up 252225788 with emacs to see what it contained, and it was only the text "%%%%%%%%". I'm very confused as to what I'm supposed to be doing here. At first I thought it was just my syntax, but the whole deal with 252225688 has thrown me off completely.
EDIT:
What I'm trying to do is that the $1 parameter could have a number of 'unsafe' characters in it (i.e., [, ], ., , ). The parameter could just be something like "", it could be "L*", it could be "w\o\r\d\". I'm told I should put the target string ($1 parameter) into a shell variable, $target like I did, and then use a sed command to rewrite those characters ([,],^, , those ones) into safe versions by either adding backslashes in front, or surrounding them by []. I would then store that rewritten version of the string into another shell variable ($newtarget). I assumed I would go about the actual replacement (sed, rewriting the shell variable) with my "sed 's/""/"/*"/g'" deal, but apparently that's not the right way to go about it.
Comment: In addition to needing to quote a `*` on the command line as @pfnuesel said, there are a couple of errors. Inside a shell script, `$1` is replaced by the first argument you gave to the shell script. It's unlikely you want this on the left hand side of an assignment statement. Did you perhaps mean to write `target="$3"`? (Don't put any spaces between the variable and the =). Also, * is special to `sed`. Can you tell us what `s/*//*/g` is supposed to do? We'll help you rewrite it.
Comment: I'm sorry, I didn't see this earlier s/*//*/g is supposed to find instances of the "*" character, and replace it with "/*", since I assumed that was how I did it syntax wise. And for the $1 bit, I just need the $target to be equal to the $1 parameter, do what I need to with $target, save that to $newtarget, and then save the value back over to $1
Comment: Edited my main question.
Comment: You need to quote special regular expression characters in sed, so use `sed 's/\*/\//g'` . Shell assignments are of the form `variable=value`. No spaces around the =. No $ in front of variable unless you want to use its contents. You can't assign to $1 inside shell scripts (you can use the `set` command to see a new arument list, but you don't need that here).
Answer: * is expanded by the shell to the list of files in your current directory, this is called glob expansion or globbing. Try
$ echo *
> file1
> file2
...

If you want to echo *, you need to escape it
$ echo \*
> *

or put it in quotes
$ echo "*"
> *
$ echo '*'
> *

Another option is to turn off glob expansion
$ set -f
$ echo *
> *

but unlikely that you want that, since glob expansion is a good thing.
So if you want to pass * as a character to a script of yours, escape it or put quotes around it.


Least upper bound for sequence $s_n= 2^{(-1)^n}\left (1- \frac{1}{n}\right) \sin\frac{nπ}{2}$

Question: Let $\{s_n\}$ be a sequence of reals such that $$s_n= 2^{(-1)^{n}}\left (1- \frac{1}{n}\right) \sin\frac{nπ}{2}.$$ Then find the least upper bound of $s_n$?
Here, $s_n$ will be 0 whenever $n$ is even and when n is odd, then $s_n=\frac{1}{2} \left (1- \frac{1}{n}\right) \sin\frac{nπ}{2}$, also since $|\sin x| \leq 1$ for all $x \in \mathrm{R}$, therefore
$$ - \frac{1}{2} \left (1- \frac{1}{n}\right) \leq s_n \leq \frac{1}{2} \left (1- \frac{1}{n}\right) $$
So supremum should be $\frac{1}{2}.$
Is my argument correct?
Answer: Hint for another approach:
examine $n\equiv ?\pmod{4}$ and find $\displaystyle\lim\sup s_n$
Comment: Subsequences $\{s_{4m+1}\}$ and $\{s_{4m+3}\}$ tend to $1/2$ and -$1/2$ respectively, so $1/2$ and -$1/2$ are limit superior and limit inferior respectively.
Answer: Your argument is not complete. To say that the supremum is $\frac 1 2$ you also have to show that $s_n$ attains values arbitaririly close to $\frac 1 2$. One way of doing this is to observe that $s_{4m+1} \to \frac 1 2$.


Spectrum of a ring in which $a^p=a$ for all $a$ and prime number $p$

Question: It is known the result that spectrum of a boolean ring is zerodimensional and compact topological space, e.g. has a base with clopen sets and satisfies Haussdorf condition. It is asked if this result can be generalized for $\mathbb{Z}_p-$algebra $A,$ where $p$ is a prime number, such that $a^p=a$ for all $a\in A.$ It seems for me that it is true also for such that rings.
Indeed, note that for arbitrary $x\in A$ we have $$V(x)\cap V(1-x^{p-1})=V((x)+(1-x^{p-1}))=V(A)=\emptyset$$ and $$V(x)\cup V(1-x^{p-1})=V((x)(1-x^{p-1}))=V(0)=\text{Spec}A,$$
so each base open set is closed and each base closed set is open. We can easily note like in boolean ring such that every prime ideal in A is maximal because his quotient is the field isomorphic to $\mathbb{Z}_p,$ so for prime ideals $\mathfrak{p,q}$ we know that $\mathfrak{q}\not\subset\mathfrak{p},$ so it exists $x\in \mathfrak{p}\setminus\mathfrak{q}.$ So we have $\mathfrak{p}\in V(x)$ and $\mathfrak{q}\in \text{Spec} A\setminus V(x)=V(1-x^{p-1}).$ Hence $\text{Spec}A$ is Haussdorf.
I'm not sure if my reasonings are correct. My intuition says that it is something incorrect because I thought that $0-$dimensional compact topological space is the spectrum of some boolean ring...
Answer: Yep this is correct!
Consider the following algebraic characterization of $0$-dimensional rings.

A ring $R$ is $0$-dimensional iff for every $x \in R$ there exists an $n \in \mathbb{N}$ such that $x^{n+1} R = x^n R$

Proof I think you already know the if direction.  Conversely, suppose for the sake of contradiction that $x^{n+1} y \not= x^n$ for any $y \in R, n \in \mathbb{N}$.  Then in particular the multiplicative set generated by the elements $x, 1-xy$ does not contain $0$.  So there's a prime $\mathfrak{p}$ disjoint from this multiplicative set.  That would firstly imply $x \notin \mathfrak{p}$, but since the ring is $0$-dimensional by assumption, $\mathfrak{p}$ is maximal and then $x$ is a unit in $R/\mathfrak{p}$, hence $ax - 1 \in \mathfrak{p}$ for some $a \in R$, also a contradiction.  $\square$
In your case $a^p = a$, so in fact $a^2R = aR$.
Also note that any $0$-dimensional ring is Hausdorff with respect to the Zariski topology.  This is a special case of the fact that

The minimal prime spectrum of a ring is always Hausdorff with respect to the (topology induced by the) Zariski topology.

Proof Indeed, if $\mathfrak{p}, \mathfrak{q}$ are two distinct minimal primes of a ring, then find an element $f \in \mathfrak{p} \setminus \mathfrak{q}$.  Since $f \in \mathfrak{p}$, the image of $f \in R_\mathfrak{p}$ is in the nilradical of $R_\mathfrak{p}$, hence there exists $s \notin \mathfrak{p}$ such that $sf^n = 0$ for some $n$.  In particular, $\mathfrak{q} \in D(s), \mathfrak{p} \in D(f)$, and $D(f) \cap D(s) = \emptyset$, so we've separated $\mathfrak{p}, \mathfrak{q}$ $\square$.
You can also show that the minimal prime spectrum of a ring is totally disconnected with respect to the Zariski topology.  So $0$-dimensional rings are quasi-compact, Hausdorff, and totally disconnected (so yes they are $0$-dimensional as topological spaces too).
As you say, Stone duality assures us that the spectrum of any $0$-dimensional ring can be realized as the spectrum of a Boolean algebra.  In particular, we can put a Boolean algebra structure on the idempotents of any ring by defining addition as the map sending $(e,f) \to e + f - 2ef$ (and multiplication inherited from the ring).  This is isomorphic to the canonical algebra structure on the clopens of the Zariski topology.  Stone duality is telling us that the idempotent algebra associated to a $0$-dimensional ring has the same spectrum as the original ring.


What is difference between  and  in maven plugin (jbehave example)

Question: As in title - here is piece of code.
I can have < scope > as well as < phase >
Jbehave documentation doesn't say much about it (http://jbehave.org/reference/stable/maven-goals.html)
               <execution>
                    <id>run-stories</id>
                    <phase>test</phase>
                    <configuration>

                        <includes>
                            <include>**/*Stories*.java</include>
                        </includes>
                    </configuration>
                    <goals>
                        <goal>run-stories-as-embeddables</goal>
                    </goals>
                </execution>

Answer: The <phase/> element/property is a "standard" Maven property that indicates which phase of the Maven lifecycle the execution will occur in.
The <scope/> element/property you're referring to is specific to the JBehave plugin itself. Per the plugin's documentation, it seems that <scope/> is used to control which "set" of your project's Maven dependencies will be included in the JBehave plugin run. Per this answer on the JBehave site, it seems that, typically, JBehave is executed using only the project's main dependencies and code, not the test dependencies and code.


Can an interior wall be built over an existing heat/air vent allowing air in both rooms

Question: I am looking to build an interior wall in my master bedroom to creat a walk in closet.  The best placement for the wall hits directly in the center of a current heat/air
Comment: what's the floor? hardwood? carpet? Your best bet is to move the vent to the BR, no sense in heating the closet.
Comment: The answer to this question must be "probably" because it's not clear what you're asking. You'll want to move the vent to the main room, right? Please revise to clarify.
Comment: You need a *register boot* or an *(oval) stack head*. It's probably 6" round, or oval. Might be 14x3.25 square... you'll figure it out. I'm not a fan of using walls as a chase, especially for supply air; duct it back how it should be.
Comment: @Mazura one could extend the duct itself into the interior wall...
Comment: That's part of *how it should be.* 'directly in the center' couldn't be better, unless it's perpendicular. Then you have to patch little bits of floor, and transition the duct (mangle it) which will cut it off significantly, unless you can get a *torpedo* boot in there to transition to 14x3 or oval to come up the wall a little, and then put a register boot.
Comment: There's four different combinations for ways this can possibly be run. They make fittings to do it all. The question is if you can get your hands in there to cut the duct back to make room for the fittings, or if you have to tear up some floor. Or you can cheat....
Answer: You want to make a closet in your master bedroom , to me that is a non load bearing wall(s). This won't be hard you just cut the bottom plate where the vent hits and move it up a foot or so. Then a wall register on each side provides the same amount of heat or possible slightly more flow because of less restriction.
I put vents in large closets to help keep air movement and reduce the chance of mold and mildew in the closet. You don't have to duct up to the vents as these are interior walls but I would seal that short stud bay at the bottom and top to keep the air directed in the bedroom closet area.
Answer: The amount of air flow to any room is based on "heat loss" or "heat gain".  You do not want the same size registers In both your bedroom and closet. One room will over heat or over cool.
If the bedroom is on a corner of the house and has windows, it will have significantly more heat loss and/or heat gain.
I live in a moist environment, so a little air movement in every room (including closets) is desired to reduce mold, etc. Be careful of placing the register too low on the wall where it could be blocked.
Comment: This doesn't answer the question can a wall be built over a register location.
Comment: @EdBeal Explaining why larger vents should be in larger rooms and smaller vents in smaller rooms certainly says "yes" and how to divide the vent up proportionally. You just said "cut the bottom plate" but the wall isn't built yet. Then you say "put a wall register on each side of the wall" without recognizing the size of each room. AND somebody down voted it too.
Comment: I also got a down vote. I did mention more flow because less restriction with common areas as master bath and closets it is quite common to split a duct like that. But the basic answer is yes then I explained how I would do it ,


How to muffle a small speaker

Question: So I have a sump pump in my basement. When the power goes out, it will beep to let you know the power is out. I plan on going out of town for a couple of weeks
My wife will not go down into the basement at all. She wants me to unplug the pump which I don't want to do
How can I muffle the speaker to where it's almost silent?
Comment: Have your wife have someone to come in that will go down.  A non working sump pump is not good.  I imagine the beep is there to let you know there is a problem that could get bad.
Comment: What's the use of a device that beeps when the power goes off? Surely in a power cut a) you'll be perfectly aware because… it's a power cut & b) you'll have some irritating beeping to tell you what you already know… which you can do nothing about until the power comes back on :\ *…or am I missing something, somewhere?*
Comment: @Tetsujin Power may not be *fully cut* to the house, but just to *the sump circuit* which should have nothing else on it. Beeping lets the homeowner know that it's running on battery power in case they can do something about it before catastrophe happens. Battery systems also beep when the battery is low on power or the lead-acid battery needs refilled with distilled water.
Comment: @FredricShope - *"Power may not be fully cut to the house"* - really? I honestly don't get how that could happen, other than a fault which could trip a breaker… but how often is that going to happen? I don't think we've had a trip here in 20 years & I caused that one;) If it has a battery that needs topping up once a blue moon [& who has batteries that need that any more?]  why not check it before going away?
Comment: Tell your wife to wear earplugs while you are away?
Comment: i tone down annoying beepers with poster putty. Usually it's not a speaker, but a piezo buzzer, which looks like a small black cylinder with a 1mm hole centered at the end. Shove a pea-size amount of putty onto the end to bury the hole. It will be about 1/16th as loud after. If it is a speaker cone, soak cotton balls in warm Vaseline and shove into a zip-lock bag which you then cram around the speaker enclosure opening (that recipe won a science Olympiad trying to muffle a speaker).
Answer: Depending on how its located and how big the pump is. An inverted bucket could muffle it a little. Otherwise try sticking bandaid or plaster on it. And simulate a power fail to test.

How to muffle a small speaker


What framework shoud I use to implement the RAISR upscaling algorithm on the GPU?

Question: I recently ran across the paper RAISR: Rapid and Accurate Image Super Resolution and thought it seemed like an interesting technique for scaling up images. However, I haven't seen any implementation of it, and I would like to see what it would be like to use it for scaling up a video in realtime, if that is possible. So I'm thinking of implementing my own version of it, but I will need to use GPU acceleration in some way if I want to at least give it a chance to run in realtime. Ultimately, I would like to see if I could successfully implemented this in an open source media player.
So, what library should I use to implement this algorithm? DirectX and CUDA are out of the question, since I want to make it run under any (major) OS and on any graphics card (well, on most of the popular ones, at least), so I'm thinking that my only options are

OpenGL (ES) + GLSL (ES), and
OpenCL.

(Vulkan also exists but I don't know whether this API is mature enough yet.)
If I choose OpenGL + GLSL, is this approach flexible enough to allow this algorithm to be implemented? Are there algorithms that cannot be implemented this way and have to be implemented in OpenCL, and if so, how do I know if my algorithm is one of them?
If I on the other hand choose OpenCL, will it be possible for other people to use my implementation without installing OpenCL on their computer?
Comment: "*If I on the other hand choose OpenCL, will it be possible for other people to use my implementation without installing OpenCL on their computer?*" That's just as true of OpenGL. The only difference being that GL typically comes with graphics drivers, while CL typically requires an explicit download.
Comment: Why was my question downvoted?
Comment: @NicolBolas That may be true. So what frameworks do media players and other video software usually use to accelerate video rendering?
Comment: "Vulkan also exists but I don't know whether this API is mature enough yet." It's mature but Apple doesn't support it, so you won't meet your goal of running on any OS.
Comment: I implemented a CUDA version of RAISR and am working on an OpenGL implemention. The hashing step isn't much of a problem -- just cache things in shared memory. You'll get garbage performance on older hardware, but on newer low-end cards, it's totally fine. The tricky part is the filter lookup, and there's quite a few methods available to deal with that problem (shared memory, some compression tricks, etc). But you'll probably get decent performance if you just store the filters in an RGBA texture.
Answer:
Are there algorithms that cannot be implemented this way and have to be implemented in OpenCL, and if so, how do I know if my algorithm is one of them?

Yes. Generally scatter-gather algorithms work poorly in OpenGL as the data locality is poor. When you have to grab bits from all over the input image for each output pixel, it's going to be slow or nearly impossible to implement in a typical GL shader. Likewise, when a calculation on an input pixel results in data that needs to be spread out to several output pixels, it's a poor fit.
It's hard to tell just from the abstract, but it looks to me like this wouldn't be a great fit for a typical OpenGL shader. I think you'll end up needing to sample an area of the input, classify it, then sample from one or more of a large set of small exemplars.
I mainly work on iOS and macOS which both come with OpenGL and OpenCL. Not sure how Windows and Linux handle that.
Comment: Thanks. So do you mean that scatter-gather algorithms work better in OpenCL than in OpenGL?
Comment: Which part of the algorithm don't you think would be well suited for an OpenGL shader? The algorithm uses interpolation by combining the pixels in a small neighborhood linearly with coefficients that it gets from a lookup table. The table key is obtained by looking at the strength, angle and spread respectively of the gradients in a local neighborhood and combining the quantizations of those values. It also calculates the local binary patterns feature.
Comment: The part you described sounds like it involves sampling in an area around the pixel currently being operated on to calculate a value to then use in a lookup table. So you your "gathering" by sampling in an area around the current pixel. Then your doing a dependent texture lookup. Both of those can be expensive depending on the hardware you're running on. If the area sampled in both the input texture and the lookup table is small enough, it might not be a bottleneck, but I suspect that's where it would happen. It seems OpenCL might be a better fit for that reason (to me).


Proof if $f$ continuous in $x_0$ then there is a neighbourhood of $x_0$ so f bounded.

Question: I have this question :
Proof if $f$ continuous in $x_0$ then there is a neighbourhood of $x_0$ so $f$ bounded.
I want to know if my proof is valid :
If continuous in $x_0$ then :
$$\lim_{x \to x_0} f(x)= f(x_0)$$
Therefore :
All $\epsilon>0$ exists $\delta>0$ so any $x$ that implies $|x-x_0|<\delta$ implies $|f(x)-f(x_0)|<\epsilon$.
Therefore for $\epsilon=1$ there is $\delta>0$ so any $x$ that implies $|x-x_0|<\delta$ implies $|f(x)-f(x_0)|<1$.
$|x-x_0|<\delta \rightarrow x_0-\delta<x<x_0+\delta$.
Lets choose $x_1,x_2$ that implies $x_0-\delta<x_1<x_2<x_0+\delta$
Therefore in $[x_1,x_2]$ from Weierstrass from theorem bounded there.
Comment: fyi, the word you want is "implies" not "appiles".
Comment: @SimonS Edited.
Answer: Rephrasing your argument:
$$|x-x_0|<\delta \implies |f(x)-f(x_0)|<\epsilon \implies -\epsilon<f(x)-f(x_0)<\epsilon \implies f(x_0)-\epsilon < f(x)<f(x_0)+\epsilon.$$
Comment: You know that $f$ is continuous at $x_0$ but you can't say that it is continuous in $[x_1,x_2].$ Thus, you can't apply Weiertrass.
Comment: Oh, I understand your proof is much easier, I wonder if the way I proofed it correct?, because I had an exam today, and that's how I wrote it.


Text parsing with VB in Word

Question: Using word 2007, I need to parse text in a document.
The text is in the form:
<number>. <question_text>
a. <answer1_text>
b. <answer2_text>
c. <answer3_text>
d. <answer4_text>
e. <answer5_text>
Answer: <correct_letter>. <feedback_text>

It needs to be outputted in this form:
<number>) <question_text>
~Y. <feedback_text>
a. <answer1_text>
b. <answer2_text>
*c. <answer3_text>
d. <answer4_text>
e. <answer5_text>

The answer who's letter is the correct_letter needs to have a * in front of it.
There are multiple questions in a given document. Any help towards a VB solution will be appreciated. I figure the solution involves looping through each line in the document, looking for each variable, and once all variables are found, output them in the correct formatting.
Answer: It sounds like using Word as your database...which is not my skillset.
But I know Word works with XML now -- if you converted it to XML, it would then at least be queryable...  From there you could use XSL Transformations.

Text parsing with VB in Word


Hide view while push to tabBar - swift

Question: I have a view controller like below.

This view is attached with a tabBarController. The tabBarController has 5 viewControllers and I have to present the 5th viewController of tabBar from another page. So I used the below codes for present that viewController
@IBAction func onClickUserProfile(_ sender: Any) {
        let navVc = self.storyboard?.instantiateViewController(withIdentifier: "ProfileVC")as! ProfileVC
        navVc.userId = Int(self.userId)
        navVc.navigationItem.hidesBackButton = true
        navVc.tabBarController?.tabBar.isHidden = false
        self.navigationController?.pushViewController(nxtVc, animated: true)
    }

But after execute the code it resulting the view controller as the below image.
The view undergoes the tabBar. Anyone help me to push to a tabBar view.
Comment: try to set automaticallyAdjustsScrollViewInsets = false, in ProfileVC(viewDidLoad)
Comment: Nothing happens.The view return the same result
Comment: Why don't you use the present function to present your view controller?
Comment: While using present it hides the tabBar and navigationBar
Comment: What is the bottom constraint of the "Sell Your Staff" button ?
Comment: You can use your tabBar to access the 5th VC and switch your VC that way, it should be better than create new instance to push, the issue should because the constraint that connect to the button
Comment: @Ahmet set the bottom constraint to super view
Comment: @Tj3n How to access the tabBar and switch to 5th VC can you please explain it with code
Comment: @AngelFSyrus check the answer .
Answer: You need to set the selected UIViewController from UITabBarController  something like this should work .
self.tabBarController?.selectedViewController = self.tabBarController?.viewControllers![1]

where tabBarController?.viewControllers returns the array of current ViewControllers embedded in the UITabBarController .
Your code should be something like this.
@IBAction func onClickUserProfile(_ sender: Any) {
        let vc =  self.tabBarController?.viewControllers![1] as! ProfileVC // use your index
        vc.userId = Int(self.userId)
        self.tabBarController?.selectedViewController = vc
    }

Note: Don't create an instance of the UIViewController as .instantiateViewController(withIdentifier:) use the already existed
  ones in the array tabBarController?.viewControllers, creating new
  instance will be treated as new one and gives the problem you have up
  there .

Hide view while push to tabBar - swift


Zooming also count as window resize?

Question: $(window).resize(function(){
            console.log('resize');
            setheight();
        });

I just want to activate when user actually resize the window by draging the edge of the window but not zooming, but it actually activate the function while zoom in and zoom out, how to prevent that??
Answer: The resize event is sent to the window element when the size of the browser window changes.However when we zoom in/out the size of the browser changes so the resize event is fired.
Comment: so what should I do? any event listener thats won't fire on zoom but only window resize?
Comment: @FatDogMark - Set a variable that captures the width of the window on load. On the resize event - check that the window width still matches the value captured on load. If false, then trigger whatever is supposed to happen at resize.
Answer: You could just use the resize event to check for changes in window size like this...

$(document).ready(function () {
    var width = $(window).width();

    function resizeIt() {
        $(window).resize(function () {
            if ($(window).width() != width) {

              alert('resize events');

            }
        });
    }

  resizeIt();
}
Comment: the correct way is not to use $(window).width() but window.outerWidth, since zooming will change window.innerWidth (and jquery.width() is actually based on window.innerWidth)
Comment: actually this won't work bc zooming also change window.innerWidth.
Answer: As mentioned by @Mizok.H the correct way to detect resize is NOT by using window.innerWidth as it also gets changed while zooming.
The correct way is to use window.outerWidth since it stays unaffected while zooming.
Use the code below:
var root = document.documentElement;

screen_size();

window.addEventListener('resize', screen_size);

function screen_size()
{
  root.style.setProperty('--screen-x', window.outerWidth);
  root.style.setProperty('--screen-y', window.outerHeight);
}

you can finally use defined variables in your CSS like:
width:  calc(1px * var(--screen-x));
height: calc(1px * var(--screen-y));

Zooming also count as window resize?


How to convert IplImage to lept.PIX

Question: I develop OCR system based on JavaCV.
I use following libraries for my project:

https://github.com/bytedeco/javacv
https://github.com/bytedeco/javacpp-presets/tree/master/tesseract

In one case I need to find some part of an image and recognize letters on it.
I store a part of an image in IplImage type.
But for Tesseract I must use PIX format.
How can I convert IplImage to Pix ?
Comment: http://stackoverflow.com/a/8126992/2836621
Comment: Is there a design issue that prevents you from reading the image directly as PIX ?
Comment: @goodbytes, the author of the question has found a hack. https://github.com/bytedeco/javacpp-presets/issues/224
Answer: Posting the hack like solution found by the author of the question. It can also be found here.
IplImage prepareImg = ...
cvSaveImage("plate.jpg", prepareImg);
PIX pixImage = pixRead("/plate.jpg");

And from this question, you can convert IplImage to BufferedImage as follows.
public static BufferedImage toBufferedImage(IplImage src) {
  OpenCVFrameConverter.ToIplImage iplConverter = new OpenCVFrameConverter.ToIplImage();
  Java2DFrameConverter bimConverter = new Java2DFrameConverter();
  Frame frame = iplConverter.convert(src);
  BufferedImage img = bimConverter. convert(frame);
  BufferedImage result = (BufferedImage)img.getScaledInstance(
      img.getWidth(), img.getHeight(), java.awt.Image.SCALE_DEFAULT);
  img.flush();
  return result;
}

Answer: IplImage prepareImg = ...
cvSaveImage("test.jpg", prepareImg);
PIX pixImage = pixRead("/test.jpg");

--- Source : Same Github issues
As mentioned by a comment by rajind ruparathna

How to convert IplImage to lept.PIX


When I start my instance with encrypted volumes attached, the instance immediately stops with the error "client error on launch"

Question: When I was start EC2 instance with encrypted volumes attached from lambda function which was invoked from cloudwatch event, the instance immediately stops with the error "client error on launch". Can anyone help me in this.?
It's related with AWS KMS permission.
Answer: It is related to the permissions.
Please check if user/role has required permissions for KMS or if there is any specific restriction applied for KMS key usage.
I have found a great post regarding this: Instance with encrypted volumes attached stops immediately when started


Access Denied When Enumerating Through Process Modules C++

Question: I am trying to enumerate through a process's modules to get the memory address range it operates in. This function works with other processes fine. However, on the particular process which I had intended to analyze I get error code 5, ERROR_ACCESS_DENIED. Note that at position 1 I get error code 0 and at position 2 I get error code 5. I understand that some kernel objects can be protected which could explain this error code. Is this the reason? If so, is it possible to work around that?
<code>int PrintModules(DWORD processID)
{

HMODULE hMods[1024];
HANDLE hProcess;
DWORD cbNeeded;
unsigned int i;

// Print the process identifier.

printf("\nProcess ID: %u\n", processID);

// Get a handle to the process.

hProcess = OpenProcess(PROCESS_ALL_ACCESS,
    FALSE, processID);
std::cout << "POSITION 1 : " << GetLastError() << std::endl;
if (NULL == hProcess)
{
    return 1;
}
// Get a list of all the modules in this process.

if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
{
    for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
    {
        TCHAR szModName[MAX_PATH];

        // Get the full path to the module's file.

        if (GetModuleFileNameEx(hProcess, hMods[i], szModName,
            sizeof(szModName) / sizeof(TCHAR)))
        {
            // Print the module name and handle value.

            _tprintf(TEXT("\t%s (0x%08X)\n"), szModName, hMods[i]);
        }
    }
}
else {
    std::cout << "POSITION 2 : " <<GetLastError() << std::endl;
}

// Release the handle to the process.

CloseHandle(hProcess);

return 0;
}
</code>
Comment: Is it no option to run your application under local administrative rights or set the right privileges for your process (`AdjustTokenPrivileges()`)?
Comment: I have tried to run the application as administrator and had the same issues.
Comment: Please use ProcessExplorer or an equivalent tool to check the security information of your process. Some like anti virus programs or system processes do not allow a read for other processes.
Comment: Process Explorer shows that the process is not protected and the system has read/write permissions. I have already adjusted token privileges.
Comment: PROCESS_ALL_ACCESS is a big demand, that allows you to mess with a process in any imaginable way.  When you enumerate *all* running processes then you almost always encounter one that you don't have sufficient access rights for to do that.  You'll have to skip it.  Do consider lowering your demand, seems you don't need more than PROCESS_QUERY_INFORMATION.
Comment: @HansPassant - `PROCESS_QUERY_INFORMATION` not enough. need also `PROCESS_VM_READ` because this api read from target process virtual memory
Comment: and if you say true, that error in call `EnumProcessModules` - task not in any privileges or process access at all - you already open process with all access. however I very doubt that `EnumProcessModules` can return error access denied on process handle opened with all access
Answer: ERROR_ACCESS_DENIED means your handle is invalid.  You're getting and invalid handle when you call OpenProcess for one of two reasons.
Either your process id is wrong or you're not running as administrator.  You need to run as administrator for PROCESS_ALL_ACCESS permissions.


polymorphic association for element, anything else needs to be added?

Question: I have adopted and I'm not sure exactly why something isn't working.
I have a pricable polymorphic association which I use for only a single model called Item. It looks like this:
class Item < ActiveRecord::Base
  #price
  has_one :price, :as => :pricable
  accepts_nested_attributes_for :price

  attr_accessible :price_attributes, :price, ....

I'd like to add to an Event model and have added the following:
class Event < ActiveRecord::Base
  #price
  has_one :price, :as => :pricable
  accepts_nested_attributes_for :price
  attr_accessible :price, :price_attributes

However, I am not able to set it:
ruby-1.9.2-p290 :001 > e=Event.find(19) #ok
ruby-1.9.2-p290 :002 > e.price
Creating scope :page. Overwriting existing method Price.page.
  Price Load (0.8ms)  SELECT `prices`.* FROM `prices` WHERE `prices`.`pricable_id` = 19 AND `prices`.`pricable_type` = 'Event' LIMIT 1
 => nil
ruby-1.9.2-p290 :003 > e.price.price=23
NoMethodError: undefined method `price=' for nil:NilClass
    from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.0/lib/active_support/whiny_nil.rb:48:in `method_missing'
    from (irb):3

Hmmm.... it looks like the relationship is set up correctly and that Event has access to price via attr_accessible. Any idea what else could be going on?
thx
Answer: Relationship appears to be defined correctly, however if e.price returns nil then obviously e.price.price= won't work and return undefined method error. You need to build/create an associated price object first:
> e = Event.find(19)
=> #<Event id: 19, ...>
> e.price
=> nil
> e.create_price(price: 23)
=> #<Price id: 1, priceable_id: 19, price: 23, ...>

or if you would like to use nested attributes:
> e = Event.find(19)
=> #<Event id: 19, ...>
> e.price
=> nil
> e.update_attributes(price_attributes: { price: 23 })
=> true
> e.price
=> #<Price id: 1, priceable_id: 19, price: 23, ...>

Comment: cool, is build_price an alias for create_price? I was able to get working like 5 min after bounty. lol ...
Comment: build_price is not alias for create_price. The difference between them is that build_price only builds associated price object and does not save it to database while create_price builds price object and immediately saves it. Check [has_one](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one) documentation for details about build_association and create_association methods.
Answer: This is how your models should look like
class Price < ActiveRecord::Base
  attr_accessible :value
  belongs_to :priceable, :polymorphic => true
end

class Item < ActiveRecord::Base
   attr_accessible :name, :price_attributes
   has_one :price, :as => :priceable
   accepts_nested_attributes_for :price
end

class Event < ActiveRecord::Base
  attr_accessible :name, :price_attributes
  has_one :price, :as => :priceable
  accepts_nested_attributes_for :price
end

This is how your price migration should look like
class CreatePictures < ActiveRecord::Migration
  def change
    create_table :pictures do |t|
      t.string  :name
      t.integer :imageable_id
      t.string  :imageable_type
      t.timestamps
    end
  end
end

And then you can easly do something like this
Item.new( { name: 'John', price_attributes: { value: 80 } } )


cron.daily seems to run but doesn't log any activity

Question: We have a number of scripts setup to run in the /etc/cron.daily directory - some of them show evidence of being run at about the right time (files are archived/compressed and truncated), but others seem to be ignored.
Checking both /var/log/cron.log and /var/log/syslog lists none of the daily jobs - only the hourly (and a couple of 20 minute jobs).
Is there some other log somewhere? The crontab contains these lines:
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 4    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

Comment: Try to remove all dots in the script names
Answer: What are the 20-minute jobs?  It looks like you pasted /etc/crontab, and it has no 20-minute entries.
What is the contents of /var/log/cron.log?
Do the permissions on /etc/cron.daily look right?  (e.g. should be at least r-x root)
Do the scripts inside /etc/cron.daily have execute permissions?
What does
run-parts --test --report /etc/cron.daily

print?
What happens if you add a new script in that directory that does something trivial that you can verify, e.g.
date >> /tmp/date.out

What does /etc/syslog.conf contain?  It should be something like:
cron.*                          -/var/log/cron.log

If it's cron.notice or cron.warn or cron.err rather than cron.*, then not all activity will be logged to /var/log/cron.log.
Answer: If a cronjob has output or fails, cron will mail the user about it if the bsd-mailx package installed. Read such mails with the mail command.
Comment: You can install any mail server you like, not just bsd-mailx.  I am pretty sure that you can also edit a config file somewhere to use another mail server, but having one locally means mail won't be lost should the other server be down or unreachable temporarily.


convergence $ \sum_{n=1}^{\infty} 2^n \cdot \left(\frac{n}{n+1}\right)^{n^2} $

Question: How can I check convergence of  $ \sum_{n=1}^{\infty} 2^n \cdot \left(\frac{n}{n+1}\right)^{n^2} $ ?
If I want check necessary condition $u_n \rightarrow 0$ I need to do sth like that:
$$ u_n = 2^n \cdot \left(\frac{n}{n+1}\right)^{n^2} = 2^n \cdot \left(\left(\frac{1}{1+\frac{1}{n}}\right)^{n}\right)^2 $$ but now I can't write just
$$ \left(\left(\frac{1}{1+\frac{1}{n}}\right)^{n}\right)^2 \rightarrow \frac{1}{e^2}$$ because I have $ 2^n $ part...
Thanks for your time.
Comment: Hmmm... $$\left(\frac{n}{n+1}\right)^{n^2} \ne \left(\left(\frac{1}{1+\frac{1}{n}}\right)^{n}\right)^2=\left(\frac{n}{n+1}\right)^{2n} $$
Comment: Ahh.. My fail, your right, thanks
Answer: Using Root test,
$$\lim_{n\to\infty}\sqrt[n]{u_n}=\dfrac2{\lim_{n\to\infty}\left(1+\dfrac1n\right)^n}=\dfrac2e<1$$
Comment: It is great idea! $\frac{1}{e} \in \left(\frac{1}{2};\frac{1}{3} \right) $ so it is clearly under $1$. But how can I solve necessary condition? I can't use there root test


ro root fs on /proc/mounts

Question: my ubuntu 9.10 is mounting the root filesystem as read only.
 already tried some options found on the forums like fsck, remounts, etc, but no luck...
for what I could find, my problem is is /proc/mounts:
root@WKS00335:~# cat /proc/mounts
 rootfs / rootfs rw 0 0
 none /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
 none /proc proc rw,nosuid,nodev,noexec,relatime 0 0
 udev /dev tmpfs rw,relatime,mode=755 0 0
 /dev/mapper/WKS00355-root / ro,relatime,barrier=1,data=ordered 0 0
 none /sys/kernel/security securityfs rw,relatime 0 0

my root is defined as ro
for etc/fstab, I've got:
root@WKS00335:~# cat /etc/fstab
 # /etc/fstab: static....
 #comments#
 #<file system>...
 proc /proc proc defaults 0 0
 /dev/mapper/WKS00355-root / ext4 errors=remount-ro 0 1
 #boot was on /dev/sda5 during installation
 UUID=9254b90c-c665-4dc1-8e1a-7b2e6a493ca4 /boot ext2 defaults 0 2
 /dev/mapper/WKS00355-swap_1 none swap sw 0 0
 /dev/sdc0 /media/cdrom0 udf,iso9660 user,noauto,exec,utf8 0 0
 /dev/fd0 /media/floppy0 auto rw,user,noauto,exec,utf8 0 0

the question is, how can I change /proc/mounts so that /dev/mapper/WKS00355-root / is rw instead of ro?
Answer: sudo grep -ir WKS00355-root /var/log/ ; dmesg | grep WKS00355-root
It would certainly appear that SOME kind of error is causing your root partition to go read-only, so you'll need to look through the logfiles to try to figure out why.  The above command should return something relevant.
If it doesn't, the error in question might be in a logfile that's already been compressed and archived.  Easiest thing to do, if uptime isn't an issue, is just to reboot and then immediately issue the command above if root is still read-only.
What happens if you issue the command sudo mount -o remount,rw / ?

ro root fs on /proc/mounts


While uploading the img file src in img tag not working (src url not changing)

Question:

input type='file' name="modelvariant_file" id="imageUpload" accept=".png, .jpg, .jpeg" >
<img id="imagePreview"    src="<?php echo url('/') ?>/public/assets/images/upload-profile.png">

when I upload the image. i can able to select image but image is  not showing after uploading . same time img tag src attribute remains same not changing.is this information enough ? or need more
Answer: I think you need to ignore the closing tag at ' at the url('/') try using src="<?php echo url(\'/\') ?>/public/assets/images/upload-profile.png" which will ignore the closing tag


MALWARE on my Ubuntu 16.04.01 lts

Question: I have malware which puts advertising in all my browsers.
Originally I installed Windows 10 and shortly thereafter, my computer was infected.
I erased the hard drive and installed Ubuntu 16.04.1 LTS. However, ads still appear in the Firefox browser plus the native Ubuntu web browser. A screenshot to show examples of the ads.
The left side of the picture is an normal browser without infection and the right side is the infected browser. When i see the same page in my other computer looks like the left-side image.

PS: Any thoughts on what kind of virus or malware this is?  In the other PC's Firefox browser (Firefox), on the same wifi with the same ISP, infection has not yet appeared.
Comment: Please, dont vote negative if you dont give a usefull answer or an explanation. Do another thing, and dont bother people who really needs help. Thank you so much!
Comment: Do you sync your history and other bookmarks with other firefox browsers that you use on other systems?
Comment: Thanks george for response!, i made a clean installation without import bookmarks, or plugins or extensions. :)
Comment: The browser on the left has some add-ons. What add-ons are installed and are they also installed in the browser on the right?
Comment: I really ask you to check your router. Try to reflash it. I had similar issues some years ago (long before iot worms have became mainstream), I checked pcs, they were clear. Then I reflashed my router with firmware from vendor website and infection have gone. The easiest way to check if the ads are because of tampering with connection is to open any https website and check if it has the ads you think made by malware.
Comment: Do you have problems when running the live-media (without persistence) in the "try" mode?
Comment: This whole question is hysteria and false premises.  The advertising in question is in the LaVoz page itself (using Javascript and s) and is served up by a WWW advertising company called SmartAdServer.  SmartAdServer allows advertisers to target adverts by operating system and WWW browser.  This "MALWARE" hooplah and all of this fumbling around with routers, plug-ins, anti-virus softwares, and even reinstalling operating systems is just nonsense.  Targetted advertising, people.  The advertisers know what your WWW browser and operating system are.
Comment: AlexP I disable all the add ons and still appearing! And in other browser(in other computer) with all defaults addons dont showup this advertising.
KOLANICH I will try your solution today and tomorrow tell you what happend
UBFAN1 When im using ubuntu in a USB LIVE shows the same ads!
JDeBP IM using diferent computers and one show up this advertising and the other no, my cellphone dont show this ADV so, i think what is my computer only :(

Thanks to all for help me! Really :)
Comment: I THINK! What the virus or ADV soft, maybe could stay in the MBR or HDD Firmware! SO im gonna try to make a LOW - LEVEL FORMAT of my hard drive and TELL YOU what happend! IF any has more ideas, im really grateful to hear they! THANKS to all :D
Comment: K7AAY THANKS FOR THE HELP WITH MY ENGLISH!
Answer: I would use an AntiVirus vendor solution to examine the PC.
Avira has one available for non-commercial use. You install it on a USB device and then boot to it (which may require adjusting BIOS settings)
Link: https://www.avira.com/en/download/product/avira-rescue-system
To your question, this will (hopefully) identify the malware if indeed it exists. Of course, no solution is absolute.
Comment: Thank you MARK, i wil try it right now and later told you whats happend!, i dont kow it what avira has this type of online solutions.
Comment: Don't found nothing with avira. Thanks MARK! :D i will follow your path with online or usb antivirus!
Comment: Sophos offers a free antivirus for home use that works very well with ubuntu (16.04 & 16.10 at least) https://www.sophos.com/en-us/products/free-tools/sophos-antivirus-for-linux.aspx - Good luck.
Answer: Since the problem is adverts showing up indiscriminately it would suggests that you may have inadvertently installed an add-on from a site you visited.
Now that being said if you have sync enabled between browsers then when ever you install it syncs and re-install the problem.
Do a total disabling of all third party plugins and see if it solves the issue. If it remains then disable all plugins in your browser then check again.
Less I forget if sync is enabled disable it.
Please post results and good luck.
Comment: Thank you GEORGE! i disable all things and still appearing!.
Comment: do you have `clamav` ? if you do run a full system scan
Comment: I will try it CLAMAV tonight and tomorrow tell you, thanks George!
Comment: use this command `sudo clamscan -r --infected --bell  / ` when you do so it lists infected files, then when your sure no `system files` gave a `false positive` you can now do `sudo clamscan -r --remove /` to remove them. Best of luck
Comment: Where you able to resolve the issue ?
Answer: For everybody who HAS a problem like me, i dont found a solution. The only solution is a low level format and reinstal everything!. Meanwhile i have a usefull and wonderfull browser named BRAVE. This browser blocks every advertising from the malware who try to put in my webpages so, its a "temporal" solution. The malware and me, meanwhile still living togheter, in company until im format my hard disk. But thanks to this browser, them cant take money from ads, so, i recommend it to all who is tired to se advertising everywhere. THANK YOU SO MUCH, to the community for help me and support me. My greetings to all!!

MALWARE on my Ubuntu 16.04.01 lts


$f: V \rightarrow W$ linear transformation onto. There is a $g:W \rightarrow V$ linear transformation such that $f \circ g$ is identity.

Question: Problem. Let $V$ and $W$ vector space with finite dimension such that $f: V \rightarrow W$ linear transformation onto. There is a $g:W \rightarrow V$ linear transformation such that $f \circ g$ is identity.
We have, $f: V \rightarrow f[V]$ becuase $f$ is onto ($f(V)=W$). Then if we take $g:f(V) \rightarrow V$ such that $g(w)=f^{-1}(w)$. Then $f \circ g(v)= f \circ f^{-1}(v)=v$. Am I right?
Comment: What do you mean by $f^{-1}(w)$?
Comment: @PSW Given $w \in W$, it is possible to exists at least two distinct $v_1$ and $v_2$ in $V$ such that $f(v_1)=w$ and $f(v_2)=w$. So, which one is $f^{-1}(w)$?
Comment: *Hint*: Use bases for $V$ and $W$.
Comment: We have $f$is onto, then for all $w \in W$ exists $v \in V$ such that $f(v)=w$. So, $v=f^{-1}(w)$
Comment: so, $f^{-1}(w)= \sum_{i=1}^{n}(\alpha_{i}v_{i})$?
Comment: @PSW I don't understand what that means. The symbol $f^{-1}(w)$ just does not have a well-defined meaning here. It has one when $f$ is also injective.
Comment: So, if I use bases for $V$ and $W$ we prove $f$ is injective right?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/138644/discussion-between-psw-and-azif00).
Comment: $f$ doesn't necessarily have to be injective. From rank-nullity you can prove that a linear map from a larger dimensional vector space to a smaller dimensional vector space can't be injective. But on the other hand, a linear map from a larger dimensional vector space to a smaller dimensional vector space can be surjective. Consider the map $T : R^2 \to R$ defined by $T(x, y)=x$. This is a surjective linear map, but it is not an injective linear map as $T(1, 2)=T(1, 3)$
Comment: I understand that $f$ is not necessarily injective. But, in your example. We can take $g: \mathbb{R} \rightarrow \mathbb{R}^2$ defined by $g(x)=(x,x)$ we have $T \circ g(x)=T(x,x)=x$ so $T \circ g $ is identity. Now, how can we generalize that idea.
Comment: Absolutely you can. Have a look at the answer below.
Answer: Hint, to rigorize the idea you have: Let $W$ have basis $w_1,\dots,w_m$, and pick $v_1,\dots,v_m\in V$ such that $f(v_i)=w_i$. Then the $\{v_i\}$ are linearly independent since any linear relation $\sum a_iv_i=0$ implies $\sum a_iw_i=0$, which contradicts the $\{w_i\}$ being linearly independent. Now, define $g\colon W\to V$ by $g(w_i):=v_i$. Check this is well-defined and satisfies the necessary conditions.
Comment: What is the need to say that the $v_i$ are linearly independent?
Comment: Right, that's unnecessary. The $v_i$'s being linearly independent shows $g$ is injective.


When dividing by a fraction, why can you not take the reciprocal of term involving addition/subtraction?

Question: Given something like:
$$\frac{a}{\frac{a}{b}}$$
You would multiply the numerator $a$ by the reciprocal of the denominator, $\tfrac ba$  to get:
$$
a\cdot\frac{b}{a}= \frac{ab}{a}=b
$$
Given
$$
\frac{1}{\frac 1a + \frac 1b}
$$
By taking the LCM and adding the denominators you get:
$$
\frac{1}{\left(\frac{a+b}{ab}\right)}
$$
Given the reciprocal division rule in example one:
$$
\frac{ab}{a+b}
$$
Why can you not take the reciprocal of $\frac 1a + \frac 1b$ to begin with? I did this and ended up with:
$$
1\cdot\left(\frac a1 + \frac b1\right)
=a + b
$$
However $\frac{1}{1/a + 1/b}$ is not the same as $a+b$ so this is incorrect. I was trying to find a similar example online but I could not, why is this incorrect? Does the rule only work with one fraction as the denominator and not terms linked by addition and/or subtraction?
Comment: This is *exactly* the reason you should be using [Mathjax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)!
Comment: Thanks, I am working on the rest!
Comment: Sorry! I am reading the page now!
Comment: Cool!  I did the first edit for you ...
Comment: Your edit made the result of the first multiplication $a$ instead of $b$.
Comment: Welp! Thanks Ross, I'm struggling over here...
Comment: @Sphygmomanometer Very nice typesetting! :)
Answer: The reciprocal of $\frac{1}{a} + \frac{1}{b}$, is by definition
$$
\frac{1}{\frac{1}{a} + \frac{1}{b}} = \frac{1}{\frac{a+b}{ab}} = \frac{ab}{a+b}.
$$
So your reasoning fails because $\frac{a}{1} + \frac{b}{1}$ is not the reciprocal of $\frac{1}{a} + \frac{1}{b}$.
Answer: When you took the reciprocal of $\frac 1a+\frac 1b$ to get $a+b$, you implicitly assumed that the reciprocal of a sum is the sum of the reciprocals. This is not true.
Note that $\frac 1a$ is $a^{-1}$. Just as the square of a sum is not the sum of the squares (in general), that is, $(x+y)^2\neq x^2+y^2$, so also the reciprocal of a sum is not in general the sum of the reciprocals: $(x+y)^{-1}\neq x^{-1}+y^{-1}$.
Comment: Nope, not me. My name is pretty common.


JQuery UI Dialog & Asp (web forms) calling event handler

Question: I have a form with a submit button. On clicking the submit button, i display a jqueryUI dialog with Confirm and Cancel. On clicking Confirm, I want to post back and call the submit button's event handler not the Page_Load event.
I have the following
HTML
<input type="submit" value="Submit" id="submit" runat="server"  onclick="submit" />

JQuery
$("#dialog").dialog('option', 'buttons', {
                "Confirm": function () {
                    $("#ctl01").submit();
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            });

so far, this will call the page_load event because i am 'just' submitting the whole form.
Server side
protected void Page_Load(object sender, EventArgs e)
    {
        if(Page.IsPostBack)
            result.Text += "hey post-back, we did it!";
    }

    protected void submit(object sender, EventArgs e)
    {
        result.Text += "hey, event handler! ";
    }

Comment: I'm not seeing a question here? Does it not work? What do you want it to do?
Comment: i want it to run the submit(object sender, EventArgs e) event handler, instead of the Page_Load
Answer: From your post I got that you want to simple go to the server side event while clicking on the  button in the Dialog.
So I created a Hidden ASP Server Button and triggering it's click from the Confirm button.
Here is the working code.

    <title></title>
    <link href="CSS/ui-lightness/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />

    <form id="form1" runat="server">

            These items will be permanently deleted and cannot be recovered. Are you sure?

    <input type="button" value="Submit" id="submit" />
    <asp:Button runat="server" Style="display: none" ID="btnNew" Text="Submit" OnClick="btnNew_Click" />
    </form>

In _Default.asp.cs
public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            result.Text += "hey, event handler! ";
        }

    }

Comment: Looks like a clumsy implementation IMHO - don't see the need for duplicate hidden buttons. Makes the HTML confusing.
Comment: i added e.preventDefault(); just before calling the hidden button's click. @SpaceBison the first click will be cancelled by jQuery, and instead of posting back, it will display the dialog. On the Confirmation, we simulate the click event so that the postback will run the button's event handler. (if we use $('#form').submit(), the code will only run the Page_load not the button's click event
Answer: I think onclick is a client-side handler
Have you tried OnServerClick, since it's a HTML Button?
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlbutton.onserverclick%28v=VS.100%29.aspx


Mongodb aggregate use field reference

Question: Data:
{
   "_id": "test1",
   "orderStatus": "shipped",
   "history": {
      "pending": {startAt: '2021/03/16'},
      "shipped": {startAt: '2021/03/18'},
   }
}

Is it possible to access sub document by another field?
I'd like to get current order status startAt in an aggregation pipeline, for example:
db.aggregate([{$addFields: { currentStartAt: "history.$orderStatus" }}])

but it doesn't work.
Comment: Use `currentStartAt: "$history.orderStatus"` and you should **never** store date/time values as string, it's a design flaw. Use proper `Date` objects.
Comment: Your solution doesn't work, "$history.orderStatus" not exist
Answer: This also works but I have no idea about performance, let me know how it performs.
db.collection.aggregate([
{
    "$addFields": {
    "currentStartAt": {
        "$arrayElemAt": [
        {
            "$map": {
            "input": {
                "$filter": {
                "input": {
                    "$objectToArray": "$history"
                },
                "as": "el",
                "cond": {
                    "$eq": [
                    "$orderStatus",
                    "$$el.k"
                    ]
                }
                }
            },
            "in": "$$this.v.startAt"
            }
        },
        0
        ]
    }
    }
},
{
    "$project": {
    "currentStartAt": 1
    }
}
])

Another query doing same thing
db.collection.aggregate([
    {
        "$addFields": {
        "currentStartAt": {
            "$filter": {
            "input": {
                "$objectToArray": "$history"
            },
            "cond": {
                "$eq": [
                "$orderStatus",
                "$$this.k"
                ]
            }
            }
        }
        }
    },
    {
        "$project": {
        "currentStartAt": {
            "$first": "$currentStartAt.v.startAt"
        }
        }
    }
])

Answer: Try this one:
db.collection.aggregate([
   { $set: { history: { $objectToArray: "$history" } } },
   { $set: { history: { $filter: { input: "$history", cond: { $eq: ["$orderStatus", "$$this.k"] } } } } },
   { $project: { currentStartAt: { $first: "$history.v.startAt" } } }
])

Within a mongo shell you can also do this one:
var field = db.collection.findOne({}, { orderStatus: 1 }).orderStatus;
var field = "$history." + field + ".startAt";
db.collection.aggregate([
   { $project: { currentStartAt: field } }
])

Comment: This query is working, but with too much performance cost in a huge collection. I'd like to access directly the field by a dynamic reference based on another field. If no one is going to give a better answer I'm going to accept this

Mongodb aggregate use field reference


Design consistency issues when allowing the user to change design

Question: What's the best way to solve user design consistency problems inside an application that gives total control over the appearance?
For example, user can choose font of element X, then later adds element Y but doesn't remember what font he used on X or he is lazy to check it out, so he chooses a different font. Can I present the font selector in a way that it makes the user choose the right font?
Comment: Can you provide some screenshots or a little more detail to help describe this situation?
Answer: I don't understand why the user would be able to set a font specific to either X or Y - Surely you could place font control as a global variable: set the font once for all elements. - That way the user can only make a consistent choice.
I find, when dealing with user customisation, it's best to stick to limited choices and mostly at a large scale: system wide choices for font, colour scheme, etc. That way, your site won't end up looking like GeoCities.
Answer: It sounds like a bit of contradiction to me, but if you give total control over the appearance to the user then how can you also then restrict them to make consistent choices?
I think one common strategy is to give users a 'theme', such as what windows and other operation systems do, that applies a set of styles to the user interface, then allow users to customize specific elements but not all of it.
The other thing is to provide all the user interface components to the user, and allow them to customize individual elements within that component, such as what many bootstrap theme modifier tools allow you to do.
I am sure you'll find something between the two that will work for your users. Perhaps also having some analytics on what users are choosing to customize will let you figure out what you can keep control over versus what you let the users customize.
Answer: You should take a look to most CMS that include this kind of feature. What they usually do is to offer pre-defined layout sets with fonts, colors and some choice of structure (columns, full width vs boxed and such). Personally, I also offer a way to modify things further with extra HTML and CSS coding. Since this will only be used by advanced users, they can easily fine tune at will.
Leaving this decision to users is a big problem. Going back to the CMS samples, we get this claim almost every single day "I used a theme but can't make it look like the demo" or "I need to hire a designer to make the theme look as I want". Doh. The more choices you add, the less likely a regular user will be to make something that looks right. A designer has training, is a professional, knows the theory and the trends. Most users think their personal taste is amazing and unrivaled. Yet, they can't tell exactly why their site looks so bad. And the answer always end in... your coding. Simple as that.
So, this is what WE do:

if this is for a final user, we research and eventually train the user with a more customized CMS. HOWEVER, we always set some strict boundaries so the user can't go crazy. we simply don't let him break the site.
if this is for a broad user base, boundaries get even stricter and most layouts are pre-defined, even color palettes and combinations, at most we leave some font choices, where they can choose between 5 to 10 font families for headers and the same for text. We're the professionals, so we have to deliver a professional product, even if it looks as "limited".

Think about this: People don't like to assembly their furniture, they do it because it's cheaper, but 100 out of 100 times they would take a professionally built piece of furniture over some "build it yourself" crap. Giving some engines and metal won't make a regular guy a car engineer. So... why do it with sites? Sites may give an income many times the price of an Ikea chair, so why would anyone want to go this way? (Of course, unless you're selling themes on Envato or the likes, then you tell users "you can do anything because we offer 1,000,000 options!" )
In short
If you want consistency, start by restricting options and make the whole thing consistent within your own rules, do not leave any room for randomness
EDIT: while more oriented to mobile, you might find some useful concepts in "Using Back-End Design to Create Customizable Front-End Mobile Experiences"
Answer: While providing font customizations may seem like an eye candy feature, you might want to pose a limitation on the number of choices. It becomes difficult for people other than designers to make font choices if they are given more choices to decide from. Choose in such a way that the fonts are from different families to help making the decision easier. Ideal number of choices could be four or five, one of which the user would settle down to.
Answer: Just provide a "Recently used" section for each type of design choice. For example when changing the font have a recently used font like provided in MS word:

For colors, use recently used color:

etc.
If you want you can add under it a label saying where it is used but unless the user is using way too many fonts or colors they should be able to determine from their small recently used list which one goes where ("Ohh the Arial Bold is what I used on my headers").


How to make snap Firefox use locally installed fonts?

Question: I need to use an intranet app which relies on locally installed fonts for its look, but snap version of Firefox by default doesn't look into user's ~/.fonts. Is there a workaround for that? If not, are there plans to address this specific use case?
Comment: For an authoritative answer, you would need to ask Mozilla (whom we are not); they make the Firefox snap.
Comment: For the terminal in JupyterLab I was able to put fonts into `.local/share/fonts`
Answer: There is currently a bug that prevents Firefox from correctly using locally installed fonts. See: https://bugzilla.mozilla.org/show_bug.cgi?id=1760996
I have set up a workaround on my computer using symlinks:

~/snap/firefox/current/.local/share/fonts → ~/.local/share/fonts
~/snap/firefox/current/.config/fontconfig → ~/.config/fontconfig

First you create the symbolic links.
After that, you run
fc-cache -f -r

to force Firefox to use the refreshed font cache.
Finally, restart Firefox to make the change take effect.

Example
I have installed the Apple's SF Pro fonts on my computer. Here is what I got after I have set up these symlinks, opened up https://fetch.spec.whatwg.org/, and changed the global font family (as defined in  of that page) to SF Pro Text:
Answer: Don't think there is such a plan. But how about putting the fonts in /usr/local/share/fonts instead?


What's the maximum value of $\frac{2}{a^2+1}-\frac{2}{b^2+1}+\frac{3}{c^2+1}$ given that: $abc+a+c=b$

Question:
Given that: $abc+a+c=b$. What's the maximum value of $$\frac{2}{a^2+1}-\frac{2}{b^2+1}+\frac{3}{c^2+1}.$$

(DO NOT use trigonometric methods)
Comment: is given that $$a>0,b>0,c>0$$?
Comment: @Dr.SonnhardGraubner No
Comment: another approach is to define $a$ using $b$ and $c$ from the equation $a b c+a +c=b$ then put the derivative of the first form to $0$ once with respect to $b$ and other with $c$ , leaving you with expression containing only one variable, also put the derivative of that expression to $0$ and solve for that variable backward to the first variable , and see the values it gives, the maximum value is $\frac{10}{3}$ and the minimum value is $2$.
Answer: For  $a=\frac{1}{\sqrt2}$, $b=\sqrt2$ and $c=\frac{1}{2\sqrt2}$ we'll get a value $\frac{10}{3}$.
We'll prove that it's a maximal value.
Indeed, the condition gives $c(ab+1)=b-a$.
If $ab=-1$ then $a=b$ and $a^2+1=0$, which is impossible.
Thus, $ab\neq-1$, $c=\frac{b-a}{ab+1}$ and we need to prove that
$$\frac{2}{1+a^2}-\frac{2}{1+b^2}+\frac{3}{1+\left(\frac{b-a}{1+ab}\right)^2}\leq\frac{10}{3}$$ or
$$\frac{2(b^2-a^2)}{(1+a^2)(1+b^2)}+\frac{3(1+ab)^2}{(1+a^2)(1+b^2)}\leq\frac{10}{3}$$ or
$$(a^2+4)b^2-18ab+16a^2+1\geq0,$$
for which it's enough to prove that
$$81a^2-(a^2+4)(16a^2+1)\leq0,$$
which is
$$(2a^2-1)^2\geq0.$$
Done!
I got a value $\frac{10}{3}$ and values $a$, $b$ and $c$ by the following way.
Let $k$ be a maximal value of our expression.
Thus, the following inequality is true for all values of $a$ and $b$.
$$\frac{2(b^2-a^2)}{(1+a^2)(1+b^2)}+\frac{3(1+ab)^2}{(1+a^2)(1+b^2)}\leq k$$ or
$$(ka^2-3a^2+k-2)b^2-6ab+ka^2+2a^2+k-3\geq0.$$
Thus, $k\geq3$ and since we have a quadratic inequality of $b$, we need that the equality
$$9a^2-(ka^2-3a^2+k-2)(ka^2+2a^2+k-3)\leq0$$ or
$$(k^2-k-6)a^4+2(k^2-3k-2)a^2+k^2-5k+6\geq0$$
will be true for all value of $a$.
But the last inequality is a quadratic inequality of $a^2$, which says that we need
$$(k^2-3k-2)^2-(k^2-k-6)(k^2-5k+6)\leq0$$ or
$$3k-10\geq0,$$
which gives a value $\frac{10}{3}$ and from here we can get the case of the equality occurring.
Comment: How could you guess the maximum value?
Comment: @Hamid Reza Ebrahimi I added something. See now.
Answer: prove that $$\frac{2}{a^2+1}-\frac{2}{b^2+1}+\frac{3}{c^2+1}\le \frac{10}{3}$$ and the equal sign holds if $$a=\frac{2}{3}\left(\frac{1}{2\sqrt{2}}-\sqrt{2}\right),b=-\sqrt{2},c=-\frac{1}{2\sqrt{2}}$$
Comment: Can it be proved using classical AM-GM or QM-AM inequalities?
Comment: if given that $a,b,c$ are real numbers no
Comment: i have solve $$abc+a+c=b$$ for $c$ and i got a problem in two variables
Comment: How did you find $\frac{10}{3}$?
Comment: see above my comment


Linq query ("not in ") on datatable

Question: I would like to return all rows from TableA table that does not exists in another table.
e.g.
select bench_id from TableA where bench_id not in (select bench_id from TableB )

can you please help me write equivalent LINQ query. Here TableA is from Excel and TableB is from a Database
I am loading Excel sheet data into DataTable, TableA. TableB I am loading from Database. In short, TableA and TableB is type of DataTable
Comment: In little addition.  I am loading Excel sheet data into DataTable : TableA  and  TableB I am loading from Database. In short, TableA and TableB is type of DataTable.
Answer: So if table A is from Excel, are you loading the data into memory first? If so (i.e. you're using LINQ to Objects) then I suggest you load the IDs in table B into a set and then use:
var query = tableA.Where(entry => !tableBIdSet.Contains(entry.Id));

If this isn't appropriate, please give more details.
Converting into a set is probably best done just by using the HashSet constructor which takes an IEnumerable<T>. For example:
var tableBIdSet = new HashSet<string>(db.TableB.Select(entry => entry.Id));

(If the IDs aren't actually distinct, you could add a call to Distinct() at the end.)
Answer: var lPenaltyEmployee = from row1 in tBal.getPenaltyEmployeeList().AsEnumerable()
                                   select row1;

var PenaltyEmp = new HashSet<string>(lPenaltyEmployee.Select(Entry => Entry.Emsrno);

DataTable lAbsentEmp = (from row in tBal.getAbsentEmployee(txtFromDate.Text).AsEnumerable()
                                    where !(PenaltyEmp).Contains(row["Emsrno"].ToString())
                                    select row).CopyToDataTable();

Answer: From a in TableA
Group Join b in TableB on a.bench_id Equalsb.bench_id into g = Group
Where g.Count = 0
Select a

Linq query ("not in ") on datatable


Install Windows XP in Ubuntu 11.04

Question:
Possible Duplicate:
How do I dual boot Windows XP and Ubuntu?

I have Ubuntu 11.04 on my hard disk. Now I want to create a NTFS partition for Windows XP and install Windows XP to get dual operating systems. How should I go about doing this ? How to create the partition in Linux? I am new to Linux..Can anyone please help me ?
Thanks
Answer: You're going to have to boot from a live CD, run sudo gparted, resize your Ubuntu partition for room for XP, then [optional] create a NTFS for XP.  [Edit: If you're a total n00b, here is a link to a gparted tutorial: http://www.dedoimedo.com/computers/gparted.html ] :)
Then you boot from the XP cd, select the partition [or if you didn't create one, tell it to use unallocated space].
Once that installs, you are going to have to reinstall the GRUB bootloader.  If you have grub legacy, I know how. If you have grub-pc [the new one, aka grub 2 I think], I'm not exactly sure how, but a quick google search should tell you.
To reinstall the bootloader you again will have to boot from a live CD and run some commands on the terminal.
For legacy grub:  sudo install-grub /dev/sdX
And you may want to run sudo update-grub, [But you probably should backup /boot/grub/menu.cfg first] and hopefully it will find your XP installation and add it to the menu.  If not you will have to manually edit /boot/grub/menu.cfg.  sudo gedit /boot/grub/menu.cfg
If GRUB finds your windows XP automatically, you're done.
Find the part where it mentions chainloading, [it's commented out] and copy that part, and paste it next to your Linux entries.  Then just replace the "root (hd0,0)" line:  hd0 means the first disk [sda], the next 0 means the first partition. So if your XP partition was /dev/sda4, your line would look like "root (hd0,3)" because the number starts at 0, not 1.

Install Windows XP in Ubuntu 11.04


How can I replace deprecated method dispatch_get_current_queue()?

Question: I am developing a chat application using xmppframework in iOS 5; it works perfectly.
But I updated my Xcode to 4.5.1, iOS 5 to iOS 6 and my Mac OS to 10.7.5, and the project did not work due to deprecation issues. I replaced all methods with new methods in iOS 6 except this one:
dispatch_get_current_queue()

How can I replace this method in iOS 6?
Comment: Huh. So it does. Guess I was looking at the wrong documentation.
Comment: @NoahWitherspoon __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_6,__MAC_NA,__IPHONE_4_0,__IPHONE_6_0)
Means that its deprecated starting in 6.0
Comment: The answers here provide several alternatives: http://stackoverflow.com/questions/13237417/alternatives-to-dispatch-get-current-queue-for-completion-blocks-in-ios-6/
Comment: `dispatch_get_current_queue` is not deprecated. What error or warning are you seeing?
Answer: It depends what you need to achieve with this call.
Apple states that it should be used for debugging anyway.
Perhaps the queue does not matter (as you just need a background queue) so get a global queue with specific priority (dispatch_get_global_queue(dispatch_queue_priority_t priority,
        unsigned long flags);)
OR,
If you do need to execute some pieces of code in the same queue , create a queue, retain it and dispatch all your tasks there.
Answer: How about using NSOperationQueue?
-(void) doSomeThing:(void (^)(BOOL success)) completionHandler
{
    NSOperationQueue* callbackQueue = [NSOperationQueue currentQueue];
    if(!callbackQueue) {
        callbackQueue = [NSOperationQueue mainQueue];
    }
    dispatch_async(...,^{
         // do heavyweight stuff here
         // then call completionHandler
         if(completionHandler) {
             [callbackQueue addOperationWithBlock:^{
                 completionHandler(...);
             }];
         }
    });

Comment: I'm not sure this is the way to go because now you've just add the last part of your operation to the end of your queue.  What if your queue has one max concurrent operation and you have 20 operations in your queue?


LINQ to Entities does not recognize the method String.Format

Question: I'm trying to format a double value (by showing only 2 decimals). I tried to use AsEnumerable but I keep getting this error

LINQ to Entities does not recognize the method
  String.Format

var tw = workers.Select(x => new
            {
                Id = x.Id,
                JobOpportunityFeedbacks = x.JobOpportunityFeedbacks.AsEnumerable().
                Select(y => new
                {
                    Rating = String.Format("0.00",y.Rating),
                    Feedback = y.Feedback
                });

Answer: You have to do the AsEnumerable outside of your initial Select
var tw = workers.Select(x => new
    {
        Id = x.Id,
        JobOpportunityFeedbacks = x.JobOpportunityFeedbacks
            .Select(y => new
            {
                y.Rating,
                y.Feedback
            })
    })
    .AsEnumerable()
    .Select(x => new
    {
        x.Id,
        JopOpertunityFeedbacks = x.JobOpportunityFeedbacks
            .Select(y => new
            {
                Rating = String.Format("0.00",y.Rating),
                y.Feedback
            })
    });

Comment: @HediNaily What do you mean twice as slow?  Twice as slow as what?  I know it looks like you're doing the same stuff twice, but this avoids having the DB return more data than you need.
Comment: You're answer is the solution. However, it's going to be twice slower, do you think there is another alternative. (I can't use decimal type unfortunately)
Answer: Use SqlFunctions class - I didn't try this but should work.
var tw = workers.Select(x => new
            {
                Id = x.Id,
                JobOpportunityFeedbacks = x.JobOpportunityFeedbacks.AsEnumerable().
                Select(y => new
                {
                    Rating = SqlFunctions.StringConvert(y.Rating, 4, 2)
                    Feedback = y.Feedback
                });

https://msdn.microsoft.com/en-us/library/dd487158(v=vs.110).aspx


HVAC leaking cold air at unit: seal with tape?

Question: I was in my crawlspace today and noticed that there was cold air leaking from a grouping of three round openings in my unit (pictured in the middle of the photo below). The outer two holes had rubber gaskets that I was able to adjust in order to stem the flow of air but the large black pipe in the middle had no gasket. While our home is cooling well at the moment, I am wondering if this is a problem I should have an HVAC repair person come look at, or if I can/should just seal these with HVAC tape myself.

Any advice here would be much appreciated; thanks!
Answer: A little bit of duct seal, will plug that hole right up.

(source: idealind.com)
Grab a bit off the brick, and roll it into a snake (like you used to do with play-doh). Wrap it around the pipe, while pushing it into the hole.
Comment: Thanks for the tip!  Just wanted to be sure that there weren't internal problems causing this leak that I should have a pro look at.
Comment: @PhilipAllen Not likely. Those pipes are connected to the evaporator coil, which is in a pressurized chamber. If it's not sealed around the pipe, air is going to come out.


Why is my question put on hold?

Question: I have a question about this: How to change the default view of the "extend" page in a custom administration theme
Can you tell me why my question is put on hold or voted for closing ?
I think that my question is very clear with my screenshots and edited description that I have added.
I feel that as a new user asks a question you often ask to be closed or put on put on hold.
Can you check this case even for me ?
Answer: I'm only guessing at the motivation for closing, but given the "Unclear what you're asking" I'd assume people aren't sure exactly what part of the desired feature you're stuck at implementing.
Writing broader tutorials/how-to's doesn't suit Q+A very well because there are often a bunch of different disciplines involved, different parts of the system to gain knowledge about, etc, so it's best to break a task down into smallest parts and ask questions about each of those. That way we end up with content that helps people who want to do a similar thing to you, but also helps people who need to solve the same generic tasks for another purpose altogether.
For example, if you're approaching this programatically your broken-down list of things to find out might be:

How do I replace the content of an administration page, or create a new one?
How can I make sure the permission requirements stay the same for the new/replaced page
How do I programatically get a list of modules?
How do I render that list into something pretty for the user?
How do I get that rendered content onto the page?
How do I achieve the layout I need while still allowing the form submission to operate?

I'm sure there are more but you get the idea.
I'm not saying you should necessarily ask all of these as questions, but those are the things you would go off and research, and when you get stuck with a narrower implementation detail, this site is the perfect medium to get help with it.
As an aside, there often is a, perhaps inevitable, correlation between the length of membership and likelihood of questions being closed. It's not because we don't want questions from new users, quite the opposite (we wouldn't survive without them), but because new users often aren't aware of the expectations put on them.
Writing a good question for this repository of knowledge is hard. It takes a lot of time and effort to properly research a topic and present a query in a way that's suitable for and useful to as broad an audience as possible; newer users are usually under the impression this is an extension of the drupal.org support forums, rather than what it actually is.
There's no blame attached to that in any direction, we don't hold a grudge against anyone for asking a question that was deemed to be off-topic, but we do need to close them so they don't stick around and become examples for still newer users of what's acceptable to ask.
BTW those last few paragraphs (from the "aside") are much more general thoughts, I wasn't thinking about you or your question specifically when I wrote them.

Why is my question put on hold?


Python regex issue with strings

Question: Hi wonder if someone can help I've converted to Python from Perl and for the most part I love it.  However I struggle with regex in Python this is not as strong or easy as perl for anyway.  How do I use a list of exemption values(exemptions_list) to search another list which is being iterated in a for loop.  Problem is that the values in the for loop are slightly different from the search exemptions.
i.e. one of the exemptions is the string "default" but the variable coming in to be search is default_10 or default_20.  Likewise none is the search pattern but the share is called none_20 etc.  I don't really want to iterate over the search patterns as I am already iterating over the shares which come from another subprocess output.  So basically it never finds the string as it is looking for default_20 rather than default.  How can break down the variable coming in from shared_list so that python uses default from the variable to search again the strings in the exemptions_list.  The share variable is as stated generated differently for different systems subprocess output.
Many thanks
in Perl it would be easy.
if ( $share =~ /^.*_[\d\d]/ && $share !~ /$cust_id|$exemptions/ ) {

Python:
exemption_list = "none temp swap container"
shares_list [' this is dynamic and comes in with values such as none_20 temp_20, testtmp etc ]'
def process_share_information(shares_list, customer_id):
    for share in shares_list:
        share_match = re.search(share, exemption_list)
        if not share_match:
            print 'we have found a potentially bad share not in exemptions'

Comment: Please give a [Minimal, Viable, Complete Example](https://stackoverflow.com/help/mcve) with every question on Stack Overflow. As it stands, your code will not run.
Comment: not sure that is very helpful if the code ran then why would I be here ?  not really going to post pages of private code just looking for a little help on regex.
Comment: @Stu: What Kevin means is that your code is not valid Python. It has syntax errors.
Comment: Yes that is correct, it was was really meant as a discussion point.  Apologies I will try harder next time to get a good example first.
Answer: Strips last _\d\d from string
re.sub(r'_\d\d$', '', string)

So to check for exemption do
>>> re.sub(r'_\d\d$', '', "none_20") in exemption_list
True

If searched words are in more general format than name_\d\d, iterate over exemptions instead.
>>> exemptions = "none temp swap container".split()
>>> shares_list = "this is dynamic and comes in with values such as none_20 asdfnone anonea temp_20, testtmp etc"
>>> for e in exemptions:
...     print(e)
...     print(e in shares_list)
...     print(re.findall(r'\b\S*?{}\S*?\b'.format(e), shares_list))
...     print()
...
none
True
['none_20', 'asdfnone', 'anonea']

temp
True
['temp_20']

swap
False
[]

container
False
[]

Or if you only need one result for whole string
>>> any(e in shares_list for e in exemptions)
True

Comment: Thanks I did think of this however unfortunately that would not fit with other exemptions if they were all of the format _dd then yes.  However on some occasion the share value will be wwwwdddd_default_dddwwwddd etc.
Comment: maybe I should reverse it an do if exception_list in share  can I do this as the full list of exemptions or would I need to loop the exemptions also ?.
Comment: @Stu I've figured it was in `name_\d\d` format, since that was in your *perl* example. Please edit your question so it is more clear.
Comment: Apologies yes I understand.  Basically I have a string of exemptions that form part of a list of shares that I want to iterate over and if they are not in the exemption list then they need checked.  i.e. list  to shorten it all down say the strings exemptions are "default temp"  and I have a loop variable with share names coming in like with values like 'stuarttemp' I want to ignore this one as it has temp in the share name.  Likewise the next share is stu_0023_default_blah I would want to ignore this one.
Comment: Looks great, can you explain a little on what the logic is here, the findall method of re seems to be failing on my version of python.  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 181, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
Comment: @Stu What do you not understand? I can't reproduce the error.

Python regex issue with strings