text:
Q: How to fetch string from AsyncTask class method to MainActivity? i have code that fetches a string on php page using a class that extends AsyncTask . Now I need to change button color on UI according to the string value. But I discovered that v cannot change it in AsyncTask class so v need to pass again the resultString to main thread. How should i do that?
Here is my code:
MainActivityClass
{
    //button color changes acc to php page string
}

AsyncTaskClass
{
    String result=fetch string data from php using doInBackground method;
    //cant change button color here need to pass result to main activity
}

A: Async task has a override method, onPostexecute(), call your mainActivity function in this function and pass string as parameter.
Use following for reference:
https://developer.android.com/reference/android/os/AsyncTask.html
https://stackoverflow.com/a/9671602/2487029

A: Class A{
    private MyListener ml;
    doInBackground(){
        //string your_string = GetFromWeb();
        //passString(your_string);

    }
    public void setMyCustomListener(MyListener l){
        ml = l;
    }
    public interface MyListener{
        public void passString(String s);
    }
}

Class B implements MyListener {

    @Override
    public void passString(String s){
        //Do your thing here
    }
}


text:
Q: Jacl script behaves wrongly in case of special characters \ ! ; $ Hi I have written one jacl script which is not working properly in case of ; $ ! \
test.jacl
set password [ lindex $argv 1 ]

puts "Hello your entered password is  $password"

Script OUTPUT
When I run
../test.jacl testUser Foo\b4r*

it returns
Hello your entered password is Foob4r*

CASE 2:
 ../test.jacl testUser Foo$b4r*

OUTPUT
Hello your entered password is Foo*

CASE 3:
../test.jacl testUser Foo;b4r*

OUTPUT
Hello your entered password is Foo

CASE 3:
../test.jacl testUser Foo!b4r*

OUTPUT
-bash: !b4r*: event not found

Kindly suggest best way to overcome this problem

redpajama_set_name: RedPajamaStackExchange


text:
Q: bufio.NewReader ReadBytes - Reading multiple message at the same time I have this listener function that listens on a network for messages from its peers.
It works fine must of the time but when it recieves two messages at the same time I get the following error:
" Message Decode error - extra data in buffer"
Can this be modified to allow multilpe message at the same time?
func Listen(peer Peer) {

    log.Info(" Listening for messages from: ", peer.Address)

    for {
        //will listen for message to process ending in newline (\n)
        msg, msgErr := bufio.NewReader(peer.conn).ReadBytes([]byte(`\n`)[0])
        if msgErr == io.EOF {
            peer.conn.Close()
        } else if msgErr == nil {
            msg, err := hex.DecodeString(string(msg[:len(msg)-1]))
            mgsDecoded, decodeErr := DeserializeMessage(msg[:])

            if decodeErr == nil {
                // use decoded message here
            } else {
                log.Warn(" Message Decode error - ", decodeErr)
            }

        }
    }
}

//DeserializeMessage - Decode our message from a byte array to
//networkMessage *NetworkMessage
//over the network
func DeserializeMessage(serialized_bytes []byte) (NetworkMessage, error) {
    // Create new buffer and decoder
    buf := bytes.NewBuffer(serialized_bytes)
    enc := gob.NewDecoder(buf)
    // Create new Block Instance to load the serialized block into
    var networkMessage NetworkMessage
    err := enc.Decode(&networkMessage)
    return networkMessage, err
}

Added how we send a message:

func SendMsgToPeer(networkMessage NetworkMessage, peer Peer) {

    log.Debug(" Message Sent -> Peer: ", peer.Address,
        " Command: ", string(networkMessage.Command),
        " Payload: ", string(utils.TruncateString(networkMessage.Payload, 50)))

    msg, err := networkMessage.SerializeMessage()
    if err != nil {
        log.Warn("❌ Error encoding message.")
    }

    peer.conn.Write([]byte(hex.EncodeToString(msg)))
    peer.conn.Write([]byte(`\n`))
}

A: The application creates and discards a buffer on every iteration of the loop. The discarded buffer can contain unprocessed data read from the connection.
Fixed by creating the the bufio.Reader once outside of the loop.
The expression []byte(`\n`)[0] evaluates to the byte \, not \n.  Fix by specifying \n as the delimiter.
br := bufio.NewReader(peer.conn)
for {
    //will listen for message to process ending in newline (\n)
    msg, msgErr := br.ReadBytes('\n')
    ...

The client writes the message terminator as the two bytes \, n. Change the client to write the single byte \n by using an interpreted string literal instead of a raw string literal.
peer.conn.Write([]byte("\n"))

If you can remove the requirement to use newline separated hex encoded messages, then you can use the gob decoder directly:
func Listen(peer Peer) {
    defer peer.conn.Close()
    log.Info(" Listening for messages from: ", peer.Address)
    dec := gob.NewDecoder(peer.conn)
    for {
       var networkMessage NetworkMessage
       err := dec.Decode(&networkMessage)
       if err != nil {
          log.Info("decode error:", err)
          return
        }
        // do something with networkMessage
    }
}

Make corresponding changes to the client code. Add field enc *gob.Encoder to Peer and initialize the field to gob.NewEncoder(peer.conn).  Use the encoder in SendMsgToPeer.
func SendMsgToPeer(networkMessage NetworkMessage, peer Peer) {
    log.Debug(" Message Sent -> Peer: ", peer.Address,
        " Command: ", string(networkMessage.Command),
        " Payload: ", string(utils.TruncateString(networkMessage.Payload, 50)))
    err := peer.enc.Encode(networkMessage)
    if err != nil {
        log.Warn("❌ Error encoding message.")
    }
}


text:
Q: proof check product equals zero entails a multiplicand is zero Currently trying to learn/teach myself proofs, however I could use some feedback on this proof. just want to know if its correct. I am sure there is a much quicker way to prove this. My main concern is directed towards its correctness.
thank you
For all integers $a$ and $b$, if $ab=0$ and $a\neq0$, then $b=0$.
Suppose $ab=0$ and $a\neq0$.
By the trichotomy law there are 3 cases to consider for $b$.
Either $a<b$, $b<a$ or $a=b$
Case 1. Suppose $a<b$, and assume for a contradiction that $b\neq0$.
Thus either $0<b$ or $b<0$.
Case 1.1. Suppose $0<b$. Since $a<b$ we know that $a-b<0$.
So by the axiom of transitivity;
$a-b<b$ following this and applying the scaling axiom
$ab-bb<bb$
applying scaling again we achieve
$aba-bba<bba$ which is $0<0$. A contradiction.
Note that whilst scaling by "$a$" we did not know whether $a<0$ or $0<a$, however the result remains the same.
Thus it is not the case that $0<b$.
Case 1.2. Suppose $b<0$. Since $a<b$ by transitivity $a<0$.
From $a<b$ we get $a-b<0$.
Now applying scaling axiom we obtain.
$ab-bb>0$ so $–bb>0$
Applying scaling again we have $0<0$. A contradiction.
Thus it is not the case that $b<0$.
Since it's the case that $b$ is neither greater nor less than zero, it must be that $b=0$. However this violates the initial supposition that $b\neq0$. An absurdity, thus $b=0$.
Therefore if $a<b$ then $b=0$.
Case 2. Suppose $b<a$ and assume for a contradiction that $b\neq0$.
… cases follow similarly to case 1…
Therefore, if $b<a$ then $b=0$.
Case 3. Suppose $a=b$.
Substituting this in for $ab=0$ we find $aa=bb=0$.
Further, it can be shown that $aab=a(0)=0=aa$. Therefore $a=0$.
This contradicts the initial assumption that $a\neq0$. Therefore $a\neq b$.
Now eliminating case 3 from trichotomy  leaves only cases 1 &2. Both cases imply that $b=0$.
Therefore if $ab=0$ and $a\neq 0$, then $b=0$.
UPDATE hey read your answer and tried to put a comment on but it would not post, so I am putting it here...
Hmm a little confused on why I would choose $a>0$ as my case 1 assumption. The reason I broke case 1 into 1.1 and 1.2 was to show for case 1.1 that if $b>0$ then $b<0$ (or some other contradiction) and similarly for 1.2. Which would then mean my assumption that $b \neq 0$ is contradicted. This would give me the required, if $a<b$ then $b = 0$. If I started with your assumptions for $a$ in these cases. I would be contradicting one of my primary assumptions.This would only then serve to eliminate the case $a<b$ similar to how I did my case 3. Is this what you are suggesting? Just want to make sure I am interpreting your solution correctly, otherwise good answer :)

A: In general you have the right idea: break the problem down to cases and prove each case by axioms. You could use more detail in 1.2 to prove that $a(0) = 0$ and $b(0) = 0$. In case 3, instead of saying "it can be shown," just show it.
The main problem is that the proof is redundantly long. If we assume this axiom of the "scaling principle," we should be able to demonstrate the proof very briefly:
"Suppose $b ≠ 0$. Then (case 1) $a > 0 \implies ab > 0b$, by the scaling principle $\implies ab - 0b > 0 \implies a - 0>0$, which is a contradiction. Similarly for case 2 when $a < 0$".
Note that this uses roughly the same structure, axioms, and strategy as your proof. So why is yours so long? It seems to be because you are breaking the proof into cases based on the value of $a$ relative to $b$. You go to so much work to get to the relation $a - b<b$, while what you really need is $a<0$, which is where my proof starts.
To summarize: you are adding more conditions than you need. Remove them and your proof will be shorter, cleaner, and easier to evaluate.


text:
Q: Element Tree : Can't build root tree when getting XML from webpage I'm trying to parse an XML page I'm downloading from the web.
import requests
url = "http://www.w3schools.com/xml/cd_catalog.xml"
XML = requests.get(url)
print XML.content

tree = ET.ElementTree(XML)
root = tree.getroot()

print root.tag, root.attrib

I get one of two errors when I try and do this
for the above example webpage
    AttributeError: 'Response' object has no attribute 'tag'
And for the actualy XML site I'm looking at
    AttributeError: 'str' object has no attribute 'tag'
However if I just copy and paste the XML I've downloaded into a .xml file and open it works fine with no errors. Would anyone know how to fix these problems..?

A: You need to parse the response body, not the response object:
root = ET.fromstring(XML.content) # no .getroot() call required

or pass in a file object:
XML = requests.get(url, stream=True)
tree = ET.parse(XML.raw)
root = tree.getroot()

The latter could fail if the stream is compressed; the raw file object does not decompress this for you.


text:
Q: MSSQL Executing table filled with instructions I need to change the collation for quite a lot tables including the columns. I already wrote a sql-statement which generate these for me. I wanted to create a stored procedure to automate this process. I created a table to store these generated statements and want to execute row after row. How can I do that?
Thanks in advance


text:
Q: Magento Category Path Url Structure I am migrating a Magento installation from 1.7 to 1.9. In the (old) 1.7 installation, URL's are structured as follows:
Category:
www.webstore.com/category/sub-category/sub-sub-category

