text:
Q: How can angular velocity or angular momentum be a vector? Rotations in 3 dimensions are not commutative; however they are in the plane. In classical mechanics, are we allowed to say that angular momentum is a vector because particles only rotate along a single axis? Or do we make some kind of argument that you can assign angular velocity to an object because you can approximate it locally as being along a single rotation axis and so its "locally commutative" and hence appropriate to call it a vector? If that is the case what happens if we have a particle rotating in a way that isn't differentiable? Is there some physical reason that particles can't rotate in that sort of way?
I'm really confused by this and haven't taken physics since high school, any help would be appreciated. :)

A: There are a couple of things at play here, which coincidentally(?) mirror the difference between mathematicians who say "vector" to mean anything can be added commutatively and multiplied by a scalar, and physicists who say "vector" to mean a 3- (or 4-)dimensional quantity that transforms properly under change of coordinates.

*

*While arbitrary rotations in 3 dimensions do not commute, infinitesimal rotations do. (In fact any "infinitesimal" transformations commute, as you can see by multiplying $I + \epsilon A$ and $I + \epsilon B$ and ignoring second-order terms in $\epsilon$.) Since angular velocity can be thought of as "infinitesimal rotation per infinitesimal time", it ends up being a vector (in the mathematical sense) even though rotation itself isn't. Similarly, angular momentum is the derivative of kinetic energy with respect to angular velocity, so it is a gradient, which is a (dual) vector (to angular velocity).

*There's an interesting mapping between these infinitesimal rotation matrices and vectors (in the physical sense) which only works in 3 dimensions. If you think of an infinitesimal rotation as $I + \epsilon A$, one can show that $A$ must be antisymmetric. This means its diagonal entries are 0, leaving only 3 degrees of freedom in the off-diagonal entries. Such a matrix can be associated with a vector using the cross product:
$$\begin{bmatrix}0 & -\omega_z & \omega_y \\\ \omega_z & 0 & -\omega_x \\\ -\omega_y & \omega_x & 0\end{bmatrix} \mathbf{r} = \mathbf{\omega} \times \mathbf{r}$$
So angular velocity isn't "naturally" a vector in physical space, but rather lives in a different 3-dimensional vector space. That's why once you interpret it as a physical vector, it turns out to transform slightly differently, as J.M. has pointed out in the comments.


text:
Q: Stack Overflow Isn't Valid HTML5
Possible Duplicate:
The "Hello World!" box is surrounded by paragraph tags twice

stackoverflow.com  isn't valid HTML5.  There's an extra </p> in the "Hello World!" box.
See for yourself (meta is fine however).
I think the Stack Overflow programmers should take time out of their busy schedules to fix this terrible mistake. (sarcasm, but I just kinda wanted to point this out)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby on Rails ignoring integer limit I need to index a table of users using an externally sourced id, which is a 64-bit integer. Rails is perfectly capable of storing such a number, unless it's the primary key it seems. I have the following migration:
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users, :id => false do |t|
      t.integer :id, limit: 8
      t.string :name

      t.timestamps null: false
    end
  end
end

The migration works fine, no errors reported, but when I attempt to seed it with a 64-bit integer, I'm told off by this:
RangeError: 76561198054432981 is out of range for ActiveRecord::Type::Integer with limit 4

Obviously Rails is ignoring the limit field, so long as it's the primary key/the :id field? How should I go about dealing with this?
For what it's worth I'm using sqlite3 (default), but to my knowledge, sqlite is perfectly capable of storing 64-bit integers.
Here's the table_info from sqlite:
0|id|integer(8)|0||0
1|name|varchar|0||0
2|created_at|datetime|1||0
3|updated_at|datetime|1||0

A: The limit value you gave is correct; it corresponds to BIGINT type

Make sure your migration is applied; open you database in some CLI or GUI software and verify the col-type
Addition:
Changing a column's length or datatype in a migration will invalidate the column as a primary key. Rather, creating an initializer that overrides the site's default primary key datatype should provide the behavior you're looking to implement:
# config/initializers/change_primary_key_datatype.rb
require 'active_record/connection_adapters/postgresql_adapter'
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::NATIVE_DATABASE_TYPES[:primary_key] = "bigserial primary key"

This is what we would do for PG database; This is possible because of

however in the code base of SQLite there is


text:
Q: how to insert the actual or current filename (the name of the file I'm working saved in a folder) in .tex or latex document? how to insert the actual or current filename (the name of the file saved in a folder) in .tex or latex document? In Writer (OpenOffice) is normal to use it in a foot or header document, but in .tex documents is there a way to do it? I need it to print it in the foot. Thanks

A: Using footnote ...
\let\thefootnote\relax\footnotetext{\tiny{This is the last page of \jobname.pdf}}

A: You can use the currfile package.
Here is how you put the current file name generically into a document:
\documentclass{article}
\usepackage{currfile}

\title{Article}
\author{Author}
%\date{}

\begin{document}
\maketitle

The current file is: \currfilename.\\

\end{document}

Here is how you put the current file name in the footer:
\documentclass{article}
\usepackage{currfile}

\title{Article}
\author{Author}
%\date{}

\usepackage{fancyhdr}
\pagestyle{plain}
\renewcommand{\headrulewidth}{0pt}  %get rid of header
\fancyfoot[L]{\currfilename} %put current file in footer

\begin{document}
\maketitle
\thispagestyle{fancy}% sets the current page style to 'fancy'

Your text goes here.\\

\end{document}


text:
Q: Is there any similar work environment for Python like the RStudio for R? Similarly, R language has the work environment in RStudio, so there I can run code and see plots, the output of the code run etc. What would be the equivalent for Python language? A program like RStudio where I could run code and see in that program the plot outputs, the console etc.
Thanks!

A: Spyder IDE comes pretty close to the rstudio feel https://www.spyder-ide.org/.
But you'll  find that in the python community jupyter notebooks are more prevalent for data science work
https://jupyter.org/

A: Well, why not simply use RStudio to do your Programming in Python?
With the Reticulate package you can simply open and run Python Scripts in RStudio.

I don't know how efficient that is though.
For just Python I would advise Spyder IDE or Jupyter Notebook.


text:
Q: Have  post 1 when clicked, 0 when not clicked Is it possible to have a <input type="checkbox"> post 1 when selected and 0 when not selected?
By default, it only POST's something (in Firefox 'on') if it has been selected, nothing when not selected.
Preferably without the use of JavaScript.

A: Long story short: No.
<select> only sends the value of the <option> or <option>s that is/are selected.
Just make sure you have an idea of what the options are going into it, and you'll have it made in the shade.
Edit: To address the updated question:
Same story still short: No.
Only the value (or occasionally content) of "successful" controls are sent.
If a checkbox is not checked, it's not successful, and as such, won't be sent.
Just make sure you have an idea of what the controls are going into it, and you'll have it made in the shade.
Reedit: It's probably possible with JavaScript, by messing with the onSubmit action, and setting the value of the related name to 0 if it's not already set.
At the risk of sounding like your tennis instructor, I do have to inform you that this course of action is neither wise nor advisable.

A: I know that in Ruby on Rails the default workaround is to use two inputs like so:
<input type="hidden"   name="whatever" value="0" />
<input type="checkbox" name="whatever" value="1" />

That way, if the checkbox isn't checked, the zero value gets sent. But if it is, both values get sent. Rails will deal with this behind the scenes, but if you go this route with a different server backend, you may need to take that into account.
Alternatively, if you like JavaScript, you can use a nameless, valueless checkbox with its "onchange" event bound to something that sets the hidden input's value appropriately.
Hope that's useful!


text:
Q: How to left outer joins with conditions I have this relation:
class Action < ApplicationRecord
   has_many :actions_users

I tried to make a query like:
select *
from actions left outer join actions_users
on actions_users.action_id = actions.id and actions_users.user_id = 1
where actions.user_id = 1

Meanwhile, in my experience, in all of the result that I tried,
select *
from actions left outer join actions_users
on actions_users.action_id = actions.id
where actions.user_id = 1 and actions_users.user_id = 1

the join condition code and general condition are in where function.
How can I work it out?

A: You can pass a string in join query and use the rails table naming conventions for this.
Action.joins("left outer join action_users on (action_users.id = actions.id and action_users.id = 1")).where('action_users.user_id = ? ', 1)

A: Up to Rails 7 there is no way to specify conditions directly on an OUTER JOIN, see the documentation for Specifying Conditions on the Joined Tables. The examples shown are suitable for INNER JOINs (as they use .where), but won't work for OUTER JOINs for the same reason.
You could try to specify the OUTER JOIN manually, but will run into problems passing parameters:
Action.joins("LEFT OUTER JOIN action_users ON (action_users.id = actions.id AND action_users.id = :user_id")

So you will need to do parameter substitution somewhat like this:
outer_join_sanitized = ApplicationRecord.sanitize_sql([
  "LEFT OUTER JOIN action_users ON (action_users.id = actions.id AND action_users.id = :user_id)",
  { user_id: 22 }
])

And you could then use Actions.joins(outer_join_sanitized). At this point you might agree that just running with raw SQL from the start is the easier way to go.

A: Action.left_outer_joins(:actions_users).where(user_id: 1)

select *
from actions left outer join actions_users
on actions_users.action_id = actions.id and actions_users.user_id = 1
where actions.user_id = 1

Although you did not ask for it yet, ...
Action.left_outer_joins(:actions_users).where(actions_users: {status: 'active'})

select *
from actions left outer join actions_users
on actions_users.action_id = actions.id and actions_users.user_id = 1
where actions_users.status = 'active'

A: Because you have a general where condition, you can use includes. This will generate a LEFT OUTER JOIN query:
Action.includes(:actions_users).where(actions_users: { user_id: true })
Or if you are using Rails 5+, Active Record provides a finder method left_outer_joins:
Action.left_outer_joins(:actions_users).where(actions_users: { user_id: true })


text:
Q: Equivalence of strict convexity of a normed space with strict convexity of $p$th norms Let $E$ be a normed vector space. One says that the norm $\Vert \Vert$ is strictly convex if $\Vert tx+(1-t)y \Vert < 1, \forall x,y \in E \; \text{with} \; x \neq y, \Vert x\Vert = \Vert y \Vert = 1, \; \forall t \in (0,1)$. One says that a function $\phi : E \to (-\infty , +\infty]$ is strictly convex if
$\phi(tx+(1-t)y)<t\phi(x) + (1-t)\phi(y) \; \forall x,y\in E \; \text{with} x\neq y , \; \forall t \in (0,1)$.
How can I show that the norm $\Vert \Vert $ is strictly convex iff the function $\phi(x) = \Vert x \Vert ^p$ is strictly convex for $1<p<\infty$?