Product:
www.webstore.com/product.html

I am unable to replicate this url structure in the new installation as the configuration setting in
System -> Configuration -> Catalog -> Search Engine Optimizations only allows to turn on or off the category path for products, but I only want to turn it on for the category url path.
Is there a setting, I am overlooking or is it be necessary to change the catalog rewrite generation code and if so, how can this be accomplished?

A: I think you can go to admin > catalog > URL Rewrite Management and set there the URL structure you need. The downside is that you'll need to add a rule for each category/product and for any new ones in the future.


text:
Q: Graded ring constructed from an integral domain The aim of this construction is to obtain a projective curve $\operatorname{Proj}(A)$ from a given affine curve $\operatorname{Spec}(R)$. Example: from $\mathbb{A}^1_k$ to $\mathbb{P}^1_k$
But I want to consider a more general situation as follows.
Let $R$ be an integral domain with a degree function $\deg: R\to \mathbb{N}$, satisfying the usual degree properties as in polynomial rings. We can construct a graded ring $$A = \bigoplus_{d=0}^\infty R_d$$ by setting $$R_d = \{r\in R: \deg(r)\leq d\}.$$ Now, suppose $t = \gcd\{\deg(r):r\in R\}$ and $R_0$ is a field. Moreover, there exists a positive integer $r$ such that $$\dim_{R_0} (R_{(n+1)t}/R_{nt})\leq r$$ for all $n$ with equality for large enough $n$.
Now, I want to show that $R$ and $A$ are finitely generated $R_0$-algebra. Put $X = \operatorname{Proj} A$. Do we have $\dim X = \dim A-1$?
An example would be $R = k[x]$ polynomial ring over a field $k$. Then, $R_0 = k$ and $R_d = \{\text{polynomials of degree }\leq d\text{ in }x\}\cong \{\text{homogeneous polynomials of degree }d \text{ in }x_0,x_1\}$. In this case, $t=1$ and $\dim_k (R_{n+1}/R_n) = 1$ for all $n$. Moreover, $A = \bigoplus_{d=0}^\infty R_d \cong k[x_0,x_1]$ is finitely generated $R_0$-algebra. Then, $X = \mathbb{P}^1_k$; $\dim X = 1 = \dim A-1$.

A: We may assume $t = 1$ (by dividing all degrees by $t$). We have $$R = \bigoplus_{d=0}^\infty R_d/R_{d-1}.$$
Let $k = R_0$ and $K = Frac(R)$. Let $x$ be a homogeneous element with $\deg x = d > 0$. Let $\dim (R_i/R_{i-1}) = r$ for $i \ge N$. Then multiplication by $x$ induces an injection of $k$-vector spaces $$(R_i/R_{i-1}) \xrightarrow{\cdot x} (R_{i+d}/R_{i+d-1})$$ and these are of the same dimension for $i \ge N$ which implies that this is an isomorphism for $i \ge N$. Thus, if we take some finitely many homogeneous generators over $k$ of $R_N$ together with $x$ then these will generate $R$ over $k$.
Edit: My initial answer was needlessly complicated, I edited out the useless parts.


text:
Q: Spectral measure and commutativity. I want to prove that if $A\in B(H)$ and $N\in B(H)$ is a normal operator, and $AE(\Delta)=E(\Delta)A$, where $E$ is the spectral measure given by $N$ and $\Delta$ is a Borel subset of $\sigma(N)$, then $AN=NA$.
I tried these first steps:
$\langle ANg,h \rangle =\langle (\int z dE(z))g,A^\ast h \rangle$...
but I cannot go on.
Maybe writing down the definition of the integral respect to the spectral measure as the limit of the sum of $z*E(\Delta_i)$ taken on a partition $\{\Delta_1...\Delta_n\}$ of the spectrum with every piece of the partition quite small, is possible to achieve the result.
Can you suggest me a more straightforward way?
Thank you!

A: The Spectral Theorem tells you that for every $\varepsilon>0$ there exists a partition $\{\Delta_1,\ldots,\Delta_n\}$ of $\sigma(N)$ and complex numbers $\lambda_1,\ldots,\lambda_n$ such that
$$
\left\|N-\sum_{j=1}^n\lambda_j\,E(\Delta_j)\right\|<\varepsilon.
$$
As $A$ commutes with $\sum_j\lambda_j\,E(\Delta_j)$, you get that $\|AN-NA\|<2\varepsilon$; as $\varepsilon$ is arbitrary, $AN-NA=0$.


text:
Q: How can I pass along an array of floats as a uniform to shaders from Three JS To clarify I am using Three JS, React-Three-Fiber, React
I have disc with points mapped on it, I have calculated the distance of every point to the center of the desk and stored results in an array. I would like to pass this array to the shaders but I am struggling to understand how to do it. I read in the docs you can also pass along vec3,mat3,float essentially. My array has a length of 1000 so I cannot use it with any of the data types uniforms can be used with, if I store the array as a define how can I go about using it in the shader file?
uniforms
  const uniforms = useMemo(() => ({
    uTime: {
      value: 0.0
    },
    uRadius: {
      value: radius
    },
    uDistance: {
      value: normalDistances
    }
  }), [])

fragment shader
const fragmentShader = `
uniform vec3 uDistance;

varying float vDistance;

  void main() {

    float x = uDistance[52];

    vec3 color = vec3(0.5, 0.5, x);

    gl_FragColor = vec4(color, 1.0);
  }

`

export default fragmentShader

I cannot import a uniform without specifying the data type, and I cannot find how to import a define which was passed along from javascript. Does anyone know what my issue is? Thanks!

A: uniform vec3 uDistance;

This is no valid declaration of a uniform array. You always have to define the length like so:
uniform vec3 uDistance[8];

However, keep in mind that uniform arrays require a uniform vector for each entry. If you want to use a length of 1000, you easily hit the maximum supported uniform vectors on devices.
I suggest you encode your distance data into a texture and then sample it in your shader. In three.js, you can use the DataTexture class for this.


text:
Q: Using a pull subscription with a long running process I have something like this in my main.py:
while (True):
    pulled = subscription.pull(max_messages=1) # also tried with return_immediately=True
    for ack_id, data in pulled:
        subscription.acknowledge([ack_id])
        run_task() # takes 15 minutes to return
    time.sleep(30)

What I'm trying to do is get a message from the queue, acknowledge it immediately and then run my long running job.
But every single time, just after 10 minutes of run_task() starting I get the following error on the subscription.pull line:

"google.gax.errors.GaxError: GaxError(RPC failed, caused by
  <_Rendezvous of RPC that terminated with (StatusCode.UNAVAILABLE,
  {..."description":"Endpoint read failed"...}

I can tell that this error happens before run_task() finishes, but there are no exceptions thrown from inside run_task(). I have no idea how run_task() stopped and pull() is getting executed now.
Can anyone tell what's going on here? I'm kinda thinking that the message isn't being acknowledged and the acknowledgment deadline expires, but the message never gets re-delivered so that theory isn't adding up.


text:
Q: Calculate the density function of $Y=\frac{1}{X}-X$ where $X\sim U[0,1]$ I know that :
$$f_X(x)=\cases{1 & $x\in [0,1]$\\0 & $x\notin[0,1]$}$$
Then:
$$P(Y\leq y)=P(\frac{1}{X}-X\leq y)=P(X\leq\frac{1}{2}(\sqrt{y^2+4}-y))$$ as $$\frac{1}{x}-x=y\rightarrow x\frac{1}{x}-xx=yx\rightarrow 1-x^2=yx\rightarrow 1-x^2-xy=0\rightarrow \cases{\frac{1}{2}(\sqrt{y^2+4}-y)\\\frac{1}{2}(-\sqrt{y^2+4}-y)}  $$ I assumed positive root only(dont know if it is right assumption). So I am stuck from now on. Any suggestions.

A: As mentioned by @André and @Did, your inequality sign is the wrong way. We should have
$$F_Y(y)=
P(Y\leq y) = P\left(\dfrac{1}{X}-X \leq y \right) = P\left(X^2+yX-1 \geq 0 \right).
$$
You found the quadratic roots correctly. So the general solution to the quadratic inequality is $$X\leq \frac12\left(-y-\sqrt{y^2+4}\right)\quad\text{or}\quad X\geq\frac12 \left(-y+\sqrt{y^2+4}\right).$$ However, we must have $X\in (0,1)$ so we take the positive range only and we get, for any $y\gt 0$,
$$F_Y(y) = P\left(X\geq\frac12 \left(-y+\sqrt{y^2+4}\right)\right) = \dfrac{2+y-\sqrt{y^2+4}}{2}.$$
For $y\le0$, $F_Y(y)=0$. Differentiating $F_Y$ (and rearranging the result slightly) shows that the density $f_Y$ is $$f_Y(y) = \frac{\mathbf 1_{y>0}}{2}\left(1-\frac{y}{\sqrt{4+y^2}}\right) = \frac{\left(\sqrt{4+y^2}-y\right)\,\mathbf 1_{y>0}}{2\sqrt{4+y^2}} \cdot \frac{\sqrt{4+y^2}+y}{\sqrt{4+y^2}+y} = \frac{2\,\mathbf 1_{y>0}}{4+y^2+y\sqrt{4+y^2}}.$$


text:
Q: What is the difference between CLR and DLR in C#? What is the difference between CLR and DLR in C#? are these two concept comparable?

A: Just adding a bit of clarity to the already given excellent answers.
First the CLR, this is a abstraction layer that sits between user code and the physical hardware. There are several advantages:

*

*Hardware independence 2. Common type system 3. Language interoperability

The .Net DLR was created by Jim Hugunin and was

The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages.
  Dynamic languages can identify the type of an object at run time, whereas in statically typed languages such as C# and Visual Basic (when you use Option Explicit On) you must specify object types at design time. Examples of dynamic languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, Cobra, and Groovy.

DLR Architecture

The DLR adds a set of services to the CLR for better supporting dynamic languages. These services include the following:
  Expression trees. The DLR uses expression trees to represent language semantics. For this purpose, the DLR has extended LINQ expression trees to include control flow, assignment, and other language-modeling nodes. For more information, see Expression Trees (C# and Visual Basic).
  Call site caching. A dynamic call site is a place in the code where you perform an operation like a + b or a.b() on dynamic objects. The DLR caches the characteristics of a and b (usually the types of these objects) and information about the operation. If such an operation has been performed previously, the DLR retrieves all the necessary information from the cache for fast dispatch.
  Dynamic object interoperability. The DLR provides a set of classes and interfaces that represent dynamic objects and operations and can be used by language implementers and authors of dynamic libraries. These classes and interfaces include IDynamicMetaObjectProvider, DynamicMetaObject, DynamicObject, and ExpandoObject.
  The DLR uses binders in call sites to communicate not only with the .NET Framework, but with other infrastructures and services, including Silverlight and COM. Binders encapsulate a language's semantics and specify how to perform operations in a call site by using expression trees. This enables dynamic and statically typed languages that use the DLR to share libraries and gain access to all the technologies that the DLR supports.

Examples
dynamic d = "test";
Console.WriteLine(d.GetType());
// Prints "System.String".

d = 100;
Console.WriteLine(d.GetType());
// Prints "System.Int32".

dynamic d = "test";

// The following line throws an exception at run time.
d++;

A: The DLR runs on top of the CLR. The DLR allows C# dynamic variables and other dynamic language features.
http://en.wikipedia.org/wiki/Dynamic_Language_Runtime

A: The Common Language Runtime (CLR) is the core set of services offered by .NET – a type system, JIT, a garbage collector, &c. Those are available to all .NET languages, hence the "Common" part.
The Dynamic Language Runtime (DLR) builds atop of this and offers services for dynamic languages: dynamic types, dynamic method dispatch, code generation, &c. The idea is to make those things uniform and share them among dynamic languages so that they work predictably and similar, just like things on the CLR are across all languages too.
In a way those are comparable, a "normal" language on .NET uses the CLR, a dynamic language should use the DLR, but will use the CLR as well. They are basic sets of functionality that the designers considered to be good when they are common across languages. IronPython and IronRuby were implemented on top of the DLR, as is C# 4's dynamic feature.

A: I'll just add a simple diagram to demonstrate the point:
    "*** Runtime & Libraries ***"    │ "*** Languages ***"
┌────────────────────────────────────┤
│ .NET Libraries                     │
│   ┌────────────────────────────────┼──────────────────┐
│   │ Dynamic Language Runtime (DLR) │ C# 4.0 'dynamic' ├────┐
├───┴────────────────────────────────┼──────────────────┘    │
│ Common Language Runtime (CLR)      │   C# 1.0, 2.0, 3.0    │
└────────────────────────────────────┴───────────────────────┘


text:
Q: Show result of pgAgent step How setup pgAgent step so Result or Output show the number of rows processed on my function?

my function already return the number of rows affected, but that isnt the value show in Result.
BEGIN
    WHILE  int_pending > 0  LOOP
        .....
        UPDATE table SET ....
        GET DIAGNOSTICS int_row_count = ROW_COUNT;
        int_total = int_total + int_row_count;
    END LOOP;

    RETURN int_total;
END;

A: According to source code of pgagent :
output = stepConn->GetLastError();

...

rc = threadConn->ExecuteVoid(
         wxT("UPDATE pgagent.pga_jobsteplog ")
         wxT("   SET jslduration = now() - jslstart, ")
         wxT("       jslresult = ") + NumToStr(rc) + wxT(", jslstatus = '") + stepstatus + wxT("', ")
         wxT("       jsloutput = ") + threadConn->qtDbString(output) + wxT(" ")
         wxT(" WHERE jslid=") + jslid);

pgagent stores last error of of job step execution.
So, there are two ways to implement desired behaviour:

*

*patch source code to implement your feature, recompile, install and use this custom version

*use RAISE EXCEPTION inside plpgsql function, something like this:
CREATE OR REPLACE FUNCTION test_output() RETURNS VOID AS $$
   DECLARE
     rows int := 25;
   BEGIN
     RAISE EXCEPTION 'Updated rows: %', rows;
   END;
$$ LANGUAGE PLPGSQL;


text:
Q: Implementing Drag and Drop of a UIImageView using UILongPressGestureRecognizer I'm implementing a UILongPressGestureRecognizer that will allow the user to long press on an ImageView and then drag the image somewhere else.  Once the long press begins, I scale the view to indicate that dragging is ready and the user then can drag.  This is accomplished by updating the ImageViews frame each time the selector gets called with a change state.  This works perfectly but I would like to create a copy of the view and add it to a parent view on the begin state and then continue updating the copy's frame in the parent view.  I want to do this to eliminate any problems with dragging from scrollviews.  I can't seem to get the logic correct in the HandleChangeState method though.  The copy just doesn't drag correctly.
Any ideas?
Some of the code is just there because I'm trying to make a more generic UILongPressGestureRecognizer for UILabel and UIImageView but it doesn't pertain to this issue.
public class LearningViewLongPressGestureRecognizer : UILongPressGestureRecognizer
    {
        private UIImageView draggedImageView;
        private UILabel draggedLabel;
        private RectangleF originalFrame;
        private UIView parentView;
        private DRAG_CONTENT_TYPE contentType;

        public enum DRAG_CONTENT_TYPE
        {
            UIIMAGEVIEW,
            UILabel
        }

        public static Selector LongPressSelector
        {
            get
            {
                return new Selector ("HandleLongPress");
            }
        }

        public LearningViewLongPressGestureRecognizer (UIView parent, DRAG_CONTENT_TYPE contentType)
        {
            this.contentType = contentType;
            this.AddTarget(this, LongPressSelector);
            this.Delegate = new LongPressRecognizerDelegate();
            this.parentView = parent;
        }

        [Export("HandleLongPress")]
        public void HandleLongPress(UILongPressGestureRecognizer recognizer)
        {
            Console.WriteLine ("HandleLongPress Called.");
            switch (recognizer.State)
            {
            case UIGestureRecognizerState.Began:
                Console.WriteLine ("HandleLongPress Began.");
                HandleBeginState(recognizer);
                break;
            case UIGestureRecognizerState.Changed:
                Console.WriteLine ("HandleLongPress Changed.");
                HandleChangedState(recognizer);
                break;
            case UIGestureRecognizerState.Cancelled:
                Console.WriteLine ("HandleLongPress Canceled.");
                break;
            case UIGestureRecognizerState.Ended:
                Console.WriteLine ("HandleLongPress Ended.");
                break;
            default:
                Console.WriteLine ("HandleLongPress Default.");
                break;
            }
        }

        private void HandleBeginState(UILongPressGestureRecognizer recognizer)
        {
            this.originalFrame = this.View.Frame;

            if (contentType == DRAG_CONTENT_TYPE.UIIMAGEVIEW)
            {
                draggedImageView = new UIImageView();
                draggedImageView.Image = ((UIImageView)this.View).Image;
                draggedImageView.Frame = this.View.Frame;

                //Change the view scale to indicate to the user that the view is selected and ready for dragging.
                draggedImageView.Transform *= CGAffineTransform.MakeScale(1.1f, 1.1f);

                parentView.AddSubview(draggedImageView);
                parentView.BringSubviewToFront(draggedImageView);
            }
        }

        private void HandleChangedState(UILongPressGestureRecognizer recognizer)
        {
            PointF currentLocationOfTouchInParentView = recognizer.LocationInView(draggedImageView);//recognizer.TranslationInView(this.View);
            PointF deltaFromOriginal = new PointF(currentLocationOfTouchInParentView.X - originalFrame.X, currentLocationOfTouchInParentView.Y - originalFrame.Y);

            RectangleF newFrame = draggedImageView.Frame;
            newFrame.Offset(deltaFromOriginal.X, deltaFromOriginal.Y);
            draggedImageView.Frame = newFrame;
        }

        private void HandleCanceledState(UILongPressGestureRecognizer recognizer)
        {

        }

        private void HandleEndedState(UILongPressGestureRecognizer recognizer)
        {

        }

        protected class LongPressRecognizerDelegate : UIGestureRecognizerDelegate
        {
            public override bool ShouldReceiveTouch (UIGestureRecognizer recognizer, UITouch touch)
            {
                return true;
            }
        }
    }

A: Solved my calculations issue.  I needed to take the delta of the original touch location that began the gesture and the current touch location within the parent view and then add that offset to the dragged view frame.  Below is my solution.
private void HandleBeginState(UILongPressGestureRecognizer recognizer)
        {
            this.originalFrame = this.View.Frame;
            this.originalTouchLocation = recognizer.LocationInView(parentView);

            if (contentType == DRAG_CONTENT_TYPE.UIIMAGEVIEW)
            {
                draggedImageView = new UIImageView();
                draggedImageView.Image = ((UIImageView)this.View).Image;
                draggedImageView.Frame = new RectangleF(originalFrame.X, originalFrame.Y, originalFrame.Size.Width, originalFrame.Size.Height);

                parentView.AddSubview(draggedImageView);
                parentView.BringSubviewToFront(draggedImageView);

                //Change the view scale to indicate to the user that the view is selected and ready for dragging.
                draggedImageView.Transform *= CGAffineTransform.MakeScale(1.1f, 1.1f);
            }
        }

        private void HandleChangedState(UILongPressGestureRecognizer recognizer)
        {
            PointF currentLocationOfTouchInParentView = recognizer.LocationInView(parentView);
            PointF deltaFromOriginalTouch = new PointF(currentLocationOfTouchInParentView.X - originalTouchLocation.X, currentLocationOfTouchInParentView.Y - originalTouchLocation.Y);

            RectangleF newFrame = originalFrame;
            newFrame.Offset(deltaFromOriginalTouch.X, deltaFromOriginalTouch.Y);
            draggedImageView.Frame = newFrame;
        }


text:
Q: My idea was create my own js method that i will pass in three parameters (method,url,data) Js method
I have create a js post method using xmlhttprequest posting data to my
php page. The problem is how i will get the data after post request is
successful and display on my html page Below is my code.
I am currently working on a project that i have to use js method to post,get delete other more. All I want is an idea of how to get the data deplayed when the submit form function is called after successful submission of the data.
The code is working the part but the feedback part
//define form variables
var formSubmition = document.getElementById('formSubmition');
//addEventListener
formSubmition.addEventListener('submit',dataSubmit,true);;
function pageView(){
 //localstorage_cookie = localStorage setItem('userpage_id','27727');
}
// connect to server via XMLHttpRequest
function serverConnection(){
  this.object = {
         method:'',
         url:'',
         data:'',
         connect:function(a,b,d){
         if(window.XMLHttpRequest){
             server_http = new XMLHttpRequest();
         }else{
             server_http = new ActiveXObject('Microsoft.XMLHTTP');
         }
         server_http.onprogress = function(event){
             console.log(event);
        }
        server_http.onreadystatechange = function(e){
             if(server_http.readyState == 4 && server_http.status == 200){
                var res = server_http.responseText;
                return res;
             }
        }
        server_http.open(a,b,true);
        //server_http.setRequestHeader("Content-type","application/x-www-
        form-urlencoded");
          server_http.send(d);
        }
   }
}

 var conn = new serverConnection(),response_xmlhttp = new serverConnection();
 function serverConn(c,method,URI,formdata){
 //defining data configurations
 c.object['method'] = method; //defined key data for method
 c.object['url'] = URI; //defined key data for url
 c.object['data'] = formdata; //defined key data for data
 //store in global variables
 var method,url,data;
 method = c.object['method'];
 url = c.object['url'];
 data = c.object['data'];
 c.object.connect(method,url,data);
}
//submit_data using the class conn
function dataSubmit(e){
e.preventDefault();

var formdata,method,URI,username,password;
//define username and password
username = document.getElementById('username').value;
password = document.getElementById('password').value;
if(username == '' && password == ''){
  alert('fill in all the fields');
}else{
  formdata = new FormData(this);
  formdata.append('submit_data','SIGNIN');
  method = 'POST';
  URI = 'admin/php_data/loginCredentials.php';
  serverConn(conn,method,URI,formdata);
}
}

A: You need to pass a call back function to serverConnection which it can call when it receives the data from backend, something alone the lines of
function serverConnection(cb){
  this.object = {
         method:'',
         url:'',
         data:'',
         connect:function(a,b,d){
         if(window.XMLHttpRequest){
             server_http = new XMLHttpRequest();
         }else{
             server_http = new ActiveXObject('Microsoft.XMLHTTP');
         }
         server_http.onprogress = function(event){
             console.log(event);
        }
        server_http.onreadystatechange = function(e){
             if(server_http.readyState == 4 && server_http.status == 200){
                var res = server_http.responseText;
                cb(res);
                return res;
             }
        }
        server_http.open(a,b,true);
        //server_http.setRequestHeader("Content-type","application/x-www-
        form-urlencoded");
          server_http.send(d);
        }
   }
}

and then create a function to handle response
function handleResponse(res) {
  // set the res in some element
}

Now just pass it to server connection
var conn = new serverConnection(handleResponse)


text:
Q: Wordpress theme not displaying (after updating to 3.1.3) I'm building a custom Wordpress theme that was working but at some point the theme stopped loading in Wordpress and Wordpress switched back to the default TwentyTen.
I think it may have had to do with upgrading to 3.1.3. Any pointers on how to debug this?

A: Turn on WP_DEBUG in config file
http://codex.wordpress.org/Editing_wp-config.php

A: Aslo except for WP_DEBUG when themes are not showing up and just displays blank pages there is usually a quick fix:

*

*Change to another theme in the admin panel

*Change back to the theme that was not working

*If the theme has a hyphen in the name, remove it.

*Check so that all the files are in their proper place

*Check so that all the files are named right

*When the theme doesn't have a screenshot it's hard to spot, even though it's in the list. Check again carefully.


text:
Q: CountDown Script, Doesn't display or countdown correctly so I've been tyring to debug my script for my pomodoro(tomato) clock. What I want this script to do is it will recieve input(in minutes). Right now what my script is doing is counting down by 5 instead of 1 seconds. Also it will not display the minutes like I want it too.
I made the script in a logical way to log to console and test it. What I see in the console is it displays every second, but it displays 5 seconds every second if that makes sense. Here is the jsbin: https://jsbin.com/gigohajawo/3/edit?js,consolehttps://jsbin.com/gigohajawo/3/edit?js,console
Here is the code, any help would be appreciated!!!
//makes sure the page is loaded first
$(document).ready(function() {
    //global variables
    //grabs text of an id and converts it to an int
    var countMin = 5;
    var count1 = 60;

    //when button id "but" is clicked...

       //while page is up, it keeps track each second that has passed
       for(; countMin >=0;countMin--){
            var counter1 = setInterval(function(){
                //calls timer function to count down
                 count1 = Timer(count1,counter1,countMin);
            },1000);
          count1 =60;
        }

    //counts down
    function Timer(count,counter,minutes){
        count--;
        //once it hits 0 seconds, the interval will stop counting
        if(count <=0){
            clearInterval(counter);
            return count;
        }

        //displays the countdown
        if(minutes < 10){
            if(count < 10){
                console.log("0:0" + count);
            } else {
                console.log("0:" + count);
            }
        }else if(minutes > 0 && minutes < 10){
            if(count < 10){
                console.log("0" + minutes +":0" + count);
            } else {
               console.log("0"+minutes+":" + count);
            }
        } else{
            if(count < 10){
                console.log(minutes+":0" + count);
            } else {
               console.log=minutes+":" + count;
            }
        }

        return count;
    }

});

A: This JSBin seems to do what you intended.
The code:
//makes sure the page is loaded first
$(document).ready(function() {
    //global variables
    //grabs text of an id and converts it to an int
    var count1 = 120;

    // Call a function every 1000 milliseconds (1 second)
    var counter1 = setInterval(function() {
      count1 = Timer(count1, counter1);
    }, 1000);

    //counts down
    function Timer(count,counter){
        // Decrement the seconds counter
        count--;

        // Get the minutes and seconds in whole numbers
        var minutes = Math.floor(count / 60);
        var seconds = count % 60;

        // Once it hits 0 seconds, the interval will stop counting
        if(count <=0){
            clearInterval(counter);
        }

        // Pads the seconds with a 0
        if (seconds < 10) {
          seconds = "0" + seconds;
        }

        // Pads the minutes with a 0
        if (minutes < 10) {
          minutes = "0" + minutes;
        }

        //displays the countdown
        console.log(minutes + ":" + seconds)

        return count;
    }

});

Please note:

*

*Since you have defined count1 as a global variable you do not need to pass it into Timer

*The same goes for counter1
If I was rewriting it I would do something like this:
//makes sure the page is loaded first
$(document).ready(function() {
    var timeInSeconds = 120;

    var timeCounter = setInterval(function() {
      timeInSeconds--;

      // If we hit 0 seconds clear the timer
      if (timeInSeconds <= 0) {
        clearInterval(timeCounter);
      }

      // Display the current time
      displayTime();
    }, 1000);

    function displayTime(){
        // Get the minutes and seconds in whole numbers
        var minutes = Math.floor(timeInSeconds / 60);
        var seconds = timeInSeconds % 60;

        // Pad with zeros using the Ternary operator
        seconds = (seconds < 10) ? "0" + seconds : seconds;
        minutes = (minutes < 10) ? "0" + minutes : minutes;

        // Display the countdown
        console.log(minutes + ":" + seconds)
    }

});


text:
Q: Importing a file with space in name How do we import a function from a file, say, 'New File.py' in python in a different file (both being in the same directory)?
If it were, say, 'This_thing.py', then we could simply type
from This_thing.py import *fn_name*

What is the format of importing stuff from the file with the said name-type?
TL;DR,
from New File.py import fn

doesn't work. What to do?


text:
Q: Does defaults() method exist in Password? i made a service provider to validate the password in Laravel 8, but i get this error:
Call to undefined method Illuminate\Validation\Rules\Password::defaults()

PasswordRuleServiceProvider was added in app.php
// Custom Service Providers
App\Providers\PasswordRuleServiceProvider::class,

This is the provider:
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;

class PasswordRuleServiceProvider extends ServiceProvider
{
    public function register()
    {
        //
    }

    public function boot()
    {
        Password::defaults(function () {
            $rule = Password::min(8)->letters()->mixedCase()->numbers()->symbols()->uncompromised(3);
            return $rule;
        });
    }
}

I followed the Laravel doc to do this but it doesn't work, does the defaults method exist in Password? Thanks.

A: As you can see in the commit history of that Password class, this method did not exist until Laravel v8.42.0 (released on May 18th 2021). Make sure that you are using at least that version if you want to call such a method.

Next time, you should check the source code in your project for such methods, and not any other version on the internet. The source code you've linked might be newer than that


text:
Q: How can I read multiple large CSVs in chunks in parallel using R? I have 10 very large CSV files (which may or may not have the same headers) that I am reading in and processing consecutively in chunks using "readr" package read_csv_chunked(). Currently, I am able to read the 10 files in parallel using 10 cores. The process still takes an hour. I have 128 cores. Can I split each CSV into 10 chunks to process in parallel for each of the files hence utilizing 100 cores? Here is what I currently have (creating two sample files only for testing):
library(doParallel)
library(foreach)

# Create a list of two sample CSV files and a filter by file
df_1 <- data.frame(matrix(sample(1:300), ncol = 3))
df_2 <- data.frame(matrix(sample(1:200), ncol = 4))
filter_by_df <- data.frame(X1 = 1:100)

write.csv(df_1, "df_1.csv", row.names = FALSE)
write.csv(df_2, "df_2.csv", row.names = FALSE)

files <- c("df_1.csv", "df_2.csv")

# Create a function to read and filter each file in chunks
my_function <-
  function(file) {
    library(dplyr)
    library(plyr)
    library(readr)

    filter_df <-
      function(x, pos) {
        subset(x, X1 %in% filter_by_df$X1 | X2 %in% filter_by_df$X1)
      }

    readr_df <-
      read_csv_chunked(file,
                       callback = DataFrameCallback$new(filter_df),
                       progress = F,
                       chunk_size = 50) %>%
      as.data.frame() %>%
      distinct()
    return(readr_df)
  }

# Apply the custom function created above to all files in parallel and combine them
df_foreach <-
  foreach(i = files, .combine = rbind.fill, .packages = c("plyr")) %dopar% my_function(i)

I am researching nested foreach() but am not sure how to pass different functions in a nested manner (read_csv_chunked with .combine = rbind and my custom function filter_df() with .combine = rbinf.fill()). I also looked into "future" package. Any advice is greatly appreciated. Thank you.


text:
Q: Como hacer un insert en la creacion de una vista con un union MySQL Estoy intentando crear una vista cogiendo información de dos tablas diferentes con un union pero a la hora de ponerle el valor del rol de personas no lo tengo almacenado en ninguna lado y me gustaria ponerle un valor fijo, y no se como poner un insert o como hacerlo, Yo intentado lo siguiente pero en el select me da error.
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`@`localhost`
SQL SECURITY DEFINER
VIEW `users` AS
SELECT
    `usuarios`.`id` AS `id`,
    `usuarios`.`usuario` AS `username`,
    `usuarios`.`password` AS `password`,
    `usuarios`.`role_id` AS `role`
FROM
    `usuarios`
UNION
SELECT
    `personas`.`id` AS `id`,
    `personas`.`usuario` AS `username`,
    `personas`.`contraseña` AS `password`,
    `5` AS `role`
FROM
    `personas`

No se si lo que intento hacer se puede hacer o no.


text:
Q: AlertDialog is dismissing even when dismiss() not called. I am creating a AlertDialog and it is being dismissed even when dismiss() is not called. The code is as below :
public static void noInternetDialog(final Context context) {

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(R.string.alert_title);
    builder.setMessage(R.string.internet_not_available);
    builder.setCancelable(false);
    builder.setPositiveButton(R.string.retryBtnLabel, new AlertDialog.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            Toast.makeText(context, "Retry Clicked", Toast.LENGTH_SHORT).show();

        }
    });

    builder.setNegativeButton(R.string.alert_negative,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(context, "Settings Clicked", Toast.LENGTH_SHORT).show();

                }
            });

    AlertDialog alertDialog = builder.create();
    alertDialog.setCancelable(false);
    try {
        alertDialog.show();
    } catch (Exception ignored) {
    }
}

I don't want the dialog to be dismissed in some cases so i am having trouble because it is being dismissed.

A: when you set  setPositiveButton or setNegativeButton  to AlertDialog.Builde
when positive button or  NegativeButton of the dialog is pressed the dialog will automatically dismissed


text:
Q: Passing variables from mutation to query I have a GraphQL mutation that creates an item and returns the data that's created. I need to pass some of the created fields into a query. Is this possible? This is almost working but I can't figure out how to get the data between the mutation and the query:
mutation {
    createToken(
        input: { tokenname: "my token", tokendescription: "my valuable token" }
    ) {
        id
        randomdata
    }
  insert__helloworld_article(objects: [{randomdata: "Hello" , author_id: 1}]) {
    returning {
      id
    }
  }
}

So my problem is getting "randomdata" from the mutation to insert into the helloworld_article

A: You wouldn't be able to use the return value in the same mutation with GraphQL, however if those objects have a relationship you could do a nested insert.


text:
Q: image classification when a class contains different kind of images i have to classifiy images into 4 categories food attire misc and dectoration but when i see my data of food class it contains variety of images like it has cakes pics,it has wines bottel it has plates pics and so many other which are related to food but not vary similar so how to classifiy such i use transfer learning but did't get good acc
please to see dataset visit https://www.hackerearth.com/challenges/competitive/hackerearth-deep-learning-challenge-auto-tag-images-gala/machine-learning/auto-tag-images-of-the-gala-9e47fb31/
it is hackearth competion of gala event

A: You can try training with the small number of class, but covariate shift will be a big issue, and may end up with an unstable model.
You can use unsupervised techniques to add more sub-classes to the model.
First of all, you can compress the image dimensions (with PCA, t-SNE, etc.), then apply k-means clustering to find the probable new classes. Then, assign the appropriate class names to each cluster. You will end up with more classes. Then, you can train your deep learning model with those extra classes to get a more stable model.
import numpy as np
from sklearn.manifold import TSNE
# flatten the X image array

X_embedded = TSNE(n_components=2).fit_transform(X)
X_embedded.shape

# apply, k-means to find suitable clusters

from sklearn.cluster import KMeans
import numpy as np

kmeans = KMeans(n_clusters=2, random_state=0).fit(X_embedded)
kmeans.labels_

# test images
kmeans.predict(X_test)

kmeans.cluster_centers_

# for each cluster center assign a new class


text:
Q: Как вытащить анимацию из плагина WordPress? Для wp есть плагин называется mistape https://mistape.com. При выделении текста и нажатии Ctrl+Enter он отправляет на почту выделенный текст. Так вот там очень крутая анимация отправки письма. Пример можете посмотреть на моем сайте https://tehremzona.ru. Я хочу ее вытащить что бы использовать в других местах, но у меня не получается(( можете помочь с этим вопросом? Может ее возможно просто вызвать когда мне это нужно?

A: Для overlay:
#mistape_dialog .dialog__overlay {
    opacity: 0;
    -webkit-transition: opacity .3s;
    transition: opacity .3s;
}

На событие добавляется opacity: 1;
Для формы:
#mistape_dialog.dialog--open .dialog__content {
    -webkit-animation-name: anim-open;
    animation-name: anim-open;
}

#mistape_dialog.dialog--open .dialog__content, #mistape_dialog.dialog--close .dialog__content {
    -webkit-animation-duration: .3s;
    animation-duration: .3s;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}

@keyframes anim-open {
    0% {
        opacity: 0;
        -webkit-transform: scale3d(1.1,1.1,1);
        transform: scale3d(1.1,1.1,1);
    }
    100% {
        opacity: 1;
        -webkit-transform: scale3d(1,1,1);
        transform: scale3d(1,1,1);
    }
}

то есть если вы хотите использовать такую анимацию то вам нужно просто для любого елемента добавить:
.your-class {
    -webkit-animation-duration: .3s;
    animation-duration: .3s;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}

Если вы хотите отказаться от плагина, то не забудьте перенести @keyframes к себе в стили. И на нужное событие добавить css свойства:
-webkit-animation-name: anim-open;
animation-name: anim-open;

A:

.mistape-letter{
 width: 640px;
 height: 400px;
 top: calc(50% - 200px);
 position: absolute;
}

.mistape-letter-front{
 width: 304px;
 height: 190px;
 /*background: url(../img/letter-front.svg) no-repeat;*/
    /*background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSI2NDBweCIgaGVpZ2h0PSI0MDBweCIgdmlld0JveD0iMCAwIDY0MCA0MDAiIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDY0MCA0MDAiIHhtbDpzcGFjZT0icHJlc2VydmUiPjxwb2x5bGluZSBpZD0ibGVmdCIgZmlsbD0iI0U1MjEyOSIgcG9pbnRzPSIwLDAgMCw0MDAgNC4wNjMsNDAwIDMyMi43NSwyMDEuNzUgMCwwICIvPjxwb2x5Z29uIGlkPSJib3R0b20iIGZpbGw9IiNENjI3MzQiIHBvaW50cz0iMCw0MDAgNjQwLDQwMCA2NDAsMzk4Ljk1MyAzMjAuMjgxLDE5OS44MjggIi8+PHBvbHlsaW5lIGlkPSJyaWdodCIgZmlsbD0iI0JDMjMzRCIgcG9pbnRzPSI2NDAsMCAzMjAsMjAwIDY0MCw0MDAgNjQwLDAgIi8+PC9zdmc+);*/
    /*background-repeat: no-repeat;*/
    /*background-size: 100% 100%;*/
 position: absolute;
 bottom: 0;
 z-index: 4;
 left: calc(50% - 152px);
 transform: scale(0.145);
 transform-origin: 50% 100%;
 opacity: 0;
 transition: transform 0.4s, opacity 0.15s;
}

.mistape-letter-front .front-left {
    width: 0;
    height: 0;
    border-left: 152px solid #E42029;
    border-right: 0;
    border-top: 95px solid transparent;
    border-bottom: 95px solid transparent;
    position: absolute;
    z-index: 2;
    top: 0;
    left: 0;
}

.mistape-letter-front .front-right {
    width: 0;
    height: 0;
    border-right: 152px solid #E42029;
    border-left: 0;
    border-top: 95px solid transparent;
    border-bottom: 95px solid transparent;
    position: absolute;
    z-index: 2;
    top: 0;
    right: 0;
}

.mistape-letter-front .front-right:before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-right: 152px solid rgba(0,0,0,0.2);
    border-left: 0;
    border-top: 95px solid transparent;
    border-bottom: 95px solid transparent;
    position: absolute;
    top: -95px;
    right: -152px;
}

.mistape-letter-front .front-bottom {
    width: 0;
    height: 0;
    border-bottom: 95px solid #E42029;
    border-top: 0;
    border-left: 152px solid transparent;
    border-right: 152px solid transparent;
    position: absolute;
    z-index: 2;
    bottom: 0;
    left: 0;
}

.mistape-letter-front .front-bottom:before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-bottom: 95px solid rgba(0,0,0,0.1);
    border-top: 0;
    border-left: 152px solid transparent;
    border-right: 152px solid transparent;
    position: absolute;
    top: 0;
    right: -152px;
}

.mistape-letter-back{
 width: 304px;
 height: 190px;
 /*background: url(../img/letter-back.svg) no-repeat;*/
    /*background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSI2NDBweCIgaGVpZ2h0PSI0MDBweCIgdmlld0JveD0iMCAwIDY0MCA0MDAiIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDY0MCA0MDAiIHhtbDpzcGFjZT0icHJlc2VydmUiPjxyZWN0IHg9IjAiIGZpbGw9IiNCMjI0NDMiIHdpZHRoPSI2NDAiIGhlaWdodD0iNDAwIi8+PHBvbHlsaW5lIGlkPSJ0b3AxIiBkaXNwbGF5PSJub25lIiBmaWxsPSIjQjIyNDQzIiBwb2ludHM9IjAsMCAzMjAsMjAwIDY0MCwwICIvPjwvc3ZnPg==);*/
    background-color: #E42029;
    background-repeat: no-repeat;
    background-size: 100% 100%;
 position: absolute;
 z-index: 2;
 bottom: 0;
 left: calc(50% - 152px);
 transition: transform 0.4s, opacity 0.15s;
 transform: scale(0.145);
 transform-origin: 50% 100%;
 opacity: 0;
}
.mistape-letter-back:before {
    content: '';
    display: block;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background-color: rgba(0,0,0,0.4);
}
.mistape-letter-back > .mistape-letter-back-top{
 /*width: 304px;*/
 /*height: 95px;*/
    width: 0;
    height: 0;
 /*background: url(../img/letter-t2.svg) no-repeat;*/
    /*background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSI2NDBweCIgaGVpZ2h0PSIyMDBweCIgdmlld0JveD0iMCAwIDY0MCAyMDAiIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDY0MCAyMDAiIHhtbDpzcGFjZT0icHJlc2VydmUiPjxwb2x5Z29uIGlkPSJ0b3AyIiBmaWxsPSIjOTcxRTNGIiBwb2ludHM9IjAsMjAwIDY0MCwyMDAgMzIwLDAgIi8+PC9zdmc+);*/
    border-bottom: 95px solid #E42029;
    border-top: 0;
    border-left: 152px solid transparent;
    border-right: 152px solid transparent;
    background-repeat: no-repeat;
    background-size: 100% 100%;
 position: absolute;
 z-index: 2;
 bottom: 100%;
 left: calc(50% - 152px);
 transition: transform 0.4s;
 transform-origin: 50% 100%;
 transform: translateX(0) rotateX(-180deg);
}
.mistape-letter-back > .mistape-letter-back-top:before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-bottom: 95px solid rgba(0,0,0,.3);
    border-top: 0;
    border-left: 152px solid transparent;
    border-right: 152px solid transparent;
    position: absolute;
    top: 0;
    left: -152px;
}
.mistape-letter-top {
    width: 0;
    height: 0;
    /*background: url(../img/letter-t2.svg) no-repeat;*/
    /*background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSI2NDBweCIgaGVpZ2h0PSIyMDBweCIgdmlld0JveD0iMCAwIDY0MCAyMDAiIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDY0MCAyMDAiIHhtbDpzcGFjZT0icHJlc2VydmUiPjxwb2x5Z29uIGlkPSJ0b3AyIiBmaWxsPSIjOTcxRTNGIiBwb2ludHM9IjAsMjAwIDY0MCwyMDAgMzIwLDAgIi8+PC9zdmc+);*/
    /*background-repeat: no-repeat;*/
    /*background-size: 100% 100%;*/
    border-bottom: 95px solid #E42029;
    border-top: 0;
    border-left: 152px solid transparent;
    border-right: 152px solid transparent;
    position: absolute;
    z-index: 2;
    bottom: 0;
    opacity: 0;
    left: calc(50% - 152px);
    transition: transform 0.3s;
    transform-origin: 50% 100%;
    transform: rotateX(0deg);
}
.mistape-letter-top:before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-bottom: 95px solid rgba(0,0,0,.3);
    border-top: 0;
    border-left: 152px solid transparent;
    border-right: 152px solid transparent;
    position: absolute;
    top: 0;
    left: -152px;
}
.mistape-letter-top.close {
 transform: rotateX(-180deg);
}
#mistape_dialog .dialog__content .dialog-wrap{
 z-index: 3;
 position: relative;
}

#mistape_dialog .dialog__content.show-letter .mistape-letter-back,
#mistape_dialog .dialog__content.show-letter .mistape-letter-front{
 transform: scale(1) translateY(15%);
 opacity: 1;
}
#mistape_dialog .dialog__content.show-letter .mistape-letter-back > .mistape-letter-back-top{
 transform: rotateX(0deg);
}
#mistape_dialog .dialog__content.show-letter .dialog-wrap .dialog-wrap-top{
 transform: rotateX(-180deg);
}
#mistape_dialog .dialog__content.show-letter .dialog-wrap .dialog-wrap-bottom{
 background: #c1c1c1;
}
#mistape_dialog .dialog__content.show-letter .dialog-wrap .dialog-wrap-bottom textarea{
 background: #c1c1c1;
}
#mistape_dialog .dialog__content.show-letter .dialog-wrap{
 transform: translateY(-150%);
}
#mistape_dialog .dialog__content.show-letter.with-comment .dialog-wrap{
 transform: translateY(-50%);
}
#mistape_dialog .mistape_action[data-action="send"]{
 position: relative;
 z-index: 8;
}
#mistape_dialog .dialog__content.show-letter .mistape_action[data-action="send"]{
 transition-delay: 0.3s;
 transition: visibility 0.1s, opacity 0.1s;
 visibility: hidden!important;
 opacity: 0!important;
}

@keyframes send-letter1 {
 0% { transform: translateX(0) translateY(15%); }
 20% { transform: translateX(-60%) translateY(15%); }
 100% { transform: translateX(100vw) translateY(15%); }
}

@-moz-keyframes send-letter1 {
 0% { transform: translateX(0) translateY(15%); }
 20% { transform: translateX(-60%) translateY(15%); }
 100% { transform: translateX(100vw) translateY(15%); }
}
@-webkit-keyframes send-letter1 {
 0% { transform: translateX(0) translateY(15%); }
 20% { transform: translateX(-60%) translateY(15%); }
 100% { transform: translateX(100vw) translateY(15%); }
}

@keyframes send-letter2 {
 0% { transform: translateX(0) rotateX(-180deg); }
 20% { transform: translateX(-60%) rotateX(-180deg); }
 100% { transform: translateX(100vw) rotateX(-180deg); }
}
@-moz-keyframes send-letter2 {
 0% { transform: translateX(0) rotateX(-180deg); }
 20% { transform: translateX(-60%) rotateX(-180deg); }
 100% { transform: translateX(100vw) rotateX(-180deg); }
}
@-webkit-keyframes send-letter2 {
 0% { transform: translateX(0) rotateX(-180deg); }
 20% { transform: translateX(-60%) rotateX(-180deg); }
 100% { transform: translateX(100vw) rotateX(-180deg); }
}


text:
Q: Rounding positive/negative numbers to nearest "whole" number I'm trying to round numbers derived from cmath's divide function to a "whole" number, the results often being negative due to the nature of the program.
Example code:
strength = input("Input Strength Stat: ")
str_mod = round(strength/2)

However, the result of this is that it, due to an oddity in python, always returns closer to zero rather than further if, say str_mod prior to rounding ends up at something like -1.5 (resulting in -1 rather than -2 as desired)
This, since I'm trying to create an automatic derived stat calc script for a custom Pen and Paper RPG system, is not the desired behavior. What I desire is for the script to return, at -1.5, -2.0 upon rounding. I need to be able to do this while still rounding positive numbers up similarly.

A: this is because you are getting a(truncated) int from strength/2
try strength/2.0
this is not an oddity with python but simply how most languages cast types for numbers
5/2 = 2
5/2.0 = 2.5

A: You could do this the safe way:
strength = float(raw_input("Input Strength Stat:"))
str_mod = round(strength/2)

In this case, since strength is guaranteed to be a float, you can safely divide by 2 without worrying about truncation or importing division from __future__.  As a bonus, you remove a huge security liability in your game as well.
Using input, a user could do some serious damage to your system:
RPG console> Input Strength Stat: __import__('os').system('rm -r ~')
                                 #^ User input (don't try this!)

A: You may need to use Decimal to get the same rounding as RPG. With Decimal, you can set the rounding mode to up, down, half up, etc.

A: Alternatively, you could try:
from __future__ import division
in order to use py3k division. (e.g. result will be always float)

A: If I understand your problem right, you'd like something that will round half away from zero, as:
-0.5 -> -1
0.5 -> 1
These folks have some good answers. In particular, I based my answer below on AGN Gazer's answer:
from math import floor, ceil

strength = float(raw_input("Input Strength Stat:"))
str_mod  = floor((strength/2) + 0.5) if strength  >= 0.0 else ceil((strength/2)  - 0.5)

Thanks AGN Gazer!


text:
Q: Why does command-line completion not work for cc?. If I use the C compiler cc then command-line completion does not work. If I enter cc dig + press tab then nothing happens but if I compile the program with cc digenv.c then it works. Why no completion for the cc program?

A: Try this:
$ echo "complete -f cc" >> ~/.bashrc

and then source it to get the latest changes:
$ source ~/.bashrc

Then, try the completion.


text:
Q: HTML/CSS - dynamic width div next to bottom-right aligned fixed width div I am trying to create a 2 column layout where the right side div is a fixed width and its content is always aligned with the bottom of the left side div, and the right side of the window. The left side div can grow/shrink in height/width according to the content and the remaining width of the window.
This is fairly simple using a table layout:

            Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text

            Fixed text
Fixed text

http://jsfiddle.net/gpja56se/
However I can not find a way to do this with a div based layout. Is this possible, or is a table layout actually preferable in this case?

A: You can use display:inline-block for div like:

*{
    margin:0;
    padding:0;
}
.main {
    border-collapse: collapse;
}

.left {
    display:inline-block;
    width: 80%;
    background-color: blue;
}

.right {

    text-align: center;
    vertical-align: bottom;
    background-color: red;
    display:inline-block;
    width: 20%;
}

          Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text Dynamic text

          Fixed text
Fixed text

This way right side div content is always fixed at bottom in respective to left div.
Check Fiddle.
Edit:
You can also use display:table instead display:inline-block; like:
* {
    margin: 0;
    padding: 0;
}
.main {
    border-collapse: collapse;
    display: table;
}
.left {
    background-color: blue;
    display: table-cell;
}
.right {
    background-color: red;
    display: table-cell;
    text-align: center;
    vertical-align: bottom;
    width: 70px;
}

Check edited Fiddle.

A: It can be done using CSS but its more complicated because you are mixing fluid width column with fixed width one. Take a look at this article Ultimate multi-column liquid layouts and this demo The 'Right Menu' 2 column Liquid Layout (Pixel-widths)

A: this is a design you can achieve quite easily with css flexbox :
updated fiddle
#container {
    display: flex;
}
.left {
    background-color: green;
}
.right {
    flex-shrink:0;
    flex-basis: 80px;
    text-align: center;
    background-color: red;
    align-self:flex-end;
}

you will still need a container, and the difference with this design is that the right div don't go up to the top. i don't know if that matters ?
try to avoid table as much as bossible - except for real tables


text:
Q: show highest score I have a simple program that has a loop to create a timer, a beep starts the game and ends the game, there are 4 buttons so 4 players.
I have a button click event that registers a click every time the button is clicked at the end I have a print out of all players clicks.
I need a way to tell who got the most clicks so I can light a led up next to there button.
Dose any one know how I could solve this problem code is bellow.
Code
    const int  buttonPin = 7;    // the pin that the pushbutton is attached to
const int  buttonPin2 = 6;    // the pin that the pushbutton is attached to
const int  buttonPin3 = 4;    // the pin that the pushbutton is attached to
const int  buttonPin4 = 3;    // the pin that the pushbutton is attached to
const int ledPin = 13;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

int buttonPushCounter2 = 0;   // counter for the number of button presses
int buttonState2 = 0;         // current state of the button
int lastButtonState2 = 0;     // previous state of the button

int buttonPushCounter3 = 0;   // counter for the number of button presses
int buttonState3 = 0;         // current state of the button
int lastButtonState3 = 0;     // previous state of the button

int buttonPushCounter4 = 0;   // counter for the number of button presses
int buttonState4 = 0;         // current state of the button
int lastButtonState4 = 0;     // previous state of the button

boolean player1 = false;
boolean player2 = false;
boolean player3 = false;
boolean player4 = false;

int speakerOut = 5;
  int a = 0;

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:

   a ++;
  Serial.println(a);
    analogWrite(speakerOut, NULL);

  if(a > 50 && a < 300){
  analogWrite(speakerOut, 200);
  }

  if(a <= 49){
    analogWrite(speakerOut, NULL);
  }

  if(a >= 300 && a <= 2499){
      analogWrite(speakerOut, NULL);
  }

if(a > 300 && a < 2500){

  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  buttonState4 = digitalRead(buttonPin4);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState)
 {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button1 pushes:  ");
      Serial.println(buttonPushCounter);
    }
    else {
      // if the current state is LOW then the button
      // wend from on to off:
      Serial.println("off");
    }
  }
   if (buttonState2 != lastButtonState2)
 {
    // if the state has changed, increment the counter
    if (buttonState2 == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter2++;
      Serial.println("on");
      Serial.print("number of button2 pushes:  ");
      Serial.println(buttonPushCounter2);
    }
    else {
      // if the current state is LOW then the button
      // wend from on to off:
      Serial.println("off");
    }
  }
  if (buttonState3 != lastButtonState3)
 {
    // if the state has changed, increment the counter
    if (buttonState3 == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter3++;
      Serial.println("on");
      Serial.print("number of button3 pushes:  ");
      Serial.println(buttonPushCounter3);
    }
    else {
      // if the current state is LOW then the button
      // wend from on to off:
      Serial.println("off");
    }
  }
  if (buttonState4 != lastButtonState4)
 {
    // if the state has changed, increment the counter
    if (buttonState4 == HIGH) {
      // if the current state is HIGH then the button
      // wend from off to on:
      buttonPushCounter4++;
      Serial.println("on");
      Serial.print("number of button4 pushes:  ");
      Serial.println(buttonPushCounter4);
    }
    else {
      // if the current state is LOW then the button
      // wend from on to off:
      Serial.println("off");
    }
  }
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;
  lastButtonState2 = buttonState2;
  lastButtonState3 = buttonState3;
  lastButtonState4 = buttonState4;

}

if(a > 2500){
    analogWrite(speakerOut, 200);

}

if (a > 2700){
      analogWrite(speakerOut, NULL);

// below is a print out of click by each player
    Serial.print("player 1 clicks = ");
    Serial.println(buttonPushCounter);

    Serial.print("player 2 clicks = ");
    Serial.println(buttonPushCounter2);

    Serial.print("player 3 clicks = ");
    Serial.println(buttonPushCounter3);

    Serial.print("player 4 clicks = ");
    Serial.println(buttonPushCounter4);

   // if(buttonPushCounter > buttonPushCounter2 || buttonPushCounter > buttonPushCounter3 || buttonPushCounter > buttonPushCounter4){
   //   player1 = true;
   // }
    //if(buttonPushCounter2 > buttonPushCounter || ..... ){
    //  player2 = true;
    //}

   // Serial.print("The two players with the highest scores are player... ");
}
}

so what I need is a way to tell who got the most clicks

A: Use qsort().
 #include<stdlib.h>

 typedef struct {
   int Player;
   int Score;
 } PS_T;

 int compar(const void *va, const void *vb) {
   PS_T *ia = (PS_T *) va;
   PS_T *ib = (PS_T *) vb;
   return (ia->Score >= ib->Score) - (ib->Score >= ia->Score);
 }

 // Return true if Silver beat Bronze (detect ties after 2nd place.)
 int Sort4(int *Gold, int *Silver,
     int Score1, int Score2, int Score3, int Score4) {
   PS_T PS[4] = { { 1, Score1 }, { 2, Score2 }, { 3, Score3} , {4, Score4} };
   qsort(PS, 4, sizeof PS[0], compar);
   *Gold = PS[0].Player;
   *Silver = PS[1].Player;
   return PS[1].Score > PS[2].Score;
 }

 ...
 int First;
 int Second;
 Sort4(&First, &Second, buttonPushCounter, buttonPushCounter2,
   buttonPushCounter3, buttonPushCounter4);

A: You can define a macro like that:
#define MAX(a,b) ((a) > (b) ? (a) : (b))

(max of two values)
(or anything else to calculate a maximum)
then use it to get the best score
int bestScore = MAX(MAX(buttonPushCounter,buttonPushCounter2),MAX(buttonPushCounter3,buttonPushCounter4));

and finally use that best score to get the corresponding player, with a simple switch case or something else (Up to you to decide how you want to do) like that:
player1 = (bestScore==buttonPushCounter); // player1=true if the scores match etc...
player2 = (bestScore==buttonPushCounter2);
player3 = (bestScore==buttonPushCounter3);
player4 = (bestScore==buttonPushCounter4);

It's probably not the most elegant way to do, but you can see if there are more than one winner, like two players with the same high score, and "display" all of them.


text:
Q: Sticky footer - trying to understand the code I wanted to implement a sticky footer that will be pushed to bottom if content is less.
I have gone through various posts in this website and could see that two popular solutions (without flexbox) uses either
html, body
{
    height: 100%;
}

OR
html
{
      position: relative;
      min-height: 100%;
}

I am posting only the parts of the solution which I did not understand. Posting my doubts here. Please help me to understand these solutions
(a) as stated, first solution uses 100% height for html and body. But what is 100% height here? Is it refers to the height of view port or height of the entire document?
(b) in first solution, If 100% height refers only to view port height, isn't it required to make the setting to min-height instead of height because if document is larger than the view port, restricting to 100% height is not relevant.
(c) I know we make a element relative so that its child absolute/relative elements gets position from it. But what is the meaning of making html relative as it has only document as its parent?
(d) also, from your experience is there any better solution (without flexbox)? Similarly there are many posts with respect to issues in mobile browsers while using such solutions (like ios8 issue when using 100vh). Whether these solutions have any such issues?
My html knowledge is very much limited. thanks for help.
Note: both solutions are working fine and giving sticky footer as required

A: A)
The html and body tags do not fill the entire window by default, so that code forces to be 100% of screen even when inside content is less.
Without:
With 100%:
B)
You can get away with having the <body> as 100% because the content inside by default will overflow and the <html> tag has overflow:auto on by default.
So, the following works, but the content will overflow the <body>
html, body {
  height: 100%;
}

A better solution would be one of the following:
html, body {
  height: 100%;
}

body {
  overflow: auto;
}

Or
html{
  height: 100%;
}

body {
  min-height: 100%;
}


text:
Q: Cuspform, elliptic curves and character sums I was trying to read through some note by Kowalski (see https://people.math.ethz.ch/~kowalski/ik-ant-exp-sums.pdf). I was interested in trying to understand the following. The author states on page 313 that "One can also  think  this  way  about  the  real  character  sums  with  cubic  polynomials;  they are coefficients of a cusp form associated with an elliptic curve..." I assume that the author is referring to real-valued sums of the form $$\sum_{t\in (\mathbb{F}_q)^{\times}} \psi \big(f(t)\big),$$ where $\psi$ is an additive character on $\mathbb{F}_q$ (field with $q$ elements) and $f(t)\in \mathbb{F}_q[t]$ is a polynomial of degree 3.
First off, I'm sorry about the vague question. I really don't much about this subject, and I'm just curious. I would like if somebody gave a short (if possible) explanation how one can think of these sums as the coefficients of a cusp form. Or point me to a reference. Thanks!


text:
Q: xcode, UIScrollView keep looping scroll animation Objective

*

*trying to make a scrollview, it able to auto scroll to left. after complete will auto scroll to right. and repeat.

The scroll animation keep looping and keep go on the "AfterDone" method even the animation not yet complete.
- (void) afterAnimationStops{
float newOffSetX = _tableview.bounds.size.width-wContentBgImg;
NSLog(@"Inside AutoMove > %d",LzAutoMove);
if(leftright==1 && LzAutoMove==0)
{
    NSLog(@"Come In > 1");
    LzAutoMove = 1;
    leftright = 2;
    [UIScrollView animateWithDuration:3.0f
                          delay:0.0f
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         [UIScrollView beginAnimations:@"scrollAnimation" context:nil];
                         [UIScrollView setAnimationDuration:3.0f];
                         LzcurrentLocation = (-newOffSetX);
                         [imgCell.scrollview setContentOffset:CGPointMake((-newOffSetX), 0)];
                         [UIScrollView commitAnimations];
                     }
                     completion:^(BOOL finished){
                         if (finished) {
                             [self afterDone];
                         }
                     }];
}else{
    if(LzAutoMove==0){
    NSLog(@"Come In > 2");
        LzAutoMove = 1;
        leftright = 1;
        [UIScrollView animateWithDuration:3.0f
                                    delay:0.0f
                                  options:UIViewAnimationOptionCurveEaseOut
                               animations:^{
                                   [UIScrollView beginAnimations:@"scrollAnimation" context:nil];
                                   [UIScrollView setAnimationDuration:3.0f];
                                   LzcurrentLocation = 0;
                                   [imgCell.scrollview setContentOffset:CGPointMake(0, 0)];
                                   [UIScrollView commitAnimations];
                                   //[UIScrollView setAnimationDidStopSelector:@selector(afterDone)];
                               }
                               completion:^(BOOL finished){
                                   if (finished) {
                                       [self afterDone];
                                   }
                               }];

    }

}
}

- (void) afterDone{
    NSLog(@"Done");
    LzAutoMove = 0;
    [self afterAnimationStops];
}

i still learning how to use the "animation completed" method, is that any one can show me where i doing wrong? thanks!

A: You can use UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse flags for your animation option, the animation will auto repeat and reverse to original state after each completion.
[UIView animateWithDuration:3.0f
                            delay:0.0f
                          options:UIViewAnimationOptionRepeat | UIViewAnimationOptionAutoreverse
                       animations:^{
                           [imgCell.scrollview setContentOffset:contentOffset];
                       }
                       completion:^(BOOL finished){
                       }];


text:
Q: Store contacts in own application in iphone I am new to iPhone application development. My application has its own contact screen which has all contacts of phone book and also application's contacts in single list.
My application should store all contacts in its dataabse, it should not display contact screen like contact picker opens.
For this I have created entity of contact to store contacts in my application's persistent store.
I have read iphone's contacts using AddessBook APIs. I am facing some problems in that.

*

*Problem in storing contact image : To get contact image I have used ABPersonCopyImageData. It returns CFDataRef. How can we store CFDataRef in database and retrieve it. Because there are only primitive data types available in entity's attribute type (NSArry type is not available).

*Problem in storing Multivalue Properties : If any any contact has multiple numbers, then we received multiple value for number. Is there any API or mechanism available in core data ? or we have to store them using custom mechanism like using delimiter.

A: if I was you then i would be storing images in document directory convert CFDataRef into NSData and then UIImage
you can convert CFDataRef to NSData simply like this
NSData *myData = (NSData *)myCFDataRef;

then convert it to UIImage like this
UIImage *image=[UIImage imageWithData:myData];

and store it in document directory with different name like test_1.png where 1 is intiger which you increment every time for new image name
and in database store only location string

A: Problem 1:- You can convert CFDataRef to UIImage and store that in database using datatype
"Transformable"
Problem 2:- You have to save that using any delimeter or you can create different attributes for that.
Hope this help you.


text:
Q: Remove Unwrapped and make Optional in Swift?
Value of optional type '[AnyObject]?' must be unwrapped to a value of
  type '[AnyObject]'

I am passing value of one array to another array
first array declared
var arrayShow = [AnyObject]()

second array declared
var arrayData = [AnyObject]()

i m getting crash here :
i have to make below line as options and remove ! @vadian vc.arrayData = (self.arrayShow[tag] as? [AnyObject])!
My Code :
let status = self.nullToNil(value: result["status"]) as? String ?? ""
                let doc_url = self.nullToNil(value: result["doc_url"]) as? String ?? ""
                self.arrayShow.removeAll()

                if(status == "200"){
                    let data = self.nullToNil(value: result["data"]) as? [[String:AnyObject]]
                    self.arrayShow.append(data as AnyObject)
                    print("Array : \(self.arrayShow)")

                    DispatchQueue.main.async {
                        if(data?.count == 0){
                            self.alert(message: "No Data Found.")
                        }else{
                            if let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewPrescriptionReport") as? ViewPrescriptionReport {
                                vc.modalPresentationStyle = .overCurrentContext
                                vc.strTitle = "View Prescription"
                                vc.strURL = doc_url
                                vc.arrayData = (self.arrayShow[tag] as? [AnyObject])!
                                self.present(vc, animated:true, completion: nil)
                            }
                        }
                    }
                }
                else{
                    print("no data found")
                }

A: As arrayShow is not [[]] i.e Array of Arrays so the only way to remove ! is to get element at [tag] from arrayShow and append to a newly created array. Like this.
...
 let element = self.arrayShow[tag]
  vc.arrayData = [AnyObject]()
  vc.arrayData.append(element)
...


text:
Q: Save laravel_session cookie from ajax request - Single sign on I'm trying to implement a single sign on.
The other application makes a http post request to my app passing some parameters, I make a request back and get an email address for the current user. (Yes, I've set the necessary CORS header in my .htaccess)
I'm now creating a user instance with that email and try to authenticate the user.
Auth::login($user, true);
return response("OK", 200);

This works fine (if the user was found).
I now expect that with Auth::login an authenticated session gets created and a session cookie is saved. As soon as the user opens my app, this session is found, no further login is necessary and the dashboard opens.
However no cookie is saved at all.
I then tried to save the cookie manually using
response("OK", 200)
  ->cookie("laravel_session", Session::getId(), 60);

I also tried
response("OK", 200)
  ->cookie("laravel_session", encrypt(Session::getId()), 60);

And
Cookie::queue(Cookie::make("laravel_session", Session::getId(), 60));
response("OK", 200);

In every case the cookie was set but when opening my app the login screen was shown. So my guess is, that there must by anything I'm missing or the laravel_session cookie contains some other data.
So my question is:
Using an ajax post request, how do I properly authenticate a user and save that as a cookie, so he will be logged in when he opens up my app?
UPDATE
I've added some middleware in my kernel.php. Now the session cookie gets set automatically. However it doesn't seem to get encrypted. The "laravel_session" cookie value from the ajax request now looks like this: lYLxSwyuhfHToruJhc0r2zWNLkj9ONTlBM3QjkAo. However the cookie beeing set when using the usual "web" route looks like this: eyJpdiI6InV5bGRQNFJ4c01TYjZwT0I0amxzS1E9PSIsInZhbHVlIjoiZFI2WWpVWGxmTldDcVJvVlwvbVJicXBxM0pjRkVRUlBRKzZWb1BkbzliZHBVdTlmUEV4UzZkaFVMbmlRTHNYczFOZm5HSWkwRXhjb3BJRGI1NGRyM2tnPT0iLCJtYWMiOiJjMjAwMWIyMGIxYmQwYzkxMGQyNGJhMDZmZDJiNThjNGZhMTUyZWVjZDlkNjg5ZWVjYjY2MGE1ZTlmZDAxOGNmIn0%3D
Here is my ['api'] value in the kernel.php protected $middlewareGroups
'api' => [
  'throttle:60,1',
  'bindings',
  \Illuminate\Session\Middleware\StartSession::class,
  \App\Http\Middleware\EncryptCookies::class,
  \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class
],

However, when setting a session cookie with a different name directly in my response, the value seems to be encrypted now:
return response("OK", 200)
  ->cookie("my_session", Session::getId(), $minutes);

Thanks a lot for help.

A: I've found a solution. I need the StartSession::class and the EncryptCookies::class definition in my Kernel.php file AND EncryptCookies:class must be the first element in the list. It didn't worked for me when directly placing it right before StartSession::class
Here is my working "api" definition from Kernel.php
'api' => [
    \App\Http\Middleware\EncryptCookies::class,
    'throttle:60,1',
    'bindings',
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
],

Now the session cookie is set and encrypted. Yeah!


text:
Q: Refreshing jframe and disposing the older frame I have a java swing program which displays the content of an xml page in a jtable. I need to display the frame to be refreshed after every 1 minute. I need to dispose the old frame and get the new frame displayed after being refreshed
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLTableExample {
    JFrame frame = new JFrame("Frame");
    public static void main(String[] args) {
        new XMLTableExample();
    }

    public XMLTableExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager
                            .getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException
                        | IllegalAccessException
                        | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JTable table = new JTable();
                table.setOpaque(false);

                Color lav = new Color(220, 220, 250);

                try {
                    table.setModel(new XMLTableModel(new File("Htmll.xml")));
                    Thread.sleep(6000);
                    //frame.dispose();

                } catch (ParserConfigurationException | SAXException
                        | IOException | XPathExpressionException ex) {
                    ex.printStackTrace();
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                JLabel label=new JLabel("label",JLabel.CENTER);
                label.setText("Service Now Notification");
                label.setFont(new Font("Courier New", Font.ITALIC, 30));
                label.setForeground(Color.blue);

                frame.add(label,BorderLayout.NORTH);
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.setUndecorated(true);

                JButton aButton = new JButton("submit");

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

                        System.exit(0);
                    }
                });
                JScrollPane scroll = new JScrollPane(table);

                scroll.getViewport().setBackground(lav);

                frame.add(scroll);
                frame.add(aButton, BorderLayout.SOUTH);
                frame.pack();

                frame.setLocationRelativeTo(null);
                int frameWidth = 800;
                int frameHeight = 135;
                Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

               frame.setBounds((int) screenSize.getWidth() - frameWidth, 0, frameWidth, frameHeight);

               frame.setLocation((int) 220,590);
                frame.setVisible(true);

            }
        });
    }

    public static class XMLTableModel extends AbstractTableModel {

        /**
         *
         */
        private static final long serialVersionUID = 1L;
        protected static final String[] COLUMN_NAMES = { "Number", "Priority",
                "State", "Assigned", "Description", "Task" };
        private List<MSEntity> rows;

        public XMLTableModel(File file) throws ParserConfigurationException,
                SAXException, IOException, XPathExpressionException {
            rows = new ArrayList<>(25);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document dom = db.parse(file);

            setDocument(dom);
        }

        protected String getMSValue(Node msNode, String name)
                throws XPathExpressionException {
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression expression = xpath.compile("S[@N='" + name + "']");
            Node sNode = (Node) expression
                    .evaluate(msNode, XPathConstants.NODE);
            return sNode != null ? sNode.getTextContent() : null;
        }

        @Override
        public int getRowCount() {
            return rows.size();
        }

        @Override
        public int getColumnCount() {
            return COLUMN_NAMES.length;
        }

        @Override
        public String getColumnName(int column) {
            return COLUMN_NAMES[column];
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return String.class;
        }

        public MSEntity getEntityAtRow(int row) {
            return rows.get(row);
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            MSEntity entity = getEntityAtRow(rowIndex);
            Object value = null;
            switch (columnIndex) {
            case 0:
                value = entity.getNumber();
                break;
            case 1:
                value = entity.getPriority();
                break;
            case 2:
                value = entity.getState();
                break;
            case 3:
                value = entity.getAssigned();
                break;
            case 4:
                value = entity.getDesc();
                break;
            case 5:
                value = entity.getTask();
                break;
            }
            return value;
        }

        public void setDocument(Document dom) throws XPathExpressionException {

            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression expression = xpath.compile("/Objs/Obj/MS");
            NodeList nl = (NodeList) expression.evaluate(dom,
                    XPathConstants.NODESET);
            for (int index = 0; index < nl.getLength(); index++) {
                Node node = nl.item(index);
                String number = getMSValue(node, "Number");
                String priority = getMSValue(node, "Priority");
                String state = getMSValue(node, "State");
                String assigned = getMSValue(node, "Assigned");
                String desc = getMSValue(node, "Short_desc");
                String task = getMSValue(node, "Task");

                MSEntity entity = new MSEntity(number, priority, state,
                        assigned, desc, task);
                rows.add(entity);
            }

            fireTableDataChanged();

        }

        public class MSEntity {
            private final String number;
            private final String priority;
            private final String state;
            private final String assigned;
            private final String desc;
            private final String task;

            public MSEntity(String number, String priority, String state,
                    String assigned, String desc, String task) {
                this.number = number;
                this.priority = priority;
                this.state = state;
                this.assigned = assigned;
                this.desc = desc;
                this.task = task;
            }

            public String getAssigned() {
                return assigned;
            }

            public String getDesc() {
                return desc;
            }

            public String getNumber() {
                return number;
            }

            public String getPriority() {
                return priority;
            }

            public String getState() {
                return state;
            }

            public String getTask() {
                return task;
            }

        }

    }

}

My xml file is this
<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">
    <Obj RefId="0">
        <TN RefId="0">
            <T>Selected.System.Management.Automation.PSCustomObject</T>
            <T>System.Management.Automation.PSCustomObject</T>
            <T>System.Object</T>
        </TN>
        <MS>
            <S N="Number">INC0811168</S>
            <S N="Priority">2 - High</S>
            <S N="State">Assigned</S>
            <S N="Assigned">New</S>
            <S N="Short_desc">Review Ad-Hoc Service Request for Lavon A Gudmundson</S>
            <S N="Task">Catalog Task</S>
        </MS>
    </Obj>
</Objs>

I tried

frame.dispose() but the frame is not being refreshed

A: I used

static JFrame frame = new JFrame("Frame");

and the problem is solved

A: You can also try using Jframe's repaint(long tm) method.


text:
Q: problem with jquery each I'm trying to make a dynamic list with jquery. What i have is an ul element that contains a link and a sub ul element. Like this:

      List I

1

2

      List II

1

2

What i want to do with this list is:
when user clicks any of these links, the sub ul element's html( which is the sibling of the link that is just clicked ) should be copied to new_list div and then made visible.
Here is the code:
$("a.list").each(function() {
    $(this).click(function() {
      var listToShow = $(this).siblings("ul");
      $("#new_list").html(listToShow);
      $("#old_list").hide();
      $("#new_list").show();
      return false;
    });
});

This code works for all the links for the first time, but when i click the same link again an empty list comes up.
What am i missing?
Thanks.

A: Anytime you call a jQuery selector, the actions taken upon it effect all objects the selector returns. Try this. This will bind the function to all current and future  anchor tags with the class list without using each();
$('a.list').live('click', function() {
  var listToShow = $(this).siblings("ul");
  $("#new_list").html(listToShow);
  $("#old_list").hide();
  $("#new_list").show();
  return false;
});

Check out these links for some education on the subject
http://api.jquery.com/click/
http://api.jquery.com/bind/
http://api.jquery.com/live/

A: When you use a DOM element or a jQuery selection in html, the elements are removed from where they previously were and moved to the new place in the DOM.
If you want to copy them to the location, you need to use .clone:
var listToShow = $(this).siblings("ul").clone();

Note also that you don't need the each call there: the handler is automatically applied to each element in the selection.
$("a.list").click(function() {
    var listToShow = $(this).siblings("ul").clone();
    $("#new_list").html(listToShow);
    $("#old_list").hide();
    $("#new_list").show();
    return false;
});

A: Try something like this.  Hope this helps.
 $('#old_list').delegate('a.list', 'click', function() {
     $(this).siblings('ul.sub').clone().appendTo('#new_list');
 });

Remove .clone() if you want to move it instead of copying it.