A: (1) If $\phi(x) = \|x\|^p$ is strictly convex, for any $\|x\|=1, \|y\|=1, x \neq y$, we have
\begin{equation}
\phi(tx + (1-t)y) = \|tx+(1-t)y\|^p < t \phi(x)+ (1-t)\phi(y) = 1.
\end{equation}
(2) If norm $\|\cdot\|$ is strictly convex, let $$\bar{x} = \frac{x}{\|x\|}, \quad \bar{y} = \frac{y}{\|y\|},$$ we have
\begin{equation}
\|t x + (1-t)y\|^p = \|(t\|x\|) \bar{x} + ((1-t)\|y\|) \bar{y}\|^p < (t\|x\| + (1-t)\|y\|)^p.
\end{equation}
Due to function $f(u)=u^p, 1 < p < \infty$ is convex on domain $\{u \mid u \ge 0\}$. Thus
\begin{equation}
\|t x + (1-t)y\|^p < t\|x\|^p + (1-t)\|y\|^p.
\end{equation}


text:
Q: Making Camel routes run in parallel I have an application which does some basic ETL using camel routes. Each route is configured to take some data from one table do some transformation and safe it into the same table on a different schema.
So there is an one to one relationship between a camel route and a table.
Say I have these two routes:
from("direct:table_1").routeId(table1Route)
    .setBody("SELECT * FROM table_1)
    .to("jdbc:source_schema").split(body()).streaming()
    .process("someProcessor")
    .to("sql:INSERT INTO table_1 ... ?dataSource=target_schema");

from("direct:table_2").routeId(table2Route)
    .setBody("SELECT * FROM table_2)
    .to("jdbc:source_schema").split(body()).streaming()
    .process("someProcessor")
    .to("sql:INSERT INTO table_2 ... ?dataSource=target_schema");

Everything runs OK and the data is moved into target schema when sending a start processing message to both direct:table_1 and direct:table_2 end points.
However looking at the logs I can see table 2 records start being moved only after table 1 records are finished. That is definitely a no no for my application as some tables are quite big and and moving one table at a time would take a very long time to run.
My question is what I am doing wrong and how can I address this so the data movement happens in parallel.

A: I would try something like this:
from("start").multicast().parallelProcessing().to("seda:table1", "seda:table2");

Basically I have:

*

*Used multicast to send to multiple recipients and use parallellprocessing to try to send to both endpoints in parallell.

*I have replaced your direct endpoints with seda endpoints. If you don't require synchronous endpoints it can be beneficial to use seda instead.

You can also experiment with .threads() syntax for multithreading.
If you want to compute your table endpoints at runtime you can replace .multicast() with .recipientlist()

A: Alternatively, if using xml, this can be achieved by:
<routeContext id="xxxRoute" xmlns="http://camel.apache.org/schema/spring">
    <route id="xxxRouteId">
        <from uri="activemq:queue:{{xxx.queue}}" />
        <multicast parallelProcessing="true">
            <pipeline>
                <to uri="file://?fileExist=Append"></to>
            </pipeline>
            <pipeline>
                <to uri="sql:{{sql.xxxx.insertQuery}}"></to>
            </pipeline>
        </multicast>
    </route>
</routeContext>


text:
Q: C++ Accessing the Heap This problem involved me not knowing enough of C++. I am trying to access a specific value that I had placed in the Heap, but I'm unsure of how to access it. In my problem, I had placed a value in a heap from a data member function in an object, and I am trying to access it in another data member function. Problem is I do not know how, and I had searched examples online, but none were what I needed as they were all in int main() and were not specifically what I needed.
In the first data member function, I declare the value I want to be sent to the Heap;
Here's an example of what my first data member function.
void Grid::HeapValues()
{
    //Initializing Variable
    value = 2; //The type is already declared

    //Pointers point a type towards the Heap
    int* pValue = new int;

    //Initialize  an a value of in the Heap
    *pValue = value;
}

And in data member function This is what want:
void Grid::AccessHeap()
{
    //Extracting heap:
    int heap_value = *pValue; //*pValue does not exist in this function
    cout << heap_value; //Delays the value 2, which is found
                        //in the first data member function
}

I feel foolish for asking, but I am unable to find the answers and do not how. Does anyone know how to access a value from the heap in a simple way? And I would need it to be able to access in more then two data member function.

A: Don't forget to delete your pointer in the destructor when you are done. For more information visit:

*

*http://www.cplusplus.com/doc/tutorial/variables.html <-- Variable scope

*http://www.cplusplus.com/doc/tutorial/pointers.html <-- Pointers

*http://www.cplusplus.com/doc/tutorial/dynamic.html <-- Dynamic memory

A: Like Aaron said you can make the value a member of your Grid class. In this case though there is no need for it to be a pointer to an int.
class Grid
{
private:

    int value;

public:

    void HeapValue();
    void AccessHeap();
};

The value will be stored as part of the object wherever it is instanciated. You can make it on the stack or the heap, it doesn't matter. For simple values like the built in types and Objects that will be owned by the instance of the class it is unnecessary to allocate them using new. This way you don't need to worry about cleaning up with the delete operator in the Grid destructor, just make sure you dispose of the owning Grid instance properly ;-)
Of coarse there are exceptions to this that you will learn as you delve more into C++, but for your example the above will be fine.

A: pValue needs to be a member-variable of the class Grid.
class Grid
{
  private: int* pValue;
  public: void HeapValues();
          void AccessHeap();
};

Now the member-variable pValue is accessible from any member-function of Grid.

A: Why do you want it on the heap? If you add it as part of the class then it will be in the same place the class is, possibly on the stack or in global memory. Perhaps you want to have a variable size to your integer pointer? In that case, then you need to be sure to deallocate the memory when you are done with it.
The problem with stuff on the heap is finding it. There is no accessing it by name, unless you add a mechanism for that. Somehow you need to communicate the location to whatever code needs to access it. In this case, it looks like you only need access within the Grid class, so it is easy. Just make it a member variable like Aaron indicates. You might end up with something like:
class Grid
{
protected:
    int* pVals;
public:
    Grid() pVals(NULL) { }
    ~Grid() { delete [] pVals; }
    void HeapValues() {
        pVals = new int[getHeapValuesSize()];
        pVals[0] = 1; // ...
    }
    void AccessHeap() {
        cout << pVals[0]; // ...
    }

(On a side note, you appear to be using the phrase "data member function" when you mean "member function". "Data member" refers to member data of a class, like pVals, but I'm not sure what "data member function" would mean.)


text:
Q: Prevent MatLab nesting variables when saving/loading? I have a variable called sources that contains eight numbers:
sources =

    0.6028
    0.7112
    0.2217
    0.1174
    0.2967
    0.3188
    0.4242
    0.5079

I save it using save('sources.mat', 'sources'); and then load it again using sources = load('sources.mat');
However it is no longer just an array of eight numbers, the sources variable is now:
sources =

    sources: [8x1 double]

Is there any way to get rid of this nesting when saving/loading? It's hassle having to always retrieve the nested variables after loading them. When I use sources = load('sources.mat'); I would like to get back
sources =

    0.6028
    0.7112
    0.2217
    0.1174
    0.2967
    0.3188
    0.4242
    0.5079

Can this be done?

A: in the simplest scenario as the one you show us, you can create an inline function that extracts your data:
loadAndExtract = @(varname) arrayfun(@(x) x.(varname), load(varname));

now you can just load your data as a matrix:
sources = loadAndExtract('sources.mat'); % load and extract data

The drawback of this approach is that you are forced to match name of the file and name of the variable. If this is a problem for you you can make the function slightly more complex:
loadAndExtract = @(dataName,varname) arrayfun(@(x) x.(varname), load(dataName));

now if you load your data with a specific name:
save('mySources','sources');

you can still load it by specifying the name of the variable and name of the file.
sources = loadAndExtract('mySources','sources');

In principle you can write the function to extract multiple data from the same file, but then the inline function gets more and more complex and I would suggest to write is as a separate function.


text:
Q: In safari of ios, when there is a "onclick" inline a child, and a "onmouseover" inline a parent, why mouseover event fired when click the child? In safari of ios, when there is a "onclick" inline a child element, and a "onmouseover" inline a parent element. When touch the child, I want the click event be fired, but first the mouseover event be fired.

I open this html in safari in iPhone, when I click/touch the li element, dosomething1 executed, and I click/touch the li element again, dosomething2 executed. What can I do to make sure only dosomething2 execute when I click the li element?

A: Because the mouseover event bubbles from the child to the parent, and for maximum compatibility, mobile browsers fire a mouseover event when the finger position changes.
If you use proper event handling, or pass the event object into dosomething1, dosomething1 can look at event.target to see whether the target of the mousemove was the span or a descendant element and take appropriate action (or appropriately take no action).
Alternately, you can hook mouseover on (say) the ul and stop the event from bubbling ("propagating") to its ancestors.
Example of using proper event handling and doing the check in the mousemove handler:

document.getElementById("the-span").addEventListener("mousemove", function(e) {
    if (e.target === this) {
        dosomething1();
    }
});
document.getElementById("the-li").addEventListener("click", dosomething2);

function dosomething1() {
    console.log("mousemove on the span");
}

function dosomething2() {
    console.log("click on the li");
}

Text

    text in span outside the li


text:
Q: spawning a router stops when router reloads, any way is there to automatically re-spawn after router is up reloaded i run a tcl send expect script in a file and execute as ./file
#!/usr/bin/expect
spawn -noecho telnet 42.0.1.11
set timeout 900
expect "login:"
send "admin\r"
expect "Password: "
send "ram\r"
expect "#"
for {set i 0} {$i <= 1000000000} {incr i} {
 some router commands
}

this works fine until router reloads, when router reloads, this script stops  as spawn id not open., i want to resume the script (i dont know exactly how much time it takes to reload as it varies most of time).,is there any way to resume the script automatically
Thanks

A: Wrap your login procedure into a proc and call it again if you get EOF. Here is the basic idea, just remember that there may be other ways for things to go wrong.
Edit: I have rewritten the code after some investigation. This has been tested on Linux with "router reboot" being simulated by Solaris 10 workstation (sorry no Cisco to reboot here). As I mentioned ping implementations differ from OS to OS so proc Ping may need to be changed to accommodate your situation.
#!/usr/bin/tclsh

package require Expect

proc RouterLogin {ip user pass} {
    spawn -noecho telnet $ip
    set timeout 60
    expect "login:"
    send "$user\r"
    expect "Password: "
    send "$pass\r"
    expect "#"
    return $spawn_id
}

proc RouterPing ip {
    # ping retry limit      - 3
    # delay between retries - 30 seconds
    set limit   3
    set delay   30
    set attempt 1
    set result false
    while {$result == false && $attempt <= $limit} {
        set result [Ping $ip]
        incr attempt
        if {!$result && $attempt <= $limit} {
            # wait $delay seconds
            after [expr {1000 * $delay}]
        }
    }
    return $result
}

proc Ping ip {
    set pingCmd "ping -c 1 $ip"
    catch {eval exec $pingCmd} pingRes
    if {[regexp "bytes from" $pingRes]} {
        return true
    } else {
        return false
    }
}

proc RouterExec {ip user pass commandList} {
    set spawn_id [RouterLogin $ip $user $pass]
    set timeout 30
    foreach cmd $commandList {
        send "$cmd\r"
        expect {
            "#" {
                # you are good
                puts "Command executed successfully"
            }
            eof {
                # wait 5 minutes
                after [expr {1000 * 60 * 5}]
                if {[RouterPing $ip]} {
                    # ping was successful, relogin and resume
                    set spawn_id [RouterLogin $ip $user $pass]
                } else {
                    # ping was not successful, abort execution
                    return false
                }
            }
            timeout {
                puts "INF: timeout"
                return false
            }
        }
    }
    send "logout\r"
    return true
}

set commandList [list command1 command2 command3]

RouterExec "42.0.1.11" "admin" "ram" $commandList


text:
Q: trying to combine two nested queries for efficiency I have two nested queries, and the second is run as I iterate through the results of the first.  I'd love to have the MySQL server do this work instead of PHP, but I can't figure out how to combine these two.
the first query:
SELECT post_id,
       MAX(CASE WHEN meta_key = 'size' THEN meta_value END) size,
       MAX(CASE WHEN meta_key = 'adlink' THEN meta_value END) adlink,
       MAX(CASE WHEN meta_key = 'frontpage' THEN meta_value END) frontpage,
       MAX(CASE WHEN meta_key = 'expiration' THEN meta_value END) expiration,
       MAX(CASE WHEN meta_key = 'image1' THEN meta_value END) image1,
       MAX(CASE WHEN meta_key = 'image2' THEN meta_value END) image2,
       MAX(CASE WHEN meta_key = 'image3' THEN meta_value END) image3,
       MAX(CASE WHEN meta_key = 'image4' THEN meta_value END) image4,
       MAX(CASE WHEN meta_key = 'iframe' THEN meta_value END) iframe,
       MAX(CASE WHEN meta_key = 'location' THEN meta_value END) location,
       MAX(CASE WHEN meta_key = 'sublocation' THEN meta_value END) sublocation
    FROM wp_postmeta WHERE post_id in
      (SELECT post_id from wp_postmeta
       WHERE meta_value LIKE 'Run Of Site') GROUP BY Post_id

Then, iterating through the results, we get images from another table, as 'image1', etc., are only post id numbers in the first set of results:
SELECT meta_value FROM wp_postmeta
   WHERE post_id IN
     (SELECT meta_value from wp_postmeta
      WHERE post_id = " . $row{'post_id'} ." AND meta_key like 'image%')

HERE's the whole code to see PHP iteration (I KNOW it needs better formatting for readbility):
$rosads = mysql_query("SELECT post_id,
       MAX(CASE WHEN meta_key = 'size' THEN meta_value END) size,
       MAX(CASE WHEN meta_key = 'adlink' THEN meta_value END) adlink,
       MAX(CASE WHEN meta_key = 'frontpage' THEN meta_value END) frontpage,
       MAX(CASE WHEN meta_key = 'expiration' THEN meta_value END) expiration,
       MAX(CASE WHEN meta_key = 'image1' THEN meta_value END) image1,
       MAX(CASE WHEN meta_key = 'image2' THEN meta_value END) image2,
       MAX(CASE WHEN meta_key = 'image1' THEN meta_value END) image3,
       MAX(CASE WHEN meta_key = 'image2' THEN meta_value END) image4,
       MAX(CASE WHEN meta_key = 'iframe' THEN meta_value END) iframe,
       MAX(CASE WHEN meta_key = 'location' THEN meta_value END) location,
       MAX(CASE WHEN meta_key = 'sublocation' THEN meta_value END) sublocation
    FROM wp_postmeta WHERE post_id in (SELECT post_id from wp_postmeta WHERE meta_value LIKE 'Run Of Site') GROUP BY Post_id");
if (!$rosads) { // add this check.
    die('Invalid query: ' . mysql_error());
}

    while ($row = mysql_fetch_array($rosads)) {   // #########  ITERATE THROUGH THE LIST

        if ($row{'size'} == "Premium"){
            if ($row{'iframe'}){
                $premium = $premium . '
'.$row{'iframe'}.'
'."\n";
            }else{
                $images = mysql_query("SELECT meta_value FROM wp_postmeta where post_id IN(SELECT meta_value from wp_postmeta WHERE post_id = " . $row{'post_id'} ." AND meta_key like 'image%')");
                $premium = $premium . "
";
                while ($row2 = mysql_fetch_array($images)) {
                    $premium = $premium . "\t\r\n";
                }
                $premium = $premium . "

";
            }
        /* ### TEST STUFF ####
        echo $row{'post_id'} . ", " . $row{'size'} . ", " . $row{'adlink'} . ", " . $row{'frontpage'} . ", " . $row{'expiration'} . ", " . $row{'image1'} . ", " . $row{'image2'} . ", " . $row{'image3'} . ", " . $row{'image4'} . ", " . 1$row{'location'} . ", " . $row{'sublocation'} . ", " . $row{'iframe'} . "
";
        */
        } // ###### END THIS ITERATION ####

A: You can use your query as a column also but make sure your subquery should return one record for safe side i have added LIMIT 1 in the subquery or if there are morethan 1 result you can remove the limit and can use GROUP_CONCAT(meta_value) but baware it has a default limit of 1024 characters
SELECT wpm.post_id,
       MAX(CASE WHEN wpm.meta_key = 'size' THEN wpm.meta_value END) size,
       MAX(CASE WHEN wpm.meta_key = 'adlink' THEN wpm.meta_value END) adlink,
       MAX(CASE WHEN wpm.meta_key = 'frontpage' THEN wpm.meta_value END) frontpage,
       MAX(CASE WHEN wpm.meta_key = 'expiration' THEN wpm.meta_value END) expiration,
       MAX(CASE WHEN wpm.meta_key = 'image1' THEN wpm.meta_value END) image1,
       MAX(CASE WHEN wpm.meta_key = 'image2' THEN wpm.meta_value END) image2,
       MAX(CASE WHEN wpm.meta_key = 'image3' THEN wpm.meta_value END) image3,
       MAX(CASE WHEN wpm.meta_key = 'image4' THEN wpm.meta_value END) image4,
       MAX(CASE WHEN wpm.meta_key = 'iframe' THEN wpm.meta_value END) iframe,
       MAX(CASE WHEN wpm.meta_key = 'location' THEN wpm.meta_value END) location,
       MAX(CASE WHEN wpm.meta_key = 'sublocation' THEN wpm.meta_value END) sublocation,
(
SELECT
  meta_value
FROM
  wp_postmeta
WHERE post_id IN
  (SELECT
    meta_value
  FROM
    wp_postmeta
  WHERE post_id = wpm. post_id
    AND meta_key LIKE 'image%')
LIMIT 1) images

    FROM wp_postmeta wpm WHERE wpm.post_id IN
      (SELECT post_id FROM wp_postmeta
       WHERE meta_value LIKE 'Run Of Site') GROUP BY wpm.post_id

For the group_concat()
(
SELECT
 GROUP_CONCAT(meta_value)
FROM
  wp_postmeta
WHERE post_id IN
  (SELECT
    meta_value
  FROM
    wp_postmeta
  WHERE post_id = wpm. post_id
    AND meta_key LIKE 'image%')
) images

A: To improve efficiency, replace the IN (subquery) with equivalent join operations, and ensure that you have suitable indexes in place.
In the first query, replace this:
    FROM wp_postmeta WHERE post_id in
      (SELECT post_id from wp_postmeta
       WHERE meta_value LIKE 'Run Of Site') GROUP BY Post_id

with this:
   FROM wp_postmeta m
   JOIN ( SELECT r.post_id
            FROM wp_postmeta r
           WHERE r.meta_value LIKE 'Run Of Site'
          GROUP BY r.post_id
        ) q
     ON q.post_id = m.post_id
  GROUP BY m.post_id

AND change the post_id reference in the SELECT list to m.post_id (to avoid an "ambiguous column" reference error.)
For the second query, replace the "IN (subquery)" with a JOIN operation:
SELECT t.meta_value
  FROM wp_postmeta t
  JOIN ( SELECT q.meta_value
           FROM wp_postmeta q
          WHERE q,meta_key LIKE 'image%'
            AND q.post_id = " . $row{'post_id'} ."
       ) s
    ON s.meta_value = t.meta_value
 ORDER BY t.meta_value

Combining the two queries is problematic because the second query can return more than one row that matches on post_id.
To get result set returned, we need to define what that result set is going to look like.
There's three general approaches. Briefly,
One way is to "repeat" the values returned by the first query, but that doesn't look like a good fit with your current code. The "fetch next" would need to check if the post_id had already been processed, and ignore the duplicate values. (This is the approach used by several ORM frameworks to improve efficiency; those have a code layer that strips out the duplicates, and creates the distinct objects.)
Another way is to return a fixed number of values from the second query, each as a column in the second. Note that the SQL SELECT statement has to define the number of columns to return and the datatype of each. That can't be changed dynamically when the query runs. If we can specify a finite upper bound of the number of rows to return, then we can craft SQL text to accomplish this, though the resulting statement can be a bit daunting, and there are some performance concerns.
The most convenient way to return a "set" of values is to return them as a single string, with delimiters. The MySQL GROUP_CONCAT function is a very handy way of doing that, with some limitations. First, we have to have a delimiter between the values; the default delimiter is a comma, but any character can be used (the "pipe" character seems to be pretty popular... to avoid ambiguity, we have to guarantee that the delimiter character does not appear in the values being concatenated together. The other limit is the size of the returned by the function; the maximum size is limited by the MySQL max_allowed_packet variable.


text:
Q: Listagem no Asp.Net MVC Galera, estou desenvolvendo uma aplicação que gerencia inscrições de cursos, na minha tela de listagem dos Cursos está dessa forma:

Só que eu preciso fazer uma nova tela com outro tipo de listagem, e gostaria que a listagem fosse por curso e mostrasse os alunos inscritos neste curso. Por exemplo, a tela teria que ser assim:

Alguém pode me ajudar?
Model Aluno
public class Aluno
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "O campo Nome é obrigatório")]
    [MinLength(4, ErrorMessage = "O campo Nome deve ter no mínimo 4 caracteres")]
    [Display(Name = "Nome")]
    public string Nome { get; set; }

    [Display(Name = "CPF")]
    [Required(ErrorMessage = "O campo CPF é obrigatório")]
    [Index(IsUnique = true)]
    [CPFAtributo]
    public string CPF { get; set; }

    [Display(Name = "RG")]
    public string RG { get; set; }

    [Display(Name = "E-mail")]
    [Required(ErrorMessage = "O campo E-mail é obrigatório")]
    [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Endereço de e-mail informado não é válido.")]
    public string Email { get; set; }

    [Display(Name = "Usuário")]
    [MinLength(4, ErrorMessage = "O campo Usuário deve ter no mínimo 4 caracteres")]
    [Required(ErrorMessage = "O campo Usuário é obrigatório")]
    public string Usuario { get; set; }

    [Display(Name = "Senha")]
    [Required(ErrorMessage = "O campo Senha é obrigatório")]
    public string Senha { get; set; }

    [Display(Name = "Confirmar Senha")]
    [Compare("Senha", ErrorMessage = "As senhas não conferem")]
    public string ConfirmaSenha { get; set; }

    [Display(Name = "Telefone Celular")]
    [Required(ErrorMessage = "Informe um número de Celular")]
    public string Telefone_Celular { get; set; }

    [Display(Name = "Telefone Fixo")]
    public string Telefone_Fixo { get; set; }

    [Display(Name = "Endereço")]
    [Required(ErrorMessage = "O Endereço é obrigatório")]
    public string Endereco { get; set; }

    [Display(Name = "Estado")]
    [Required(ErrorMessage = "Informe um Estado")]
    public string Estado { get; set; }

    [Display(Name = "Complemento")]
    public string Complemento { get; set; }

    [Display(Name = "Matrícula")]
    [Required(ErrorMessage = "Informe a Matrícula")]
    public string Matricula { get; set; }

    [Display(Name = "Cargo Efetivo")]
    public string Cargo_Efetivo { get; set; }

    [Display(Name = "Cargo Comissionado")]
    public string Cargo_Comissionado { get; set; }

    [Display(Name = "Telefone Orgao")]
    public string Telefone_Orgao { get; set; }

    [Display(Name = "Nome Chefe Imediato")]
    public string Nome_Chefia_Imediato { get; set; }

    [Display(Name = "Telefone Chefe Imediato")]
    public string Telefone_Chefia_Imediato { get; set; }

    public string Perfil { get; set; }

    public ICollection<Curso> Cursos { get; set; }

Model Curso
public class Curso
{
    [Key]
    public int Id { get; set; }

    [Display(Name = "Curso")]
    [Required(ErrorMessage = "O campo Curso é obrigatório")]
    public string Nome_Curso { get; set; }

    [Display(Name = "Sigla")]
    public string Sigla { get; set; }

    [Display(Name = "Ementa")]
    [Required(ErrorMessage = "A Ementa é obrigatório")]
    public string Ementa { get; set; }

    [Display(Name = "Aprovado")]
    public bool Aprovado { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date)]
    [Display(Name = "Data de Início")]
    public DateTime Dt_Inicio { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    [DataType(DataType.Date)]
    [Display(Name = "Data Final")]
    public DateTime Dt_Fim { get; set; }

    [Display(Name = "Turno")]
    [Required(ErrorMessage = "Informe um Turno")]
    public string Turno { get; set; }

    public string Status { get; set; }

    [Display(Name = "Quantidade de Vagas")]
    [Required(ErrorMessage = "A quantidade de Vagas é obrigatório")]
    public int Qtd_Vagas { get; set; }

    public int AlunoId { get; set; }

    public Aluno Aluno { get; set; }

Código de consulta conforme primeira imagem acima
public ActionResult MeusCursos()
    {
        var cursos = db.Cursos.Include(a => a.Aluno).ToList();
        return View(cursos);
    }

A: A modelagem está incorreta. Do jeito que está, um Curso pertence a um só Aluno.
O correto é criar uma tabela associativa. Sugiro algo assim:
public class AlunoCurso
{
    [Key]
    public int Id { get; set; }
    public int AlunoId { get; set; }
    public int CursoId { get; set; }
    public bool Aprovado { get; set; }

    public virtual Aluno Aluno { get; set }
    public virtual Curso Curso { get; set; }
}

Mude Aluno para:
public class Aluno
{
    [Key]
    public int Id { get; set; }
    ...

    public virtual ICollection<AlunoCurso> AlunoCursos { get; set; }
}

E Curso para:
public class Curso
{
    [Key]
    public int Id { get; set; }
    ...

    public virtual ICollection<AlunoCurso> AlunoCursos { get; set; }
}

virtual é importante para o Entity Framework reconhecer que é uma propriedade de navegação (ou seja, que a propriedade não é persistida em banco, e apenas atua como um facilitador da carga preguiçosa).
O Controller ficaria assim:
public ActionResult MeusCursos()
{
    var cursos = db.AlunoCursos
                     .Include(a => a.Aluno)
                     .Include(a => a.Curso)
                     .ToList();

    return View(cursos);
}


text:
Q: Some Widgets ARE showing some are not showing Magento http://ringmastersports.co.uk/
The site is working perfect on mobile but on desktop it works fine few widgets won't showing on frontend.
i'm working to fix these bugs from last 3 days . don't find any solutions.
this website is made in emgameworld premium magento theme.
slider don't showing and also other things are not showing like tabs. where as few widgets work fine.

A: i have run these commands and in sequence and it solved my problem
php -dmemory_limit=6G bin/magento setup:di:compile
php -dmemory_limit=6G bin/magento indexer:reindex
php bin/magento cache:clean and php bin/magento cache:flush


text:
Q: Checking multiple values in html data attribute I have a data attribute with multiple values (data-day="5,6,7") and I want to compare todays date with those values. Below please find the code I created but corrently it works only if i have ONE value only in the data attribute. How I can check and compare today date with the multiple values in the attribute please?

A: You can use split() to turn that comma delimited string to an array, then indexOf to find a matching value in the array. Try this:
jQuery(document).ready(function($){
    var getday = new Date().getDay();
    var show = 'today';

    $(".cd-gallery ul li").each(function() {
        var running_days = $(this).data('day').split(',');
        if (running_days.indexOf(getday.toString()) != -1)
            $(this).addClass('today');
    });
});

Example fiddle
Note that getDay() returns the day of the week. Today being Friday, means it will return 5. If you want to get the day of the month (today being 17), use getDate().

A: You can split the values and match against the condition you were upto

   jQuery(document).ready(function(JQuery){
        var date = new Date();
        var getday = date.getDay();
        var show = 'today';

        jQuery(".cd-gallery ul li").each(function() {
            var running_days = JQuery(this).data('day');
            var arr = running_days.split(',');
            $.each(arr, function( index, value ) {
               alert(value)
          });

        });

    });

A: var str = '5,6,7'; // = JQuery(this).data('day');
var daysArray = str.split(',');
for(...) {
    ...
}

Or by indexOf as @Roy McCrossan mentioned. It's better to check the value, but. The day may need to be trimmed before comparing.

A: You can use this:

A: Simply use this selector to match the date in your data-day attribute.
jQuery(".cd-gallery li[data-day*=" + getday + "]").addClass("today");

Try this and let me know if it works for you :)


text:
Q: typing redux store using flowtype and flow-typed I'm trying to type the redux store like this : const s:Store<S,A>=createStore (todoApp) but I get
identifier Store ... Could not resolve name flow error
any idea how to fix this ?
I am using this flow typed declarations:
// flow-typed signature: ba132c96664f1a05288f3eb2272a3c35
// flow-typed version: c4bbd91cfc/redux_v3.x.x/flow_>=v0.33.x

declare module 'redux' {

  /*

    S = State
    A = Action

  */

  declare type Dispatch<A: { type: $Subtype<string> }> = (action: A) => A;

  declare type MiddlewareAPI<S, A> = {
    dispatch: Dispatch<A>;
    getState(): S;
  };

  declare type Store<S, A> = {
    // rewrite MiddlewareAPI members in order to get nicer error messages (intersections produce long messages)
    dispatch: Dispatch<A>;
    getState(): S;
    subscribe(listener: () => void): () => void;
    replaceReducer(nextReducer: Reducer<S, A>): void
  };

  declare type Reducer<S, A> = (state: S, action: A) => S;

  declare type Middleware<S, A> =
    (api: MiddlewareAPI<S, A>) =>
      (next: Dispatch<A>) => Dispatch<A>;

  declare type StoreCreator<S, A> = {
    (reducer: Reducer<S, A>, enhancer?: StoreEnhancer<S, A>): Store<S, A>;
    (reducer: Reducer<S, A>, preloadedState: S, enhancer?: StoreEnhancer<S, A>): Store<S, A>;
  };

  declare type StoreEnhancer<S, A> = (next: StoreCreator<S, A>) => StoreCreator<S, A>;

  declare function createStore<S, A>(reducer: Reducer<S, A>, enhancer?: StoreEnhancer<S, A>): Store<S, A>;
  declare function createStore<S, A>(reducer: Reducer<S, A>, preloadedState: S, enhancer?: StoreEnhancer<S, A>): Store<S, A>;

  declare function applyMiddleware<S, A>(...middlewares: Array<Middleware<S, A>>): StoreEnhancer<S, A>;

  declare type ActionCreator<A, B> = (...args: Array<B>) => A;
  declare type ActionCreators<K, A> = { [key: K]: ActionCreator<A, any> };

  declare function bindActionCreators<A, C: ActionCreator<A, any>>(actionCreator: C, dispatch: Dispatch<A>): C;
  declare function bindActionCreators<A, K, C: ActionCreators<K, A>>(actionCreators: C, dispatch: Dispatch<A>): C;

  declare function combineReducers<O: Object, A>(reducers: O): Reducer<$ObjMap<O, <S>(r: Reducer<S, any>) => S>, A>;

  declare function compose<S, A>(...fns: Array<StoreEnhancer<S, A>>): Function;

}

A: You need to import the type Store from the redux module. Example:
import { createStore } from 'redux';
import type { Store } from 'redux';

// ...

const s: Store<S, A> = createStore(todoApp)

For more information, you can refer to the documentation for importing/exporting types from modules.

A: This is an example how you can type reducers and store:
(using redux v4 and flow v0.108)
import { createStore, combineReducers } from 'redux';
import type { Action, Store } from 'redux';

type TodoState = $Exact<{
  +text: string;
  +completed: boolean;
  +id: number;
}>;

type TodoListState = TodoState[];
type VisibilityFilterState = 'SHOW_ACTIVE' | 'SHOW_ALL' | 'SHOW_COMPLETED';

const todoListReducer = (state: (TodoListState | void) = [], action: Action<any>): TodoListState => {
  // reducer code here
};

const visibilityFilterReducer = (state: (VisibilityFilterState | void) = 'SHOW_ALL', action: Action<any>) : VisibilityFilterState =>  {
  // reducer code here
}

type AppState = $Exact<{
  todoListState: TodoListState,
  visibilityFilterState: VisibilityFilterState
}>;

const appStateReducer: (AppState | void, Action<any>) => AppState = combineReducers({
  todoListState: todoListReducer,
  visibilityFilterState: visibilityFilterReducer
});

const store: Store<AppState, Action<any> = createStore(appStateReducer);


text:
Q: Possible Boolean Tests I am trying to create a for loops in C# to do all possible tests of 3 bool variables, but I can't figure out how to do it the something along the lines of ( a && b ) || c if a is True and b and c are False the whole statement would equal false.

A: Not sure if this is what you want, but with nested foreach, you can do this:
foreach (var a in new[] { false, true, })
  foreach (var b in new[] { false, true, })
    foreach (var c in new[] { false, true, })
    {
      // use a, b, and c here
    }

Or in a style preferred by a comment:
bool[] arr = { false, true, };
foreach (var a in arr)
  foreach (var b in arr)
    foreach (var c in arr)
    {
      // use a, b, and c here
    }

A: This version allows some flexibility to expand upon:
  for (int i = 0; i < 8; i++)
  {
    bool a = (i & 1) != 0;
    bool b = (i & 2) != 0;
    bool c = (i & 4) != 0;

    Console.WriteLine("a={0},b={1},c={2}", a, b, c);
  }


text:
Q: Prevent multiple instances of an Azure web job processing the same Queue message I noticed that multiple instances of my Web job are receiving the same message and end up acting on it. This is not the desired behavior. I would like multiple messages to be processed concurrently, however, I do not want the same message being processed by multiple instances of the web job.

*

*My web job is of the continuous running type.

*I use a QueueTrigger to receive the message and invoke the function

*My function runs for several hours.

I have looked into the JobHostConfiguration.BatchSize and MaxDequeue properties and I am not sure on these. I simply want a single instance processing a message and that it could take several hours to complete.
This is what I see in the web job logs indicating the message is received twice.

[01/24/2017 16:17:30 > 7e0338: INFO] Executing:
'Functions.RunExperiment' - Reason: 'New queue message detected on
'runexperiment'.'
[01/24/2017 16:17:30 > 7e0338: INFO] Executing:
'Functions.RunExperiment' - Reason: 'New queue message detected on
'runexperiment'.'

A: According to the official document, if we use Azure queue storage in the WebJob on the multiple instance, we no need to write code to prevent multiple instances to processing the same queue message.

The WebJobs SDK queue trigger automatically prevents a function from processing a queue message multiple times; functions do not have to be written to be idempote.

I deployed a WebJob on the 2 instances WebApp, It also works correctly(not execute twice with same queue message). It could run on the 2 instances and there is no duplicate executed message.
So it is very odd that the queue message is executed twice, please have a try to debug it whether there are 2 queue messages that have the same content are triggered.
The following is my debug code. I wrote the message that with the executed time and instance id info into another queue.
public static void ProcessQueueMessage([QueueTrigger("queue")] string message, [Queue("logqueue")] out string newMessage, TextWriter log)
    {
        string instance = Environment.GetEnvironmentVariable("WEBSITE_INSTANCE_ID");
        string newMsg = $"WEBSITE_INSTANCE_ID:{instance}, timestamp:{DateTime.Now}, Message:{message}";
        log.WriteLine(newMsg);
        Console.WriteLine(newMsg);
        newMessage = newMsg;
    }
}

A: I had the same issue of a single message processed multiple times at the same time. The issue disappeared as soon as I have set the MaxPollingInterval property...


text:
Q: Tool for mass adding properties to many xml files? I have some xml that looks like this in each  report:
Header
Cell
/Cell
Cell
/Cell
...
/Header

In each cell I need to add:
                <property name="borderBottomColor">#E1E1E1</property>
                <property name="borderBottomStyle">solid</property>
                <property name="borderBottomWidth">thin</property>

This will take me about a week to do manually.
Is there a tool that could do this?
Thanks

A: You can try XMLStarlet - an open source, command-line XML editor.
It allows you for example to add or update nodes in an XML document. Which nodes are updated can be specified by an XPath expression.

A: It's hard to give an exact answer without actual sample XML input (and a full output example), but you could use XSLT
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Cell">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
            <property name="borderBottomColor">#E1E1E1</property>
            <property name="borderBottomStyle">solid</property>
            <property name="borderBottomWidth">thin</property>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

You could run this with Xalan or Saxon from the command line.


text:
Q: How to dynmically append html in td I have a tr like this

   <input id="checked1" type="checkbox" class="cd" value="1" style="margin:6px 0 0 0;">
   Staff Courtesy

      <select name="questionType" id="questionType" class="qType QSelect" style="padding:3px;">
         <option value="">--Select--</option>
         <option value="1">text</option>
         <option value="2">rating</option>
         <option value="3">boolean</option>
         <option class="show-checkboxes" value="4">option</option>
      </select>

   Enter Some Text
   <input type="hidden" id="optionInputa1">

Initially the 3rd td does not show anything but if the drop down changes then some text appears in the 3rd td
For example if text is selected then in the 3rd td it will show place for text.The code for it is as below
var option='Get Options';
     var txt = 'Enter Some Text';
     var bool = 'Yes or No';
     var rating='place for rating';
     $('#addNew .QSelect').change(function () { //alert(this.value);
         if (this.value == '4') $(this).closest('tr').find('.out').html(option);
         if (this.value == '1') $(this).closest('tr').find('.out').html(txt);
         if (this.value == '3') $(this).closest('tr').find('.out').html(bool);
         if (this.value == '2') $(this).closest('tr').find('.out').html(rating);
     });

     $('#addNew .QSelect').change(function() {
            var cbs = $(this).closest('td').next().children();
            if ($('.show-checkboxes', $(this)).is(':selected')) {
                $(cbs).show();
            } else {
                $(cbs).hide();
            }
        }).trigger('change');

        $('#addNew .cd').change(function() {
            var checked = $(this).is(':checked');
           // $('#optionSave').removeAttr('disabled');
           if ($(".cd:checkbox:checked").length > 0)
{

               $('#optionSave').removeAttr('disabled');
}
else
{

    $('#optionSave').attr('disabled',true);
}
            $(this).closest('td').siblings().find('select, input').prop('disabled', !checked);
        }).trigger('change');
}

My problem
I want to programatically set the value of dropdown.For example if I want to set the drop to text then I have to set it value to 1.
This is the code for it
$.each(data1.savedQuestionTypesList, function(index, currQueTyp) {
                    console.log("queeeeeeeeeeeee  "+currQueTyp.pqid.qid.id + "qtid name"+currQueTyp.qtid.name);
                    $('#checked'+currQueTyp.pqid.qid.id).closest('tr').find('select').val(currQueTyp.qtid.id);

                });

So as the drop down value changes so also the the 3rd td changes.
For example
in the above each loop if currQueTyp.pqid.qid.id=1 and currQueTyp.qtid.id=1 then the dropdown is changed to text and in the 3rd td place for text will appear.
But if I do with a button then why the 3rd td does not change.
For example there is button
<button type="button" id="testButton">test</button> and upon clicking I want to change the drop down value

$('#testButton').click(function(){

                    $('#checked1').closest('tr').find('select').val(1);

});

So here the dropdown value changes but the 3rd td does not change
Fiddle here

A: Working Demo
Use this for the button event,

*

*In your case #checked1 was a totally wrong selector. You had multiple checkboxes with same Ids. That won't work. Use class selector in such case.

*And you need the checked checkbox so :checked.

$('#testButton').click(function(){

    $('.cd:checked').closest('tr').find('select').val(1).change();

});


text:
Q: about Monit and PHP Excuse me, may I ask in linux, is there any way to call php code from the monitrc file of Monit?
THanks

A: Yes. You need to use the following command to execute scripts:
php /full/path/to/your/script.php


text:
Q: Why is Orthanc so indestructible? The tower of Orthanc is said to have been impenetrable:

By the next day, only the tower of Orthanc remained, as it was hewn of one piece of impenetrable rock...
-"Orthanc", The One Wiki to Rule Them All.

It survives an attack on it by the Ents and has seemingly lasted many thousands of years; it was built in the Second Age.
It is also said that even though it was the Númenórean men who built the tower, it was as though something else was involved:

it was fashioned by the builders of old who smoothed the Ring of Isengard, and yet it seemed a thing not of the craft of Men, but riven from the bones of the earth in the ancient torment of the hills.
-"Orthanc", The One Wiki to Rule Them All.

What makes the tower so impenetrable?

A: It's indestructible because of magic.
From The Two Towers, "Flotsam and Jetsam":

"Many of the Ents were hurling themselves against the Orthanc-rock; but that defeated them. It is very smooth and hard. Some wizardry is in it, perhaps, older and stronger than Saruman's"

It was built by the people of the Second Age who had access to more powerful magic than they do in the time of LotR. If they could enchant palantíri to communicate instantly over vast distances, then why not a tower to be really strong?
As a side note, it is strong for the same reason the walls of Gondor are so strong. I don't have a quote for this but they are nigh indestructible.
From The Return of the King, "The Siege of Gondor":

For the main wall of the City was of great height and marvellous thickness, built ere the power and craft of Númenor waned in exile; and its outward face was like to the Tower of Orthanc, hard and dark and smooth, unconquerable by steel or fire, unbreakable except by some convulsion that would rend the very earth on which it stood.

A: I've read before that the origins are volcanic, though the only reference I could quickly find is from a game:

The impenetrable tower of Orthanc forms the core of the defenses, with a vast circular wall one mile in diameter providing the first line of security.  The earth itself formed the citadel, for the outer ring is a volcanic cone shaped by the Men of Númenor with the help of Hill-giants and the spire of Orthanc is in fact a pillar of glossy black volcanic rock known as laen.

In which case the hard part of the Númenórean work was cutting rooms into it.

A: The implication is that it's made of some kind of heavy volcanic rock;

For the main wall of the City was of great height and marvellous thickness, built ere the power and craft of Númenor waned in exile; and its outward face was like to the Tower of Orthanc, hard and dark and smooth, unconquerable by steel or fire, unbreakable except by some convulsion that would rend the very earth on which it stood.
- Return of the King

and

They came now to the foot of Orthanc. It was black, and the rock gleamed as if it were wet. The many faces of the stone had sharp edges as though they had been newly chiselled. A few scorings, and small flake-like splinters near the base, were all the marks that it bore of the fury of the Ents.
- The Two Towers

As far as the movies are concerned, according to the LotR "Making of" Appendices, the production crew proceeded on the assumption that the tower was comprised of obsidian, a substance that has long been considered (however erroneously) to be unbreakable:

According to Richard Taylor, the painting of Alan Lee made it look as if the tower walls were chipped out of black obsidian (a kind of volcanic glass). In the FOTR Appendices he explains how the miniature technicians of Weta built up their model by carving every single element out of micro-crystalline wax. Eventually, the 13 feet high movie tower was cast into resin with the aid of a massive silicon mould.


text:
Q: Accessing ComInterface to VB6 OCX Control with win32 handle in c# I'm at the moment automating the test for a legacy application developed in vb6, which uses a GridEx2000b Control from Janus Systems.
For doing this I'm using Ranorex as my favorite tool for developing the test automation, so that I can develop the test code using c#.
My problem now is to automate the GridEx 2000b control, which Ranorex out of-the-box don't have any support for. Therefore I'm trying to figure out a solution where I can reference the GrixEx control using the Win32 handle I can find for the control, so I can use the ComInterface from the component to navigate the automate the control.
I have an idea of a solution but I cannot figure out how to do it, where I hope that you guys would be able help me.
The pseudo code for the problem:
using GridEX20;

class GridExWrapper
{
    public GridEX20.GridEXClass Instance;

    public GridExWrapper(IntPtr win32handle)
    {
        Instance = (GridEX20.GridEXClass)Win32ControlUtilities.GetControlReference(win32Handle);
    }
}

class Win32ControlUtilities
{
    public static SomeKindOfHandle GetControlReference(IntPtr win32Handle)
    {
        ...
        ...
        ...
    }
}

I'll get the win32handle from Ranorex or some other spy tool.
Then I can use the GridExWrapper like this.
using NUnit.Framework;

class Program
{
    [Test]
    public void control_should_have_9_items()
    {
        /// Get win32 handle from Ranorex
        IntPtr win32handle = XXXXXX;
        int expectedItemCount = 9;

        GridEXClass control = new GridExWrapper(win32handle);
        Assert.AreEqual(expectedItemCount, control.ItemCount);
    }

}

A: You could try the Microsoft UI Automation library (System.Windows.Automation) for identifying the properties of the control. Sometimes even if Ranorex fails, MSUIA manages to recognize the control as it looks into native properties of a control for identification. Not guaranteed but worth a try.Here is a link to a tutorial on using MSUIA.


text:
Q: Understanding double pointer to an array in C I have been learning C for couple of months and I came across a question which is given below.
#include <stdio.h>

int main() {
    int a[2][2] = {{1,2}, {3,4}};
    int (**p)[2] = &a;

    for (int i=0; i<2; ++i) {
        for (int j=0; j<2; ++j) {
            printf("%d %u\n", a[i][j], (*(a+i) + j));
        }
    }

    for (int i=0; i<4; ++i) {
        printf("%d %u\n", *(*p + i), (*p + i));
    }

    printf("%u\n", p);
    printf("%u\n", p+1);
    printf("%u\n", p+2);
    printf("%u\n", p+3);
    printf("%u\n", *p);
    printf("%u\n", *p+1);
    printf("%u\n", *p+2);
    printf("%u\n", *p+3);
    puts("");
}

The output that I am getting on my machine is as follows:
1 3751802992
2 3751802996
3 3751803000
4 3751803004
1 1
9 9
17 17
25 25
3751802992
3751803000
3751803008
3751803016
1
9
17
25

I understand the first four lines of the output where the elements of the 2D array and their respective addresses is getting printed but I have absolutely no clue how the other outputs are happening.
I checked in an online IDE and there also I am getting the same output except the addresses which obviously will differ.
I know that int (**p)[2] is incomparable pointer type to a[2][2] which is a (int *)[2] data type.
But still I want to understand how the p pointer is working.
Can someone please help me understand how this is happening?
I have been eagerly waiting to get the logic behind the code outputs.
I am extremely sorry for the long code snippet and the long output sequence.
Thanks in advance.
N.B - I know that the code is producing a lot of warnings but I want to get the core idea about p.

A: The problem with this code starts right here:
int main() {
    int a[2][2] = {{1,2}, {3,4}};
    int (**p)[2] = &a; // <-- Invalid conversion, undefined behaviour

    // warning: incompatible pointer types initializing 'int (**)[2]' with an expression of type 'int (*)[2][2]' [-Wincompatible-pointer-types]

    // ... Everything past here is undefined behaviour
}

There's a huge difference between int** and what you're attempting to cast, one big enough that this conversion isn't possible.
int** means, specifically, a structure where it's an array of int*, or pointers. Treating int[2] as a pointer is going to be a mess. That any of this code even semi-works is hard to explain. It's the compiler trying to make the best of a bad situation.

A: I introduced a macro LEN to calculate your array sizes instead of hard-coping the magic numbers, fixed the declaration of p, changed the unsigned format %u to signed %d as you were printed signed values, the last loop, I am sure what the 2nd thing you were trying to print so left it out, and the last section of print statements were pointers so used %p for those in a loop instead of duplicating the code:
#include <stdio.h>

#define LEN(a) sizeof(a) / sizeof(*a)

int main() {
    int a[2][2] = {{1,2}, {3,4}};
    int (*p)[2] = a;

    for (int i=0; i < LEN(a); i++) {
        for (int j = 0; j < LEN(*a); j++) {
            printf("%d %d\n", a[i][j], *(*(a + i) + j));
        }
    }

    for (int i=0; i < LEN(a) * LEN(*a); i++) {
        printf("%d\n", *(*p + i));
    }

    for(int i = 0; i < LEN(a) * LEN(*a); i++) {
        printf("%p\n", p + i);
    }

    for(int i = 0; i < LEN(a) * LEN(*a); i++) {
        printf("%p\n", (void *) *(p + i));
    }

    puts("");
}

A: This is a problem:
int (**p)[2] = &a; // int (**)[2] = int (*)[2][2]

The type of &a is int (*)[2][2], not int (**)[2].  Your pointer declaration should be
int (*p)[2][2] = &a;

Unless it is the operand of the sizeof or unary & operators or is a string literal used to initialize a character array in a declaration, an expression of type "N-element array of T will be converted, or "decay", to an expression of type "pointer to T" and the value of the expression will be the address of the first element of the array.
The expression a "decays" from type "2-element array of 2-element array of int" (int [2][2]) to "pointer to 2-element array of int" (int (*)[2]).  However, since a is the operand of the unary & operator that conversion doesn't take place, so &a has type "pointer to 2-element array of 2-element array of int" (int (*)[2][2]).  Thus,
   p  == &a
 (*p) ==  a

  (*p) + i  ==   a + i  == &(*p)[i] == &a[i]
*((*p) + i) == *(a + i) ==  (*p)[i] ==  a[i]

  *((*p) + i) + j  ==   *(a + i) + j  == &(*p)[i][j] == &a[i][j]
*(*((*p) + i) + j) == *(*(a + i) + j) ==  (*p)[i][j] ==  a[i][j]

A: A pointer is used to store the address of variables. So, when we define a pointer to pointer, the first pointer is used to store the address of the second pointer. Thus it is known as double pointers.
EXAMPLE:
int main() {
   int integerValue = 84;
   int *pointer1;
   int **pointer2;
   pointer1 = &integerValue;
   pointer2= &pointer1;
   printf("Value of integer = %d\n", integerValue);
   printf("Value of integer using single pointer = %d\n", *pointer1);
   printf("Value of integer using double pointer = %d\n", **pointer2);
   return 0;
}

OUTPUT:
Value of integer = 84
Value of integer using single pointer = 84
Value of integer using double pointer = 84


text:
Q: Python Django Template cannot get name from model function While I understood that I can call a function definition from our models, I can't seem to extract the file name of my uploaded document. Below I tried the following template format but either results from my desired output:
.html Version 1
<form action="." method="GET">
{% if documents %}

      {% for document in documents %}

 {{ document.docfile.filename }}
        <input type = "submit" name="load-data" value="Add to Layer"/>

      {% endfor %}

Result: It just shows the button.
.html Version 2
<form action="." method="GET">
{% if documents %}

      {% for document in documents %}

 {{ document.filename }}
        <input type = "submit" name="load-data" value="Add to Layer"/>

      {% endfor %}

Result: It just shows the button.
.html Version 3
<form action="." method="GET">
{% if documents %}

      {% for document in documents %}

 {{ document.docfile.name }}
        <input type = "submit" name="load-data" value="Add to Layer"/>

      {% endfor %}

Result: Prints the complete pathname (eg: /documents/2016/10/08/filename.csv) together with the button
Here's the rest of my code:
models.py
class Document(models.Model):
     docfile = models.FileField(upload_to='document/%Y/%m/%d')

     def filename(self):
        return os.path.basename(self.file.name)

views.py
documents = Document.objects.all()
return render(request, 'gridlock/upload-data.html',
              {
               'documents' : documents,
               'form': form
              })

I hope someone can explain why everything I tried:
{{ document.docfile.filename }} or {{document.file.filename}} or {{document.filename}} won't work either for me? Thanks!

A: I think you got pretty close with {{ document.filename }}, except in your models you need to change
def filename(self):
    return os.path.basename(self.file.name)

into
def filename(self):
    # try printing the filename here to see if it works
    print (os.path.basename(self.docfile.name))
    return os.path.basename(self.docfile.name)

in your models the field is called docfile, so you need to use self.docfile to get its value.
source: django filefield return filename only in template


text:
Q: Issue with multiple bootstrap-multiselect on page On Page I have 3 multiple-select-boxes. Only for 3rd one I have additional logic (custom onchange event).
So first 2 I just initialize with line of code :
$('.multiselect').multiselect();

But when I've tried to add custom logic for 3rd select - it doesn't work.
$('#RegionIds').multiselect({
    onChange: function(option, checked) {
        alert('changed value' + $(option).val());
    }
});

Alert never appears in this case.

Update : JsBIN Example : https://jsbin.com/voquhegode/edit?html,js,output

Update 2 :
Thanks for replies. But I've found another issue with multiple selects.
https://jsfiddle.net/x6z6w0n8/7/ In case I want to set selected values on initialize step, I saw one additional select. This causes line of code where I manualy set selected values
$(select).multiselect('select', jsonArr[i].Item1);

A: You should use $('.multiselect').multiselect(); in the end like here fiddle Because you cover other elements with custom logic which has the same class .multiselect
$('#example-onInitialized').multiselect({
  onChange: function(option, checked, select) {
    var changedVal = $(option).val();
    if (changedVal < 3) {
      if (checked == true) {
        console.log('less');
      } else if (checked == false) {
        console.log('more');
      }
    }
  }
});
$('#RegionIds').multiselect({
    onChange: function(option, checked) {
        console.log('changed');
    }
});
$('.multiple').multiselect();

Or if every select has custom logic call multiselect() for concret IDs.


text:
Q: How to localize Autolayout Constraint added programmatically in swift In my swift code I am using autolayout constraints. Some are added directly from storyboard and some are added programmatically on UIScrollView.
When the app runs in arabic version (RTL direction) the autolayout constraints added from storyboard they switch to RTL direction automatically without me doing any effort BUT the ones added programmatically on UIScrollView are not being flipped.
This is an example of my constraints being added on the UISCrollView:
        var previousView: UIView = self.productsScrollView

        for productObj in productsArray {

            let productViewObj: ProductView = ProductView(frame: CGRectMake(0, 0, self.productsScrollView.frame.size.width, self.productsScrollView.frame.size.height), productObj: productObj)

            productViewObj.translatesAutoresizingMaskIntoConstraints = false
            self.productsScrollView.addSubview(productViewObj)

            // Left Constraint
            let leftConstraint = NSLayoutConstraint(item: productViewObj,
                attribute: .Left,
                relatedBy: .Equal,
                toItem: previousView,
                attribute: (previousView === self.productsScrollView) ? .Left : .Right,
                multiplier: 1.0,
                constant: 0.0);
            self.productsScrollView .addConstraint(leftConstraint)

            // Top Constraint
            let topConstraint = NSLayoutConstraint(item: productViewObj,
                attribute: .Top,
                relatedBy: .Equal,
                toItem: self.productsScrollView,
                attribute: .Top,
                multiplier: 1.0,
                constant: 0.0);
            self.productsScrollView .addConstraint(topConstraint)

            previousView = productViewObj

... // width, height constraints

}

...// and left constraint (for the last item) is added here

    self.productsScrollView.layoutIfNeeded()

Is there anything I am missing in my code? Or should I check for the language and flip the constraints manually?
Thanks

A: You should use .Leading instead of .Left and .Trailing instead of .Right for things which should change direction with the language direction. That's the whole purpose of .Leading and .Trailing.


text:
Q: powershell get the bigger disk freespace I can get all my logical drives  and the corresponding freespace with this script:
$elements = get-WmiObject Win32_LogicalDisk
$array=@()

foreach ( $drive in $elements ) {
    $freespace = $drive.freespace / (1024*1024*1024)
    $freespace = [math]::round($freespace, 1)

    $name=$drive.Name
    $d=New-Object PSObject

    $d | Add-Member -Name Drive -MemberType NoteProperty -Value $name
    $d | Add-Member -Name Free_Space -MemberType NoteProperty -Value $freespace

    $array+=$d

 }

The problem is that I can't figure out how to manipulate my $array to return the name of the drive with the bigger freespace, with measure -Maximum for example

A: Try this:
$LogicalDisks = get-WmiObject Win32_LogicalDisk

$MostSpace = 0
$MostName = "None"

foreach ( $drive in $LogicalDisks ) {

$FreeSpace = $drive.FreeSpace / (1024*1024*1024)

$FreeSpace = [math]::round($FreeSpace, 1)

if ($FreeSpace -gt $MostSpace) {
  $MostSpace = $FreeSpace
  $MostName = $Drive.Name
  }

}

Write-Host $MostName

It'll put the drive letter into $MostName and then you can do what you want with it.


text:
Q: Parallelogram with expand/collapse animation (Warframe reference) I want to make Parallelogram with expand/collapse animation (I believe it kinda overlaps one another).
This is the reference design base from Warframe game's launcher.
With the help of friend, we have the animation. However, we are not able to make the Parallelogram work properly (it sketch the image).
Here is our testing code of animation (please check the link. This is just Javascript due to requirement to post code.
let isInfoDivCreated = false;
let isResetClicked = false;
let clickedSection;

function createRuntimeInfoDiv(id) {
    if (isInfoDivCreated && id !== clickedSection) {
        if (document.getElementById("pImg1" + "infoDiv")) {
            document.getElementById("pImg1" + "infoDiv").remove();
        }
        if (document.getElementById("pImg2" + "infoDiv")) {
            document.getElementById("pImg2" + "infoDiv").remove();
        }
        if (document.getElementById("pImg3" + "infoDiv")) {
            document.getElementById("pImg3" + "infoDiv").remove();
        }
        if (document.getElementById("pImg4" + "infoDiv")) {
            document.getElementById("pImg4" + "infoDiv").remove();
        }
        isInfoDivCreated = false;
    }
    if (!isInfoDivCreated && !isResetClicked) {
        clickedSection = id;
        var infoDiv = document.createElement('div');
        infoDiv.id = id + "infoDiv";
        infoDiv.setAttribute('class', 'infoDiv');
        isInfoDivCreated = true;
        if (id === "pImg1") {
        let innerInfoDiv = document.createElement('div');
        innerInfoDiv.id = id + "innerInfoDiv";
        innerInfoDiv.setAttribute('class', 'innerInfoDiv');

            let info = document.createElement("p");
            info.innerHTML = "Test"
            let info1 = document.createElement("p");
            info1.innerHTML = "Test"
            let info2 = document.createElement("p");
            info2.innerHTML = "Test"
            let button = document.createElement("button1");
            button.innerHTML = "Test Button";
            button.addEventListener("click", function () {
                window.parent.location.href = '';
            });
            let backImage = document.createElement("img");
            backImage.setAttribute('src', 'https://static.wixstatic.com/media/b8044a_2f1720c9043e4f94bee61cab482f5664~mv2.png');
            backImage.addEventListener('click', function () {
                resetMe();
            });
            backImage.setAttribute('class', 'backbtnImage');

            let title = document.createElement("span");
            title.innerHTML = "Test Title";
            title.setAttribute('class', 'headline');
            infoDiv.appendChild(backImage);
            infoDiv.appendChild(title);

            infoDiv.appendChild(info);
            infoDiv.appendChild(info1);
            infoDiv.appendChild(info2);
            infoDiv.appendChild(button);
            document.getElementById(id).appendChild(infoDiv);
        }
        if (id === "pImg2") {
            let info = document.createElement("p");
            info.innerHTML = "Test "
            let info1 = document.createElement("p");
            info1.innerHTML = "Test"
            let info2 = document.createElement("p");
            info2.innerHTML = ">> Test"
            let info3 = document.createElement("p");
            info3.innerHTML = ">> Test"
            let info4 = document.createElement("p");
            info4.innerHTML = ">> Test"

            let button = document.createElement("button2");
            button.innerHTML = "Test Button";
            button.addEventListener("click", function () {
                window.parent.location.href = '';
            });

            let title = document.createElement("span");
            title.innerHTML = "Test Button";
            title.setAttribute('class', 'headline');
            let backImage = document.createElement("img");
            backImage.setAttribute('src', 'https://static.wixstatic.com/media/b8044a_2f1720c9043e4f94bee61cab482f5664~mv2.png');
            backImage.addEventListener('click', function () {
                resetMe();
            });
            backImage.setAttribute('class', 'backbtnImage');
            infoDiv.appendChild(backImage);
            infoDiv.appendChild(title);
            infoDiv.appendChild(info);
            infoDiv.appendChild(info1);
            infoDiv.appendChild(info2);
            infoDiv.appendChild(info3);
            infoDiv.appendChild(info4);
            infoDiv.appendChild(button);
            document.getElementById(id).appendChild(infoDiv);
        }
        if (id === "pImg3") {
            let info = document.createElement("p");
            info.innerHTML = "Test"
            let info1 = document.createElement("p");
            info1.innerHTML = ">> Test";
            let info2 = document.createElement("p");
            info2.innerHTML = ">> Test";
            let info3 = document.createElement("p");
            info3.innerHTML = ">> Test";
            let button = document.createElement("button3");
            button.innerHTML = "Test Button";
            button.addEventListener("click", function () {
                window.parent.location.href = '';
            });
            let backImage = document.createElement("img");
            backImage.setAttribute('src', 'https://static.wixstatic.com/media/b8044a_2f1720c9043e4f94bee61cab482f5664~mv2.png');
            backImage.addEventListener('click', function () {
                resetMe();
            });
            backImage.setAttribute('class', 'backbtnImage');

            let title = document.createElement("span");
            title.innerHTML = "Test Title";
            title.setAttribute('class', 'headline');
            infoDiv.appendChild(backImage);
            infoDiv.appendChild(title);
            infoDiv.appendChild(info);
            infoDiv.appendChild(info1);
            infoDiv.appendChild(info2);
            infoDiv.appendChild(info3);
            infoDiv.appendChild(button);
            document.getElementById(id).appendChild(infoDiv);
        }
        if (id === "pImg4") {

            let info = document.createElement("p");
            info.innerHTML =
                "Test"
            let info1 = document.createElement("p");
            info1.innerHTML ="Test"

            let button = document.createElement("button4");
            button.innerHTML = "Test Button";
            button.addEventListener("click", function () {
                window.parent.location.href = '';
            });
            let title = document.createElement("span");
            title.innerHTML = "Test Title";
            title.setAttribute('class', 'headline');
            let backImage = document.createElement("img");
            backImage.setAttribute('src', 'https://static.wixstatic.com/media/b8044a_2f1720c9043e4f94bee61cab482f5664~mv2.png');
            backImage.addEventListener('click', function () {
                resetMe();
            });
            backImage.setAttribute('class', 'backbtnImage');
            infoDiv.appendChild(backImage);
            infoDiv.appendChild(title);
            infoDiv.appendChild(info);
            infoDiv.appendChild(info1);
            infoDiv.appendChild(button);
            document.getElementById(id).appendChild(infoDiv);
        }

    }
    isResetClicked = false;
}

function resetMe() {
    if (isInfoDivCreated) {
        if (document.getElementById("pImg1" + "infoDiv")) {
            document.getElementById("pImg1" + "infoDiv").remove();
        }
        if (document.getElementById("pImg2" + "infoDiv")) {
            document.getElementById("pImg2" + "infoDiv").remove();
        }
        if (document.getElementById("pImg3" + "infoDiv")) {
            document.getElementById("pImg3" + "infoDiv").remove();
        }
        if (document.getElementById("pImg4" + "infoDiv")) {
            document.getElementById("pImg4" + "infoDiv").remove();
        }
    }
    isResetClicked = true;
    clickedSection = ""
}

I made a research and  made this one. But the combination caused chaos to the code.

A: This simple html/css might help you.

.wrapper {
  max-width:600px;
  height:300px;
  overflow:hidden;
  display:flex;
  background-image: url(http://www.personal.psu.edu/wzz5072/mini.jpg);
}
.imgwrapper {
  width:150px;
  height:300px;
  overflow:hidden;
  transform:skewx(30deg);
  position:relative;
  transition: width .4s ease-in-out;
  transform-origin:top top;
}
.imgwrapper:hover {
  width:100%;
  cursor:pointer;
}
.img-responsive {
  position:absolute;
  width:auto;
  height:100%;
  left:-90px;
  top:0;
  transform:skewx(-30deg) scale(1);
  transition: transform 1s ease-in-out;
}
.imgwrapper:hover .img-responsive {
  transform:skewx(-30deg) scale(1.2);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

A: Try clip-path https://developer.mozilla.org/ru/docs/Web/CSS/clip-path
.style_prevu_kit {
    -webkit-clip-path: polygon(25% 0%, 100% 0%, 75% 100%, 0% 100%);
    clip-path: polygon(25% 0%, 100% 0%, 75% 100%, 0% 100%);
    margin: 0 -5%;
}


text:
Q: Python - Run multiple python scripts from main file I am making a python script, and from the python script I must launch multiple python scripts that must run all at one time.  It would be preferred for the other scripts to run in the background and feed the input back to the main console.  This must work on all major OSes.  Also, it is critical to run them simotaneously, otherwise I would use defs.
Running python 2.7.8, by the way.
Update:
Sorry for title mismatch.  Cookies glitched or something.  I currently have a main script, which i need to run several more python scripts from all at once, and return the output live to the main window.  If you can think of another way that is os-inspecific that can do that, let me know!
Update 2:
I found a solution:
        var=subprocess.Popen(['python', 'file.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        for line in favTL.stdout"
            print line

A: Have you looked into the python thread module?
thread.start_new_thread(function, args[, kwargs])

will start a new thread in parallel. You can either import the other python files and call the specific functions you want, or run the whole script with
subprocess.call( ["python", "file.py"] )

...though making shell calls will be slightly less portable between OS's.


text:
Q: How to get gps.h into a Yocto recipe build? I've built a simple recipe which works as long as I don't need gps.h:
recipes/foo (dunfell) $ cat foo_3.0.0.bb
DESCRIPTION = "FOO Daemon"
LICENSE = "CLOSED"

SRC_URI = " file://*.* \
    "
S = "${WORKDIR}"

INSANE_SKIP_${PN} = "ldflags"
INHIBIT_PACKAGE_DEBUG_SPLIT = "1"
INHIBIT_PACKAGE_STRIP = "1"

do_compile() {
    cd ${S}/src
    make
    cp foo ~/
    cd -
}

do_install() {
    install -d ${D}${bindir}
    install -m 0755 foo ${D}${bindir}
}

gps.h is in /usr/include on my local machine, but as Yocto is cross-compiling it provides a reasonable explanation of why it can't use the local /usr/include/gps.h:
cc1: error: include location "/usr/include" is unsafe for cross-compilation [-Werror=poison-system-directories]
foo.c:54:10: fatal error: gps.h: No such file or directory
   54 | #include <gps.h>
      |          ^~~~~~~
cc1: all warnings being treated as errors

I've tried IMAGE_INSTALL_append " libgps-dev" and " gps-lib-dev" in my layer.conf but neither of those work.
How can I get the gps.h header into my Yocto project/recipe at build time?

A: Let me copy your recipe and add some comments first:
DESCRIPTION = "FOO Daemon"
LICENSE = "CLOSED"

# --- COMMENT ---
# It is not recommended to use "*" with SRC_URI,
# as Yocto will not keep track of your files if you edit them
# so it will never rebuild automaticall after a change
# Best practice is to sepecify the local files like:
# SRC_URI = "file://src"
# This will make bitbake unpacks the "src" folder into ${WORKDIR}
# --- COMMENT ---
SRC_URI = " file://*.* \
    "

# --- COMMENT ---
# The ${S} variable is the defautl workind directory for compilation tasks,
# do_configure, do_compile, ...,
# So, if you have "src" folder that will be unpacked into ${WORKDIR}
# you need to set S to that:
# S = "${WORKDIR}/src"
# --- COMMENT ---
S = "${WORKDIR}"

INSANE_SKIP_${PN} = "ldflags"
INHIBIT_PACKAGE_DEBUG_SPLIT = "1"
INHIBIT_PACKAGE_STRIP = "1"

# --- COMMENT ---
# If your project has a "Makefile" you can use the "autotools" class
# it runs oe_runmake automatically
# inherit autotools
# If you want to copy the output to your home directory you can do it in "do_install"
# If you use autotools you do not need do_compile
# --- COMMENT ---
do_compile() {
    cd ${S}/src
    make
    cp foo ~/
    cd -
}

do_install() {
    install -d ${D}${bindir}
    install -m 0755 foo ${D}${bindir}
}

# --- COMMENT ---
# Do not forget to specify your output files into FILES for do_package to work well
# FILES_${PN} = "${bindir}/foo"
# --- COMMENT ---

Now, after dealing with that, if your recipe requires something at build-time, than the dependency needs to exist in the same recipe's workding directory, because if you are adding libgps into IMAGE_INSTALL it will be present in the rootfs but not during your build time.
So, to do that, you need to specify the dependencies recipe with DEPENDS.
I have looked for gps.h and I found it packages with gpsd recipe.
So, try:
DEPENDS += "gpsd"

So, the final recipe would look like the following:
DESCRIPTION = "FOO Daemon"
LICENSE = "CLOSED"

SRC_URI = "file://src"

S = "${WORKDIR}/src"

DEPENDS += "gpsd"

inherit autotools

do_install(){
    install -d ${D}${bindir}
    install -m 0755 foo ${D}${bindir}
    cp foo ~/
}

FILES_${PN} = "${bindir}/foo"

The only thing left is to test.


text:
Q: WebSockets, UDP, and benchmarks HTML5 websockets currently use a form of TCP communication. However, for real-time games, TCP just won't cut it (and is great reason to use some other platform, like native). As I probably need UDP to continue a project, I'd like to know if the specs for HTML6 or whatever will support UDP?
Also, are there any reliable benchmarks for WebSockets that would compare the WS protocol to a  low-level, direct socket protocol?

A: There's no UDP support for Websockets (there really should be), however you can apparently use WebRTC's RTCDataChannel API for UDP-like communication. There's a good article here:
http://www.html5rocks.com/en/tutorials/webrtc/datachannels/
RTCDataChannel actually uses SCTP which has configurable reliability and ordered delivery. You can get it to act like UDP by telling it to deliver messages unordered, and setting the maximum number of retransmits to 0.
I haven't tried any of this though.

A: I would recommend developing your game using WebSockets on a local wired network and then moving to the WebRTC Data Channel API once it is available. As @oberstet correctly notes, WebSocket average latencies are basically equivalent to raw TCP or UDP, especially on a local network, so it should be fine for you development phase. The WebRTC Data Channel API is designed to be very similar to WebSockets (once the connection is established) so it should be fairly simple to integrate once it is widely available.
Your question implies that UDP is probably what you want for a low latency game and there is truth to that. You may be aware of this already since you are writing a game, but for those that aren't, here is a quick primer on TCP vs UDP for real-time games:
TCP is an in-order, reliable transport mechanism and UDP is best-effort. TCP will deliver all the data that is sent and in the order that it was sent. UDP packets are sent as they arrive, may be out of order, and may have gaps (on a congested network, UDP packets are dropped before TCP packets). TCP sounds like a big improvement, and it is for most types of network traffic, but those features come at a cost: a delayed or dropped packet causes all the following packets to be delayed as well (to guarantee in-order delivery).
Real-time games generally can't tolerate the type of delays that can result from TCP sockets so they use UDP for most of the game traffic and have mechanisms to deal with dropped and out-of-order data (e.g. adding sequence numbers to the payload data). It's not such a big deal if you miss one position update of the enemy player because a couple of milliseconds later you will receive another position update (and probably won't even notice). But if you don't get position updates for 500ms and then suddenly get them all out once, that results in terrible game play.
All that said, on a local wired network, packets are almost never delayed or dropped and so TCP is perfectly fine as an initial development target. Once the WebRTC Data Channel API is available then you might consider moving to that. The current proposal has configurable reliability based on retries or timers.
Here are some references:

*

*WebRTC Introduction

*WebRTC FAQ

*WebRTC Data Channel Proposal

A:
I'd like to know if the specs for HTML6 or whatever will support UDP?

WebSockets won't.  One of the benefits of WebSockets is that it piggybacks the existing HTTP connection.  This means that to proxies and firewalls WebSockets looks like HTTP so they don't get blocked.
It's likely arbitrary UDP connections will never be part of any web specification because of security concerns.  The closest thing to what you're after will likely come as part of WebRTC and it's associated JSEP protocol.

are there any reliable benchmarks ... that .. compare the WS protocol to a low-level, direct socket protocol?

Not that I'm aware of.  I'm going to go out on a limb and predict WebSockets will be slower ;)

A: To make a long story short, if you want to use TCP for multiplayer games, you need to use what we call adaptive streaming techniques. In other words, you need to make sure that the amount of real-time data sent to synchronize the game world among the clients is governed by the currently available bandwidth and latency for each client.
Dynamic throttling, conflation, delta delivery, and other mechanisms are adaptive streaming techniques, which don't magically make TCP as efficient as UDP, but make it usable enough for several types of games.
I tried to explain these techniques in an article: Optimizing Multiplayer 3D Game Synchronization Over the Web (http://blog.lightstreamer.com/2013/10/optimizing-multiplayer-3d-game.html).
I also gave a talk on this topic last month at HTML5 Developer Conference in San Francisco. The video has just been made available on YouTube: http://www.youtube.com/watch?v=cSEx3mhsoHg

A: On a LAN, you can get Round-trip times for messages over WebSocket of 200 microsec (from browser JS to WebSocket server and back), which is similar to raw ICMP pings. On MAN, it's around 10ms, WAN (over residential ADSL to server in same country) around 30ms, and so on up to around 120-200ms via 3.5G. The point is: WebSocket does add virtually no latency to the one you will get anyway, based on the network.
The wire level overhead of WebSocket (compared to raw TCP) is between 2 octets (unmasked payload of length < 126 octets) and 14 octets (masked payload of length > 64k) per message (the former numbers assume the message is not fragmented into multiple WebSocket frames). Very low.
For a more detailed analysis of WebSocket wire-level overhead, please see this blog post - this includes analysis covering layers beyond WebSocket also.
More so: with a WebSocket implementation capable of streaming processing, you can (after the initial WebSocket handshake), start a single WebSocket message and frame in each direction and then send up to 2^63 octets with no overhead at all. Essentially this renders WebSocket a fancy prelude for raw TCP. Caveat: intermediaries may fragment the traffic at their own decision. However, if you run WSS (that is secure WS = TLS), no intermediaries can interfere, and there you are: raw TCP, with a HTTP compatible prelude (WS handshake).
WebRTC uses RTP (= UDP based) for media transport but needs a signaling channel in addition (which can be WebSocket i.e.). RTP is optimized for loss-tolerant real-time media transport. "Real-time games" often means transferring not media, but things like player positions. WebSocket will work for that.
Note: WebRTC transport can be over RTP or secured when over SRTP. See "RTP profiles" here.


text:
Q: woocommerce_payment_complete not firing on marking order completed I need to do an action when an order is completed.
I Have tried this:
function mysite_woocommerce_payment_complete( $order_id ) {
error_log("callback fired");
}
add_action( 'woocommerce_payment_complete', 'mysite_woocommerce_payment_complete' );

But when I use the checkmark to mark the order as completed here in admin orders screen,

...the hook doesn't fire.
I tried woocommerce_order_status_changed too, it does the action when I place the order, but does nothing when i mark the order completed.
But when I mark the order completed, I get the email about completing it.
Thanks!
Edit:
I tried woocommerce_order_status_changed too, this way:
function mysite_woocommerce_payment_complete($order_id, $old_status, $new_status ) {
    error_log("$old_status / $new_status \n");
}
add_action( 'woocommerce_order_status_changed', 'mysite_woocommerce_payment_complete', 99, 3 );

but it fires on purchasing (I selected bank transfer) and shows: "pending / on-hold", but not true - see edi2 doesn't fire on manual backend change from "on hold" to "completed". Neither by checkmark nor in single order interface.
Edit2
woocommerce_order_status_changed and woocommerce_order_status_completed works, it only outputed my testing "error" into debug.log, not to error_log for some reason.
The woocommerce_payment_complete i used previously doesn't apply to methods like bank transfer, that's why that didn't work. Thanks to @helgatheviking for the quick and right answer

A: Well the completed order email is triggered by the following:
// Triggers for this email
add_action( 'woocommerce_order_status_completed_notification', array( $this, 'trigger' ) );

as seen here in source.
All "transactional email actions" (ie: actions that trigger the sending of an email) get a _notification hook in addition to the normal hook, seen here.
Thus woocommerce_order_status_completed_notification is an additional hook triggered on the woocommerce_order_status_completed hook if woocommerce_order_status_completed is in the woocommerce_email_actions array, which it is by default. To avoid any surprised from the emails, I recommend using the woocommerce_order_status_completed hook which is fired any time there is an order status change, including from within the admin, see this example:
function mysite_woocommerce_payment_complete( $order_id ) {
    error_log("callback fired");
}
add_action( 'woocommerce_order_status_completed', 'mysite_woocommerce_payment_complete' );


text:
Q: Configuring Firebase After moving our project from the Firebase legacy console and updating the pod to version 3.2.0, we need to figure out how to import the GoogleServices-info.plist into our Xcode project. Every time we download the file from the new Firebase console, we get "1.plist" which says error 403 unauthorized. What steps are necessary to obtaining this file?

A: Hi i ran into the same issue and found out that in order to generate the GoogleService-Info.plist in the web console your web console login should be recent. So to solve the issue just sign out of firebase and sign in again to refresh your credentials. After that you can try again  to download the plist and it will work


text:
Q: How to integrate $- \mu M(t) + \alpha M(t) \exp(-\beta M(t)) \,dt$? I want to solve $M$ where $M(t)$ is a function of time $t$. I have this equation,
$$M'(t) = - \mu M(t) + \alpha M(t) e^{-\beta M(t)}$$
where $\alpha, \mu$ and $\beta$ are nonnegative constants. I know that I need to take the integration in order to do so but I do not know how to solve it. I already tried integration by parts but it gives me a much more complicated equation after. Can someone tell me what technique to use?
Thank you very much in advance.