text:
Q: jQuery mousewheel scroll div IE PROBLEM I'm trying to enable mousewheel scroll for a simple div. It work for FF CHROME SAFARI...but IE 7,8,9 still won't cooperate as usual ;)
I am using jQuery mousewheel plugin :
(function($) {
var types = ['DOMMouseScroll', 'mousewheel'];
$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },
    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};
$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },

    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});
function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";
    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }
    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;
    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }
    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);
    return $.event.handle.apply(this, args);
}
})(jQuery);

with this function:
jQuery(function() {
     jQuery('#home_new_wrapper').mousewheel(function(event, delta) {
         var scrollTop = jQuery(this).scrollTop();
         jQuery(this).scrollTop(scrollTop-Math.round(delta * 20));
             return false; // prevent default
     });
});

If someone have a clue on how I can fix IE 7-8-9
Thank you
EDIT
I UPDATED MY JQUERY VERSION FROM 1.4.2 to 1.6.1 and it work.... I still have a question
Can someone help to modify this code to bind the UP/DOWN arrows too?????

A: I can't get it to work, even with jQ 1.6.2. But I can give you the arrow key code:

    $(window).bind('keydown', function(e){
if (e.keyCode == 38){
    $('#layerslider').layerSlider('prev');
}
else if (e.keyCode == 40){
    $('#layerslider').layerSlider('next');
}

});

A: I just solved this issue setting a transparent backgroung image to DIV style.
background: url(../images/desktop/common/scroll-pages-bg-fix-to-ie.png) repeat;

The scroll-pages-bg-fix-to-ie.png is 1x1 pixels with transparent color.
The problem is IE answer to this event only over areas with visual elements.
As always! IE giving us problems.
In my issue the event was .scroll
$("#content #pages").scroll(function () {...});

but I suppose my solution can solve your problem.


text:
Q: What is the Inverse function in topological spaces? If The usual topology $\tau$ on $\mathbb{R}$ and $X=\{a,b,c,d\}$ with the topology $\rho=\{\phi,X,\{a\},\{b\},\{a,b\},\{a,b,c\}\}$. Then the function $f:(\mathbb{R},\tau)\longrightarrow (X,\rho)$ defined by
\begin{equation*}
 f(x) = \begin{cases}
  c, & if \quad x \in \mathbb{Q} \\
  a, &if \quad x \in \mathbb{I}_{rr}
 \end{cases}
\end{equation*}
I know the $f^{-1}(\{a\})=\mathbb{I}_{rr}$ and $f^{-1}(\{c\})=\mathbb{Q}$. But, I'm not sure about $f^{-1}(\{b\})=\phi$ or not?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sometimes Fragment not attached to Activity (onCreateOptionsMenu) Not sure why, but I get a few error-reports from an app in the playstore which have the message:
java.lang.IllegalStateException: Fragment NewsOverViewFragment{4062e840} not attached to Activity
   at android.support.v4.app.Fragment.getResources(Fragment.java:601)
   at de.dala.simplenews.ui.NewsOverViewFragment.shouldUseMultipleColumns(NewsOverViewFragment.java:153)
   at de.dala.simplenews.ui.NewsOverViewFragment.updateMenu(NewsOverViewFragment.java:145)
   at de.dala.simplenews.ui.NewsOverViewFragment.onCreateOptionsMenu(NewsOverViewFragment.java:139)

I already did a fix and check whether the fragment is attached to the activity but this is just "avoiding" the problem. In my opinion it should never occure to get a notattached-state in onCreateOptionsMenu or onOptionsItemSelected.
Why would this occure? How is it possible for the fragment to call onCreateOptionsMenu/onOptionsItemSelected without being attached to the activity?
Regards
Code:
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    menu.clear();
    inflater.inflate(R.menu.news_overview_menu, menu);
    updateMenu();
    super.onCreateOptionsMenu(menu, inflater);
}

private void updateMenu(){
    boolean useMultiple = shouldUseMultipleColumns();
    ...
}

private boolean shouldUseMultipleColumns(){
    boolean useMultiple = false;

    Configuration config = getActivity().getResources().getConfiguration();
            switch (config.orientation) {
                case android.content.res.Configuration.ORIENTATION_LANDSCAPE:
                    useMultiple = PrefUtilities.getInstance().useMultipleColumnsLandscape();
                    break;
                case android.content.res.Configuration.ORIENTATION_PORTRAIT:
                    useMultiple = PrefUtilities.getInstance().useMultipleColumnsPortrait();
                    break;
      }

    return useMultiple;
}

Like I said I now check whether the fragment is attached and only then call shouldUseMultipleColumns() which fixes the problem but does not explain why this is called in the first place...
Edit2: My Activity
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    if (savedInstanceState == null) {
        if (getIntent().getDataString() != null) {
            String path = getIntent().getDataString();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            currentFragment = CategoryModifierFragment.getInstance(path);
            transaction.replace(R.id.container, currentFragment).commit();
        } else {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            currentFragment = NewsOverViewFragment.getInstance(NewsOverViewFragment.ALL);
            transaction.replace(R.id.container, currentFragment).commit();
        }
    }
    ...
}

This is basically the attaching procedure. However, it is possible to call other fragments which are always replacing the currentFragment so there is a chance that my NewsOverViewFragment is NOT attached. But even if this is the case - why is onCreateOptionsMenu called?

A: you should check the isAdded() function of fragment
http://developer.android.com/reference/android/app/Fragment.html#isAdded()
so your shouldUseMultipleColumns() will look like that
private boolean shouldUseMultipleColumns(){
    if(!isAdded()) return false;
    boolean useMultiple = false;

    Configuration config = getActivity().getResources().getConfiguration();
            switch (config.orientation) {
                case android.content.res.Configuration.ORIENTATION_LANDSCAPE:
                    useMultiple = PrefUtilities.getInstance().useMultipleColumnsLandscape();
                    break;
                case android.content.res.Configuration.ORIENTATION_PORTRAIT:
                    useMultiple = PrefUtilities.getInstance().useMultipleColumnsPortrait();
                    break;
      }

    return useMultiple;
}


text:
Q: Restrict Swipe Controls I am developing an endless runner game where you swipe left and right on a road to move the player between lanes. I want to restrict my lower screen proportion (not large proportion, small proportion).
How can you disable the touch or swipe controls in a specific area?


text:
Q: custom naming for threads using threadfactory I have a class that represent the world where subjects live in
public class WorldLifecycle {
    private ExecutorService executorService;

    public void startWorld() {
        executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
            r -> {
                String id = ((IdentifiableRunnable) r).getId();
                return new Thread(r, id);
            });
    }

    public void bringLife(LivingPerson ... people) {
        Arrays.stream(people).forEach(executorService::submit);
    }

    public void endWorld() {
        executorService.shutdownNow();
        try {
            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            System.err.println("Failed to finish thread executor!");
        }
    }
}

Every LivingPerson looks like this
public class LivingPerson implements IdentifiableRunnable {
    // investigate global world variable
    private boolean isRunning = true;

    private final StatefulPerson person;

    public LivingPerson(StatefulPerson person) {
        this.person = person;
    }

    @Override
    public void run() {
        System.out.println("Initial state: person=" + person.getRawPerson());
        while (isRunning) { // for now forever
            try {
                Thread.sleep(1000); // do transition every 1 seconds

                LifeState state = person.nextState();
                System.out.println(getPerson().getName() + " " + state.getActionLabel());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("End state: person=" + person.getRawPerson());
    }

    @Override
    public String getId() {
        Person person = getPerson();
        return person.getId() + " - " + person.getName();
    }

    @Override
    public void terminate() {
        isRunning = false;
    }

    // returns clone instead of existing
    private Person getPerson() {
        return person.getRawPerson();
    }

}

I want to name each thread by using person's name and unique identifier.
IdentifiableRunnable is a simple interface
public interface IdentifiableRunnable extends Runnable {
    String getId();
    void terminate();
}

I initialize everything like this
WorldLifecycle world = new WorldLifecycle();
LivingPerson male = createPerson("John", 40, Gender.MALE);
LivingPerson female = createPerson("Helen", 25, Gender.FEMALE);

System.out.println("Starting world...");
world.startWorld();

world.bringLife(male, female);

// just wait
try {
    Thread.sleep(10000);
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}

System.out.println("Destroying world...");
world.endWorld();

But when I try to run it, I get the error
Exception in thread "main" java.lang.ClassCastException: java.util.concurrent.ThreadPoolExecutor$Worker cannot be cast to com.lapots.breed.lifecycle.api.Ide
ntifiableRunnable
at com.lapots.breed.lifecycle.WorldLifecycle.lambda$startWorld$0(WorldLifecycle.java:14)
at java.util.concurrent.ThreadPoolExecutor$Worker.<init>(ThreadPoolExecutor.java:612)
at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:925)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1357)
at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:112)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at com.lapots.breed.lifecycle.WorldLifecycle.bringLife(WorldLifecycle.java:20)
at com.lapots.breed.Sandbox.main(Sandbox.java:23)

As it seems it does not get my identifiableRunnable in the ThreadFactory.
How to solve it?

A: If you trace library calls with a debugger you will notice that your newThread method will be called like so:
Worker(Runnable firstTask) {
    setState(-1); // inhibit interrupts until runWorker
    this.firstTask = firstTask;
    this.thread = getThreadFactory().newThread(this);
}

So it is passed an instance of the Worker class, which obviously can't be cast to your IdentifiableRunnable.
To execute your stream in parallel you should use ForkJoinPool how it is described in this post, in the first answer  Custom thread pool in Java 8 parallel stream
Btw, here's how you can compress the code in your post:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.stream.Stream;

public class Main {

    interface TestInterface extends Runnable{
        default String getId() {
            return "2";
        }
    }
    static class TestClass implements TestInterface {

        @Override
        public void run() {
            System.out.println("TEST");
        }
    }

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() {
            @Override
            public Thread newThread(final Runnable r) {
                String id = ((TestInterface)r).getId();
                Thread t = new Thread(r, id);
                t.setDaemon(true);
                return t;
            }
        });

        Stream.of(new TestClass(),new TestClass(),new TestClass(),new TestClass()).forEach(exec::submit);

    }
}


text:
Q: Un-flattening a table I have a table that takes the following form:
person, date, food1, food2, food3

I would like to take this table and get a result that looks like this:
person, date, foodId

So for instance, if I had a row in my original table that looked like this:
Andy, 1/1/2012,false,true,true

I would get a result that looks like this
Andy, 1/1/2012, food2
Andy, 1/1/2012, food3

So far I have
SELECT person, date,
(
    case
        when food1 = true then 'food1'
        when food2 = true then 'food2'
        when food3 = true then 'food3'
    end
) as foodId

But this only grabs one result per source row when there can be up to 3 results per source row.  Any way I can fix my query to get 2 rows from my example instead of just one?

A: You can UNPIVOT the data: Using PIVOT and UNPIVOT
Setup:
create table diet(person varchar(10), entry datetime, food1 varchar(10), food2 varchar(10), food3 varchar(10))
insert into diet values('John', CURRENT_TIMESTAMP, 'Apple','Pizza','Cake');

Unpivot Query:
SELECT person, entry, meal, food
FROM
   (SELECT person, entry, food1, food2, food3
   FROM diet) p
UNPIVOT
   (food FOR meal IN
      (food1, food2, food3)
      )AS unpvt;

Output:
person  entry   meal    food
John    2012-02-08 14:42:22.940 food1   Apple
John    2012-02-08 14:42:22.940 food2   Pizza
John    2012-02-08 14:42:22.940 food3   Cake

A: The only way I know to do this is with three queries:
INSERT INTO Table2 (person, date, foodID) SELECT person, date, 'food1' FROM Table1 WHERE food1;
INSERT INTO Table2 (person, date, foodID) SELECT person, date, 'food2' FROM Table1 WHERE food2;
INSERT INTO Table2 (person, date, foodID) SELECT person, date, 'food3' FROM Table1 WHERE food3;

A: Try this:
(SELECT person, date, 'food1' as foodId from table where food1 = true
UNION ALL
SELECT person, date, 'food2' as foodId from table where food2 = true
UNION ALL
SELECT person, date, 'food3' as foodId from table where food3 = true
) ORDER BY person

EDIT (in response to a comment)
If you need to put this into a temp table, change the query to this:
select person, date, FoodId
into #my_temp_table
from (
    SELECT person, date, 'food1' as foodId from table where food1 = true
    UNION ALL
    SELECT person, date, 'food2' as foodId from table where food2 = true
    UNION ALL
    SELECT person, date, 'food3' as foodId from table where food3 = true
) table_alias

A: try
SELECT person, date, 'food1' AS foodID FROM YourTable1 WHERE food1 = true
UNION ALL
SELECT person, date, 'food2' AS foodID FROM YourTable1 WHERE food2 = true
UNION ALL
SELECT person, date, 'food3' AS foodID FROM YourTable1 WHERE food3 = true

A: Why would you want to do that in SQL? Presentation should be done in, well, presentation layer, not data manipulation layer.
In addition to architectural "ugliness", you'll also incur some performance penalty: when returning the result of the query to the client, instead of transferring one row with simple Booleans, your DBMS now has to transfer up to 3 rows, with repeated person and date, plus food represented as string instead of Boolean.

OTOH, if you actually want to redesign your data model and need a way to transfer the data from the old model to the new, well that is a different matter...


text:
Q: assign zero in unsigned short int in c I try to assign zero to a field in a structure called list
list.ultimo = 0;

but when I use printf
printf("%d", list.ultimo);

I get the result
32766

but when I add
unsigned short int cero = 0;

the result of printf is correct, no matter that does not use cero. why?
lista.h
#ifndef LISTA_H
#define LISTA_H

typedef struct{
  elemento lista[TAMANOMAX];
  unsigned short int ultimo;
}LISTA;

void Insertar(elemento, unsigned short int posicion, LISTA);
#endif

lista.c
#include<stdio.h>

typedef short int elemento;
#ifndef TAMANOMAX
#define TAMANOMAX 10
#endif
#include"lista.h"

void Insertar(elemento x, unsigned short int p, LISTA lista){
  if (lista.ultimo >= TAMANOMAX){
    puts("full list");
    printf("%hu",lista.ultimo);
  }
}

main.c
#include<stdio.h>

typedef unsigned short int elemento;
#define TAMANOMAX 4
#include"lista.h"

int main(){
  LISTA esferas;
  esferas.ultimo = 0;
  Insertar(2,0,esferas);
  printf("\n%hu\n", esferas.ultimo);
  return 0;
}

the result is
$gcc -Wall lista.c main.c

full list

32765

0

I'm new to this, I'm slow for now, I regret the delay

A: Use %hd to print a short int and %hu to print an unsigned short int. %d is for int.
EDIT: Now that you have posted the full code, it appears that TAMANOMAX is set to 10 in lista.c, but set to 4 in main.c, leading to an incompatibilty between your main() function and the Insertar one. You should have the same value in all files. And if you want to work with different array lengths, add a length member in your LISTA structure. But TAMANOMAX should absolutely be the same everywhere, else you're in fact working with different data types and your program won't work.

A: Using mismatched format specifier with the type of the argument invokes undefined behavior.
Quoting C11 standard, chapter §7.21.6.1, fprintf() function

[..] If any argument is
  not the correct type for the corresponding conversion specification, the behavior is
  undefined.

and about %d format specifier,

d,i The int argument [....]

so, %d expects an int.
As per your question title, ultimo is unsigned short int and you're using %d to print the value.
You should use %hu to print unsigned short int.


text:
Q: Python - Reversing data generated with particular loop order Question: How could I peform the following task more efficiently?
My problem is as follows. I have a (large) 3D data set of points in real physical space (x,y,z). It has been generated by a nested for loop that looks like this:
# Generate given dat with its ordering
x_samples = 2
y_samples = 3
z_samples = 4
given_dat = np.zeros(((x_samples*y_samples*z_samples),3))
row_ind = 0
for z in range(z_samples):
    for y in range(y_samples):
        for x in range(x_samples):
            row = [x+.1,y+.2,z+.3]
            given_dat[row_ind,:] = row
            row_ind += 1
for row in given_dat:
    print(row)`

For the sake of comparing it to another set of data, I want to reorder the   given data into my desired order as follows (unorthodox, I know):
# Generate data with desired ordering
x_samples = 2
y_samples = 3
z_samples = 4
desired_dat = np.zeros(((x_samples*y_samples*z_samples),3))
row_ind = 0
for z in range(z_samples):
    for x in range(x_samples):
        for y in range(y_samples):
            row = [x+.1,y+.2,z+.3]
            desired_dat[row_ind,:] = row
            row_ind += 1
for row in desired_dat:
    print(row)

I have written a function that does what I want, but it is horribly slow and inefficient:
def bad_method(x_samp,y_samp,z_samp,data):
    zs = np.unique(data[:,2])
    xs = np.unique(data[:,0])
    rowlist = []
    for z in zs:
        for x in xs:
            for row in data:
                if row[0] == x and row[2] == z:
                rowlist.append(row)
    new_data = np.vstack(rowlist)
    return new_data
# Shows that my function does with I want
fix = bad_method(x_samples,y_samples,z_samples,given_dat)
print('Unreversed data')
print(given_dat)
print('Reversed Data')
print(fix)
# If it didn't work this will throw an exception
assert(np.array_equal(desired_dat,fix))

How could I improve my function so it is faster? My data sets usually have roughly 2 million rows. It must be possible to do this with some clever slicing/indexing which I'm sure will be faster but I'm having a hard time figuring out how. Thanks for any help!

A: You could reshape your array, swap the axes as necessary and reshape back again:
# (No need to copy if you don't want to keep the given_dat ordering)
data = np.copy(given_dat).reshape(( z_samples, y_samples, x_samples, 3))
# swap the "y" and "x" axes
data = np.swapaxes(data, 1,2)
# back to 2-D array
data = data.reshape((x_samples*y_samples*z_samples,3))

assert(np.array_equal(desired_dat,data))


text:
Q: Can you connect a live frontend to a offline backend? I was wondering, is it possible to connect a deployed frontend to a offline backend on a local host on the same machine? Or a local frontend to a live backend?

A: It is not possible to connect a deployed frontend to an offline backend as it can only source data from an online source, but an offline frontend can source data from an online backend as long as the links to the data source or APIs are correctly placed. e.g a mongoDB database, can be posted or one can get data from the database using an offline frontend.


text:
Q: Mount all Nginx virtual hosts at subpathes of the default host I have a Nginx setup with several virtual hosts (defined by server blocks for every linux home directory).
To allow a preview for domains that currently do not have a DNS entry pointing to my host, I like to show the correspondent site at eg. http://myhost.com/example.com/index.html.
For this example, I do this by
location /example.com {
    root /home/example.com/public_html;
    rewrite ^/example.com(.*)$ $1 break;
    rewrite_log off;
}

However, I would like a general solution that reroutes all vhosts.
In addition, is there a HTTP header equivalent to the HTML <base ...> tag, that Nginx could set to enable the use of / prefixed pathes in the sites?


text:
Q: Svelte.js - how to proxy bindings? I'm trying to implement checkbox component with custom styles, but can't find a way to proxy bindings. Here's how the component looks like now (it doesn't work):
<input
    id="{id}"
    bind:group
    bind:checked
    type="checkbox">

    <slot></slot>

I want it to be usable as usual checkbox with checked or group bindings. But now without group I'm getting an error. It there a way to do such things with Svelte?

A: Here is my approach. I create a reusable checkbox component and call it from any forms that need it. Note the bind:checked=checked

     {@html label}
    <input type="checkbox" class="form-check-input" id={id}
      name={name} bind:value=value bind:checked=checked>
    <slot name="afterlabel"></slot>

I call it from a view like this, note the bind:checked=user.usrRoles.reports is a boolean value:
<fieldset>
    <Checkbox name="roles" value="reports" id="role-valid" label="Reports Page" bind:checked=user.usrRoles.reports>

View Reports Page
</Checkbox>
</fieldset>


text:
Q: Hago UPDATE de PHP a MySQL pero no me actualiza y no sé por qué Estoy actualizando mi tabla de MySQL en función de si su eam (ID) está en un array:
foreach ($resultadoComparaArraysExiste as $key => $value) {
    $sql="UPDATE articulos SET `tipo_articulo`=`EXISTE` WHERE `eam`=".$value;
    $resultado=mysqli_query($conWebService, $sql);
    if($resultado){
        echo "El artículo con el valor"." ".($value)." "."actualizó correctamente el valor de su campo tipo_articulo.
";
    }else{
        echo "El artículo con el valor"." ".($value)." "."tuvo errores en la actualización de su campo tipo_articulo.
";
    }

}

El caso es que me está devolviendo el mensaje de error que le tengo puesto, no actualiza y PHP no me devuelve ningún error, más allá del mensaje que he escrito yo. Resumen: que no me actualiza y no tengo ni idea de en qué estoy fallando. ¿Alguna idea? Gracias, saludos.

A: En tu codigo anterior pusiste como parametro "ean", no "eam", intenta corregir eso, para luego realizar otra prueba,
foreach ($resultadoComparaArraysExiste as $key => $value) {
    $sql="UPDATE articulos SET tipo_articulo = 'EXISTE' WHERE ean =".$value;
    $resultado=mysqli_query($conWebService, $sql);
    if($resultado){
        echo "El artículo con el valor"." ".($value)." "."actualizó correctamente el valor de su campo tipo_articulo.
";
    }else{
        echo "El artículo con el valor"." ".($value)." "."tuvo errores en la actualización de su campo tipo_articulo.
";
    }
}


text:
Q: Fetch documents from a MongoDB collection based on timestamp I have a MongoDB collection with documents that look like this
{
    "_id" : ObjectId("5aab91b2caa256021558f3d2"),
    "Timestamp" : "2017-11-16T14:43:07.5357785+01:00",
    "status" : 1,
    "created_at" : 1521193394,
    "updated_at" : 1521193394,
    "deleted_at" : ""
}

Data gets entered into the collection every 15 minutes. Using the created_at field, which is in epoch time, I would like to find a way to fetch data at the top of every hour. So for example, data is entered at 12.00 12.15 12.30 12.45 13.00 13.15 13.30 13.45 14.00.
I would like to fetch entries from the collection that were entered at 12.00 13.00 and 14.00.
I am also open to suggestions as to whether or not using epoch time is the best way to go about it.

A: Using epoch time is really a good way to go.
Since you are stoing in seconds, every round hour can be divisible by 3600(seconds in hours) without remainder. You can make use of this property to find your documents.
db.collection.find({created_at: {$mod: [ 3600, 0 ]}});

According to $mod documentation, it will,

Select documents where the value of a field divided by a divisor has
  the specified remainder

We provided divisor as 3600 and remainder as 0. This should give what you expect.
To ignore seconds:
For this condition, mod(epoch, 3600) should be less than 59. This query can be formed using $expr of mongo 3.6
db.collection.find({$expr: {$lte: [{ $mod: [ '$created_at', 3600 ] }, 59]}});

Hope this helps!


text:
Q: Fill a block element with left most floating child (float: right) I need to fill a
 width element with his most left child (out of three childs). Those three childs are formated with display: inline-block; float: right.
what i achieved so far:

what i expected to achieve:

It's obviously that width: 66% don't help anyway. Also a 100% width will not work.
I found this question on stackoverflow, but I need something made in pure CSS, no JS, jQuery, etc. Also, using a table is not a solution for me.
If the HTML code can help in this matter:

            <input type="button" value="" class="cancel">
            <input type="button" value="" class="save">
            <input type="text" value="Big list item" class="name">

                <input type="button" value="" class="cancel">
                <input type="button" value="" class="save">
                <input type="text" value="Medium list item" class="name">

                    <input type="button" value="" class="cancel">
                    <input type="button" value="" class="save">
                    <input type="text" value="1st small item" class="name">

                    <input type="button" value="" class="cancel">
                    <input type="button" value="" class="save">
                    <input type="text" value="2nd small item" class="name">

                    <input type="button" value="" class="cancel">
                    <input type="button" value="" class="save">
                    <input type="text" value="3rd small item" class="name">

Thanks for your time,
SYNCRo,

A: Having corrected your invalid HTML (as noted in the comment to your question no element other than an li is a valid child of a ul or ol, including those elements themselves) to the following:

            <input type="button" value="" class="cancel" />
            <input type="button" value="" class="save" />
            <input type="text" value="Big list item" class="name" />

                <input type="button" value="" class="cancel" />
                <input type="button" value="" class="save" />
                <input type="text" value="Medium list item" class="name" />

                    <input type="button" value="" class="cancel" />
                    <input type="button" value="" class="save" />
                    <input type="text" value="1st small item" class="name" />

                    <input type="button" value="" class="cancel" />
                    <input type="button" value="" class="save" />
                    <input type="text" value="2nd small item" class="name" />

                    <input type="button" value="" class="cancel" />
                    <input type="button" value="" class="save" />
                    <input type="text" value="3rd small item" class="name" />

Note that I had to add a class to those li elements that contain children (since the previous, simple, li selector now matches the multiple elements in the hierarchy), in this case the class items, but adjust to taste.
The following CSS works, albeit only with a pretty up-to-date browser:
li {
    width: 80%;
    clear: both;
    float: right;
    margin: 0 0 0.2em 0;
}

li.items {
    background-color: #f90;
}

li .save, li .cancel {
    float: right;
    width: 20px;
    height: 20px;
}

input.name {
    width: -webkit-calc(100% - 45px);
    width: -moz-calc(100% - 45px);
    width: -o-calc(100% - 45px);
    width: -ms-calc(100% - 45px);
    width: calc(100% - 45px);
}

JS Fiddle demo.
This uses the CSS calc() function to determine the width of the input element as a calculation.
To be cross-browser compatible with the older browsers you could use, instead, absolute (for the .save and .cancel elements) and relative (for the li elements) positioning:
li {
    width: 80%;
    clear: both;
    float: right;
    margin: 0 0 0.2em 0;
    position: relative;
}

li.items {
    background-color: #f90;
    padding: 0 45px 0 0;
}

li .save, li .cancel {
    position: absolute;
    width: 20px;
    height: 20px;
}

.save {
    top: 0;
    right: 21px;
}

.cancel {
    top: 0;
    right: 0;
}

input.name {
    width: 100%;
}

JS Fiddle demo.
You'll note that the padding gets added to the width of the li elements, of course, so you may wish to add the box-sizing CSS property to compensate for that:
/* all other CSS remains untouched */
li {
    width: 80%;
    clear: both;
    float: right;
    margin: 0 0 0.2em 0;
    position: relative;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    -o-box-sizing: border-box;
    box-sizing: border-box;
}

JS Fiddle demo.
References:

*

*CSS box-sizing.

*CSS calc().

A: try this: just add another class with other width
HTML:

        <input type="button" value="" class="cancel">
        <input type="button" value="" class="save">
        <input type="text" value="Big list item" class="name_big_list">

            <input type="button" value="" class="cancel">
            <input type="button" value="" class="save">
            <input type="text" value="Medium list item" class="name_medium_list ">

                <input type="button" value="" class="cancel">
                <input type="button" value="" class="save">
                <input type="text" value="1st small item" class="name">

                <input type="button" value="" class="cancel">
                <input type="button" value="" class="save">
                <input type="text" value="2nd small item" class="name">

                <input type="button" value="" class="cancel">
                <input type="button" value="" class="save">
                <input type="text" value="3rd small item" class="name">

CSS:
 div {
    width: 200px;
    border: 1px solid red;
}
ul {
    padding: 0px 0px 0px 20px;
    margin: 0px;
}
li {
    display: block;
    white-space: nowrap;
    list-style-type: none;
    display: block;
    height: 20px;
    padding: 0px;
    margin: 1px;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;

    border-color: #D5AB55 #C93 #C93 #D5AB55;
    background-color: #F3CE00;
}

.name, .name_big_list, .name_medium_list {
    display: inline-block;
    float: right;
    height: 18px;
    width: 65%;
    margin: 0px;
    padding: 0px 2px;
    border: 1px solid grey;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
}
.name_big_list{
width: 73%
}
.name_medium_list{
width: 69%;
}
.save, .cancel {
    display: inline-block;
    float: right;
    height: 20px;
    width: 20px;
    margin: 0px 0px 0px 1px;
    padding: 0px;
    border: 1px solid grey;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
}
.save   { background: url(../images/confirm.png) no-repeat center center; }
.cancel { background: url(../images/cancel.png) no-repeat center center; }


text:
Q: What does "fancy being" mean? I think I know what the verb 'fancy' means (feel a desire or liking for). But does 'fancy being' here have a different meaning?

One needs to be audacious to proceed where no-one has gone before – and trail-blazers are often castigated for their effrontery. Fancy being ridiculed or ostracized for ascertaining the facticity of something ... for establishing a fact. (ref)

A: As Sven mentioned, the verb fancy here means to imagine. It doesn't here mean the secondary sense to like as it sometimes can (nor even the rather less common tertiary sense of to breed, as in pigeon fanciers or orchid fanciers).
The paywalled OED entry gives these relevant subsenses:

I. With reference to mental conception.

*

*trans.

*

*1a. To frame in fancy; to portray in the mind; to picture to oneself; to conceive, imagine. Also (with notion of fancy n. 3), to suppose oneself to perceive.
[subsenses 1b, 1c, and 1d omitted]

*

*1e. In colloq. use often in the imperative as an exclamation of suprise. Also absol.

So this is an example of sense 1e; it's being used as imperative exclamation of surprise much as if had been written:

Why, just imagine being ridiculed!


text:
Q: Why are T-Filters better than L-Filters? I was watching a beginners video about electronic filters. In that video, the presenter shows the same filter (same inductance and capacitance values) configured as an "L-Filter" and a "T-Filter" as follows:

During the video, the presenter mentions that the T-Filter provides better overall filtering over the L-Filter.
Could someone please help me understand how splitting the inductors as shown in the T-Filter makes for a better filter? What is occurring on the filter that makes one better than the other?
Thanks.

A: With a high impedance measurement device on the output, both filters will be identical in performance. However, if the output of the T filter were loaded with maybe a resistor, the filter would tend to change from a 2nd order low pass filter to a 3rd order low pass filter. If the resistor were swapped for another capacitor then the filter would tend to become a 4th order filter.
As to exact frequency response this cannot be determined without values.

A: On the top diagram the two solenoids act together as one. This makes this a second order low pass filter.
On the bottom diagram, since the solenoids are separated. It is a third order low pass filter.
There are many unknown parameters in your circuit. However it should look like this. Third order attenuates the signal's amplitude better.

A: In most situations where passive filters are used, both the input and output will have finite impedance.  If the input and output impedance are resistive, their behavior may be modeled as a series or parallel resistors.  For a voltage-based input or current-based output, impedance would appear as a resistor in series with the input or output; for a current-based input or voltage-based output, impedance would appear as resistance in parallel.
Adding such resistors to the LC circuit should help clarify the differences among different LC filter topologies.


text:
Q: Beta-binomial vs updating a prior beta distribution Bear with me, as I've just recently been learning about conjugate priors, prior and posterior distributions, and such material. My understanding of the beta-binomial distribution is that it basically is used to update a prior beta distribution with a binomial likelihood (data that we have observed that follows a binomial distribution). Together, the prior beta and binomial likelihood are compounded to form a posterior beta distribution. If that is the correct understanding (if not please correct me) then my question is: it sounds very similar to updating a prior beta distribution with observed data by manipulating the prior a & b params, so is there a difference?
Bonus question: is there such a thing as a beta likelihood, and if so what would be an example of data that follows that distribution?

A: You begin with a prior distribution.  You combine this with the likelihood to create a posterior distribution.  From the posterior distribution, you can create a posterior predictive distribution.  A prior predictive distribution also exists if you do not collect data.
In your case, you are beginning with the beta distribution as your prior distribution and a binomial likelihood function.  Your posterior is a beta distribution.  Your posterior predictive distribution is the beta-binomial distribution.  The prior predictive distribution would also be the beta-binomial distribution.
The prior distribution carries all the information you have about the parameter from outside the data.  The support for distribution is $\theta\in[0,1].$
The likelihood carries the information from the sample.  The support for the distribution is $0\dots{n}$ over the natural numbers, where $n$ is your sample size.
The posterior distribution has the same support as the prior $\theta\in[0,1]$.
The predictive distribution has support in $0\dots{m}$, where $m$ is the size of the future sample being predicted.
Because it is conjugate, updating happens in an analytic manner.  For example, if your prior was $\beta(5,12)$ and you observed seven successes and eighteen failures, then your posterior would be $\beta(5+7,12+18)=\beta(12,30)$.
If your posterior parameters were $\alpha$ and $\beta$ and $\gamma$ is your number of future success and $\delta$ is your number of future failures, then your posterior predictive distribution is $${\gamma+\delta\choose{\delta}}{\frac{\mathbf{B}(\alpha+\gamma,\alpha+\beta+\gamma+\delta)}{\mathbf{B}(\alpha,\beta)}},\gamma+\delta=m,$$ where $\mathbf{B}$ is the beta function and not the beta distribution.
Finally, yes, the beta distribution could be a likelihood function, but I cannot imagine a real world process that where it would be used.


text:
Q: What is android replacement for $.ajax with array I have existing jquery code to submit array 'array' as json var in a login process
var array1 = {
"command" : "login",
"username": $("#txt_username").val(),
"password": $("#txt_password").val(),
"remember":  $('#chk_remember').is(':checked')
};

$.ajax({
                url: 'functions.php',
                data : {'array': array1},
                dataType: 'json',
                type: 'POST',
                success: function(data) {
                    if  (data.success == 1 ){

                   $('#result').html("You have been logged in.</br>You will be     redirected to another page");
}
});

and at PHP
if (isset($_POST["array"])) {
$array = $_POST['array'];
switch ($array["command"]) {
    case "login" :
        if (DoLogin($array["username"], $array["password"]) == true) {
            $success = 1;
}
        else {
            $success = 0;
        }
        $arr = array("success" => $success, "redirect" => 1);

        echo json_encode($arr);
break;
}

how to deal with this login process from android?

A: public class Utils {

    public static String POST(String url, Login login){
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("command", login.command);
            jsonObject.accumulate("username", login.username);
            jsonObject.accumulate("password", login.password);
            jsonObject.accumulate("remember", login.remember);

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // ** Alternative way to convert Login object to JSON string usin Jackson Lib
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(login);

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if(inputStream != null)
            result = convertInputStreamToString(inputStream);
            else
            result = "Did not work!";

            } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        // 11. return result
        return result;
    }
}

// Model login obj
public class Login {
    public String password;
    public String username;
    public String command;
    public boolean remember;
}

Into Activity
Login login = new Login();

// get reference to the views
login.username = (EditText) findViewById(R.id.user);
login.password = (EditText) findViewById(R.id.pass);
login.command = (EditText) findViewById(R.id.comm);
login.remember = ((CheckBox) findViewById(R.id.rem)).isChecked();

Utils.POST(stringUrl, login) // use AsynckTask for this http://stackoverflow.com/questions/8829135/android-http-request-asynctask

A: I'd recommend looking into using Volley to handle your web requests. This is a handy guide to get started: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/


text:
Q: How to find the colored circles in an image opencv python for game development I have an image of an layout I'm tyring to find out the somewhat coloured circles
this piece of code is not able to identify the circles
This is the image I need to identify the circles of different colors

Code:-
import cv2
import numpy as np

img = cv2.imread('test7.png',0)
img = cv2.equalizeHist(img)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,10,param1=50,param2=30,minRadius=0,maxRadius=25)

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)

cv2.imshow('detected circles',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

But this is giving me error
Error
    circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,10,param1=50,param2=30,minRadius=0,maxRadius=25)
cv2.error: OpenCV(3.4.2) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/hough.cpp:1737: error: (-215:Assertion failed) !_image.empty() && _image.type() == (((0) & ((1 << 3) - 1)) + (((1)-1) << 3)) && (_image.isMat() || _image.isUMat()) in function 'HoughCircles'

I have 3 images Dog, Monkey, Donkey.
I need to place these images of dog, monkey, donkey on those circles and resize them.
Pics of those images

I want the final output like this.

A: You could try by filtering out your circles by transforming the image into HSV color space - cv2.COLOR_BGR2HSV. Then you can search your for your colors with cv2.inRange() and draw them on a mask (different mask for every color)
Something like this:

After you have the circles filtered out, you can search for contours with cv2.findContours() and find its position (you can search for it's center point or its extreme points) to determen where on the image you should put your smaller images. Note that I have resised your smaller images manually and if you whould want to have different sizes of the same picture you will have to modify the code. Also if you would like to keep transparency you should play with the chanells of your images and change the code. This is just an example on how I would approach the task.
Example code (without transparency and with same size pictures):
import cv2
import numpy as np

img = cv2.imread('thermal2.png')
dog = cv2.imread('resize1.jpg')
donkey = cv2.imread('resize2.jpg')
monkey = cv2.imread('resize3.png')

resize1 = cv2.resize(dog, (35, 40))
resize2 = cv2.resize(donkey, (60, 35))
resize3 = cv2.resize(monkey, (40, 40))

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])
lower_yellow = np.array([30,50,50])
upper_yellow = np.array([50,255,255])

mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
mask_red = cv2.inRange(hsv, lower_red, upper_red)
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)

res_blue = cv2.bitwise_and(img,img, mask=mask_blue)
res_red = cv2.bitwise_and(img,img, mask=mask_red)
res_yellow = cv2.bitwise_and(img,img, mask=mask_yellow)

gray_blue = cv2.cvtColor(res_blue, cv2.COLOR_BGR2GRAY)
gray_red = cv2.cvtColor(res_red, cv2.COLOR_BGR2GRAY)
gray_yellow = cv2.cvtColor(res_yellow, cv2.COLOR_BGR2GRAY)

_,thresh_blue = cv2.threshold(gray_blue,10,255,cv2.THRESH_BINARY)
_,thresh_red = cv2.threshold(gray_red,10,255,cv2.THRESH_BINARY)
_,thresh_yellow = cv2.threshold(gray_yellow,10,255,cv2.THRESH_BINARY)

_, contours_blue, hierarhy1 = cv2.findContours(thresh_blue,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
_, contours_red, hierarhy2 = cv2.findContours(thresh_red,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
_, contours_yellow, hierarhy3 = cv2.findContours(thresh_yellow,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

for c in contours_red:
    size = cv2.contourArea(c)
    if size > 30:
        cXY_left = tuple(c[c[:, :, 0].argmin()][0])
        cXY_top = tuple(c[c[:, :, 1].argmin()][0])
        cX = cXY_left[0]
        cY = cXY_top[1]
        img[cY:cY+resize1.shape[0], cX:cX+resize1.shape[1]]=resize1

for c in contours_blue:
    size = cv2.contourArea(c)
    if size > 30:
        cXY_left = tuple(c[c[:, :, 0].argmin()][0])
        cXY_top = tuple(c[c[:, :, 1].argmin()][0])
        cX = cXY_left[0]
        cY = cXY_top[1]
        img[cY:cY+resize2.shape[0], cX:cX+resize2.shape[1]]=resize2

for c in contours_yellow:
    size = cv2.contourArea(c)
    if size > 30:
        cXY_left = tuple(c[c[:, :, 0].argmin()][0])
        cXY_top = tuple(c[c[:, :, 1].argmin()][0])
        cX = cXY_left[0]
        cY = cXY_top[1]
        img[cY:cY+resize3.shape[0], cX:cX+resize3.shape[1]]=resize3

cv2.imshow('blue', res_blue)
cv2.imshow('red', res_red)
cv2.imshow('yellow', res_yellow)
cv2.imshow('img',img)

Result:


text:
Q: Error in elastic beanstalk upstart script? I have a AWS Elastic beanstalk app with ruby/puma configured. I see this in the instance's /etc/init. A puma.conf file with
$ cat /etc/init/puma.conf
description "Elastic Beanstalk Puma Upstart Manager"

start on runlevel [2345]
stop on runlevel [!2345]

respawn

script
exec /bin/bash <<"EOF"
  EB_SCRIPT_DIR=$(/opt/elasticbeanstalk/bin/get-config container -k script_dir)
  EB_SUPPORT_DIR=$(/opt/elasticbeanstalk/bin/get-config container -k support_dir)

        . $EB_SUPPORT_DIR/envvars
        . $EB_SCRIPT_DIR/use-app-ruby.sh

  if grep -eq 'true' /etc/elasticbeanstalk/has_puma.txt; then
    exec su -s /bin/bash -c "bundle exec puma -C $EB_SUPPORT_DIR/conf/pumaconf.rb" webapp
  else
    exec su -s /bin/bash -c "puma -C $EB_SUPPORT_DIR/conf/pumaconf.rb" webapp
  fi
EOF
end script

Is it just me or is this broken? Running the if condition(grep -eq 'true' /etc/elasticbeanstalk/has_puma.txt;) in the terminal throws an error. As does just running the entire if block. /etc/elasticbeanstalk/has_puma.txt contains one word true.
We discovered this because we were facing subtle app level issues which went away when we used bundle exec.
I was able to fix that by modifying the puma.conf thus,
$ cat /etc/init/puma.conf
description "Elastic Beanstalk Puma Upstart Manager"
EB_SUPPORT_DIR=/opt/elasticbeanstalk/support
start on runlevel [2345]
stop on runlevel [!2345]

respawn

script
exec /bin/bash <<"EOF"
  EB_SCRIPT_DIR=$(/opt/elasticbeanstalk/bin/get-config container -k script_dir)
  EB_SUPPORT_DIR=$(/opt/elasticbeanstalk/bin/get-config container -k support_dir)

. $EB_SUPPORT_DIR/envvars
. $EB_SCRIPT_DIR/use-app-ruby.sh

  exec su -s /bin/bash -c "cd /var/app/current && bundle exec puma -C $EB_SUPPORT_DIR/conf/pumaconf.rb" webapp
EOF
end script

I had to add the cd for it to work.. not too sure about it.
So is this a bug with the elastic beanstalk system? Is this fix correct or is there a cleaner/better way to achieve this?


text:
Q: how to show accordion-group based on items in array I want to show an accordion-group of angular-ui only if an array contains items. this can be changed dynamically.
I tried to use ng-show but since the array starts without items it is not displaying at all and it is not re-rendered again once items are added. I add a plunker for it: plnkr
Should I make the ng-show re-render somehow?

A: Most likely something in the accordion-group directive that prevents the ng-show from working as you want. I haven't digged deeper into it though.
You can always wrap the accordion-group in an extra div and put the ng-show there instead:

 0">
  <accordion-group heading="Dynamic Body Content">

The body of the accordion group grows to fit the contents

{{item}}

  </accordion-group>

Demo: plnkr


text:
Q: Clarification Needed Regarding $\sinh^{-1}(-3)$ As the definition of $\sinh^{-1}(x)$  goes :
$\sinh^{-1}(x)=\ln\left(x+\sqrt{x^{2}+1}\right)$
So what I expect to get is
$\sinh^{-1}(-3)=\ln\left(-3+\sqrt{10}\right)$
The value inside of the natural logarithm is positive because I can estimate that $\sqrt{10}$  is bigger than 3
However the answer in my textbook is $-\ln\left(3+\sqrt{10}\right)$
They claim that $\ln\left(-3+\sqrt{10}\right)=-\ln\left(3+\sqrt{10}\right)$
I know that $\ln(\frac{1}{x})=-\ln(x)$  But I am unable to make the connection with the answer in my textbook, is there any explanation for this ? is my first answer is correct ?

A: $$
\sqrt{10}-3=\frac{(\sqrt{10}-3)(\sqrt{10}+3)}{\sqrt{10}+3}=\frac{1}{\sqrt{10}+3}.
$$

A: Note that
$$-3+\sqrt{10}=(-3+\sqrt{10})\cdot\frac{-3-\sqrt{10}}{-3-\sqrt{10}}=\frac{-1}{-3-\sqrt{10}}=(3+\sqrt{10})^{-1}$$


text:
Q: get traceback from knitr on error How do I get better error reporting from knitr?
e.g. now knitr quits with:
Calls: knit ... lapply -> FUN -> lapply -> FUN -> rename -> <Anonymous>

When I run the same code interactively R quits with:
Calls: getSampleData ... lapply -> FUN -> lapply -> FUN -> rename -> <Anonymous>

Which is much better for understanding the problem - at least I know which function was throwing the error.
Ideally I would like also have the equivalent of traceback() appended.

A: You can set opts_chunk$set(error = FALSE), then you will be able to run traceback() when an error occurs. This requires you to run knitr in an interactive R session, though.

A: For the related problem where you actually want to display the error to the reader of your document, I wrote a wrapper function that computes and saves a traceback within a knitr document, and a replacement for traceback() that displays it.  Here's the code:
saveTraceback <- local({
  savedTraceback <- NULL
  saver <- function(e) {
    calls <- sys.calls()
    deparsed <- lapply(calls, deparse)
    deparsed <- deparsed[-length(deparsed)+0:1] # leave off last 2
    lastjunk <- max(grep("withCallingHandlers", deparsed))
    deparsed <- deparsed[-seq_len(lastjunk)]
    savedTraceback <<- deparsed
  }
  function(expr)
    withCallingHandlers(expr, error = saver)
})

traceback <- function() {
  base::traceback(environment(saveTraceback)$savedTraceback)
}

You would use it like this.  First display the code without executing it:
<<mycode,eval=FALSE>>=
f <- function() stop("this is an error")
g <- function() f()
g()
@

Then execute it in the saveTraceback() function without displaying:
<<echo=FALSE>>=
saveTraceback({
<<mycode>>
})
@

And finally call traceback(), which will display something like what the
user would have seen in the console.


text:
Q: foreach in Java: is having the statement which calculates the iterable object worse than having a variable in the loop? Working at object mapping with Java and JDBC for SQL Server I wondered myself if I would create a variable to save the value that returns a select sentence or if I could put the sentence in the foreach loop.
I have post the complete function but the question is only about the foreach loop. Both options works good for me, but I wanted to know if there is any difference about efficiency or if exists any case where the first one could fail.
public static List<User> UserList()
{
    BD miBD = new BD(BD_SERVER,BD_NAME);
    ArrayList<User> list = new ArrayList<User>();

    for(Object[] tuple: miBD.Select("SELECT name,password FROM tUser;"))
    {
        String id = (String)tuple[0];
        String p = (String)tuple[1];
        User u = new User(id,p);
        list.add(u);
    }

    return list;
}

or
    List<Object[]> tupleList = miBD.Select("SELECT name,password FROM tUser;")
    for(Object[] tuple: tupleList)
    {
        String id = (String)tuple[0];
        String p = (String)tuple[1];
        User u = new User(id,p);
        list.add(u);
    }
    return lista;
}

Which is more advisable to use?

A: In terms of performance they are exactly the same.
The first variant is one line shorter so go with that.


text:
Q: Mudar o fundo do HTML quando input for true Estou fazendo um site onde terá como fundo uma foto do Heisenberg dizendo "Say My Name" com um input do tipo text no meio da tela e quando o usuario digitar Heisenberg o background irá mudar para uma foto dele dizendo You Goddam right, porém não estou conseguindo, como faço isso usando JQuery?

$("#SayMyName").focusout( function(){
    var SayMyName = $("#SayMyName").val();
    if (SayMyName == "Heisenberg") {
        $("body").css("background-image", "url(/myimage.jpg)");
    }
    else {
        SayMyName = " "
    }
});
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Document</title>
</head>
<body>
    <form action="">
        <input type="text" id="SayMyName" name="SayMyName">
        <input type="submit" value="submit">
    </form>
</body>
</html>

A: Provavelmente o path para a url da imagem está errada, caso seja o diretório corrente não precisa da / no /myimage.jpg ou podes usar também ./myimage.jpg, além disso, faltam os apóstrofos dentro do url. Fora isso, o else não está fazendo nada... já que só atribui um espaço em branco pra uma variável que não é mais utilizada dentro do escopo dela.
A seguir eu coloquei o seu código, só que alterando o background-color, afim de mostrar que a lógica em si está correta, possivelmente, precisando verificar só o path do background-image.
A seguir eu coloquei o seu código, utilizando uma imagem qualquer...

$("#SayMyName").focusout( function(){
    var SayMyName = $("#SayMyName").val();
    if (SayMyName == "Heisenberg") {
        $("body").css("background-image", "url('https://cdn.pixabay.com/photo/2014/05/02/21/49/laptop-336373_960_720.jpg')");
    }
});
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <title>Document</title>
</head>
<body>
    <form action="">
        <input type="text" id="SayMyName" name="SayMyName">
    </form>
</body>
</html>


text:
Q: PHP autoforwarding If my PHP page contains:
<input type="submit" name="add1" value="Add Item">
<input type="submit" name="chgprice" value="Change Price">
<input type="submit" name="delete" value="Delete Item">
<input type="submit" name="main" value="Main">

as well as:
<?PHP
if($_POST['main'] == "Main"){
    header('Location: http://hidden.edu/~test/457/1/index.php');
}elseif($_POST['dspphp'] == "Display Source" && $_POST['srcpw'] == "srcpass"){
    $_SESSION['srcsite'] = "store.php";
    header('Location: http://hidden.edu/~test/457/1/source.php');
}elseif($_POST['add1'] == "Add Item"){
    header('Location: http://hidden.edu/~test/457/1/additem.php');
}elseif($_POST['chgprice'] = "Change Price"){
    header('Location: http://hidden.edu/~test/457/1/changeprice.php');
}
?>

It autoforwards to changeprice.php. I just don't understand why it autoforwards there, and doesn't to the others. I have tried moving it around in the page but nothing seems to help. I can open the page directly, and it works fine. If I change changeprice.php to, say, index.php it autoforwards there instead. Any ideas?
Thanks for the input.

A: Change:
}elseif($_POST['chgprice'] = "Change Price"){

to:
}elseif($_POST['chgprice'] == "Change Price"){

A: The problem is that ALL input fields are submitted. So you're getting all four of your submit button values.
What you want is:
<input type="submit" name="submit" value="Add Item" />
<input type="submit" name="submit" value="Change Price" />
<input type="submit" name="submit" value="Delete Item" />
<input type="submit" name="submit" value="Main" />

and on the server:
 switch($_POST['submit']) {
     case 'Add Item':
         ...
         break;
     case 'Change Item':
         etc...
         break;
     default:
         ....
 }


text:
Q: How to get Css Background image URL text from relative URL? I want to get text of background-image URL.
Expect Output:
123
http://123.com
 (It is empty)

But Actual Output:

$('#p1').html($('#bg1').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
$('#p2').html($('#bg2').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));
$('#p3').html($('#bg3').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""));

I know that this function can be implemented by manipulating strings.
Is there any other way?
I know this css is not specification, But I want to write GreaseMonkey UserScript to hack other Website.
Solved:
This style.backgroundImage saved me! Thank!

$.fn.extend({
    getBackgroundUrl: function () {
        let imgUrls = [];
        $(this).each(function (index, ele) {
            let bgUrl = ele.style.backgroundImage || 'url("")';
            bgUrl = bgUrl.match(/url\((['"])(.*?)\1\)/)[2];
            imgUrls.push(bgUrl);
        });
        return imgUrls.length === 1 ? imgUrls[0] : imgUrls;
    }
});

$('p').html($('a').getBackgroundUrl().join(','));

A: You can do that a lot easier with a single regular expression: match the url and the opening parentheses, capture the single or double quote, then capture and lazy-repeat characters until you get to the next single or double quote:

const getUrl = str => str.match(/url\((['"])(.*?)\1\)/)[2];
$('a').each((_, a) => console.log(getUrl(a.style.backgroundImage)));

No need for a big library like jQuery just to select elements, you can do it in vanilla JS quite easily too:

const getUrl = str => str.match(/url\((['"])(.*?)\1\)/)[2];
document.querySelectorAll('a').forEach((a) => {
  console.log(getUrl(a.style.backgroundImage));
});


text:
Q: IllegalStateException: Can't change tag of fragment was android:switcher now android:switcher My activity uses TabLayout + ViewPager.
The number of tabs and pages here are dynamic depending on the data fetch from the server.
The crash are reported via Crashlytics,  I'm not able to replicate it.
My Activity code:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        boolean isAppRestarting = PrefUtils.getBoolean("app_restarting", false);
        if (isAppRestarting) {
            super.onCreate(null);
            this.savedInstanceState = null;
        } else {
            super.onCreate(savedInstanceState);
            this.savedInstanceState = savedInstanceState;
        }

        initSlidingTabs();

        fetchSomeData(); // see onDataFetched() below
    }

private void initSlidingTabs() {
        List<FragmentWithTitle> sdsTabs = new ArrayList<>();
            Logger.i("There is saved instance state");
            ArrayList<String> titles = savedInstanceState.getStringArrayList(TAB_TITLES);
            if (titles != null) {
                for (int i = 0; i < titles.size(); i++) {
                    if (getFragment(i) != null) {
                        sdsTabs.add(new FragmentWithTitle(getFragment(i), titles.get(i)));
                    }
                }
            }

        mTabsAdapter = new MyTabsAdapter(getSupportFragmentManager(), sdsTabs);

        mViewPager = (ViewPager) findViewById(R.id.layoutViewPagerSlidingTabs);
        mViewPager.setAdapter(mTabsAdapter);
        mViewPager.setOffscreenPageLimit(2);

        mSlidingTabs = (TabLayout) findViewById(R.id.tabs);
        mSlidingTabs.setupWithViewPager(mViewPager);
}

@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mTabsAdapter != null) {
            outState.putStringArrayList(TAB_TITLES, mTabsAdapter.getTitles());
        }
    }

    private Fragment getFragment(int position) {
        return savedInstanceState == null ? mTabsAdapter.getItem(position) : getSupportFragmentManager()
                .findFragmentByTag(getFragmentTag(position));
    }

    private String getFragmentTag(int position) {
        return "android:switcher:" + R.id.layoutViewPagerSlidingTabs + ":" + position;
    }

/**
Callback of fetchData() in onCreate()
*/
private void onDataFetched(List<AbcObject> abcObjects) {
        if (savedInstanceState == null) {
            if (abcObjects != null) {
                for (AbcObject abcObject : abcObjects) {
                    mTabsAdapter.addTab(new FragmentWithTitle(AbcFragment.newInstance(), abcObject.getTitle()));
                }
            }
        } else {
            Logger.d("There is saved instance state");
            ArrayList<String> titles = savedInstanceState.getStringArrayList(TAB_TITLES);
            if (titles != null) {
                for (int i = 0; i < titles.size(); i++) {
                    mTabsAdapter.addTab(new FragmentWithTitle(getFragment(i), titles.get(i)));
                }
            }
        }

        mTabsAdapter.notifyDataSetChanged();
    }

MyTabsAdapter:
public class MyTabsAdapter extends FragmentPagerAdapter {

    private List<FragmentWithTitle> mTabs = new ArrayList<>();

    public MyTabsAdapter(FragmentManager fm, List<FragmentWithTitle> sdsTabs) {
        super(fm);
        this.mTabs = sdsTabs;
    }

    @Override
    public Fragment getItem(int position) {
        return mTabs.get(position).getFragment();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTabs.get(position).getTitle();
    }

    @Override
    public int getCount() {
        return this.mTabs.size();
    }

    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    /**
     * Prevent java.lang.IllegalStateException Fragment no longer exists for key android:target_state: index 5
     *
     * @return
     */
    @Override
    public Parcelable saveState() {
        return null;
    }

    public ArrayList<String> getTitles() {
        ArrayList<String> titles = new ArrayList<>();
        for (int i = 0; i < mTabs.size(); i++) {
            titles.add((String) mTabs.get(i).getTitle());
        }
        return titles;
    }

    public void addTab(FragmentWithTitle fragmentWithTitle) {
        mTabs.add(fragmentWithTitle);
    }
}

Full stacktrace:
Fatal Exception: java.lang.IllegalStateException: Can't change tag of fragment ShopFrag{4dbb6e90 #0 id=0x7f1200dd android:switcher:2131886301:0}: was android:switcher:2131886301:0 now android:switcher:2131886301:9
       at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:444)
       at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:426)
       at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:103)
       at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1038)
       at android.support.v4.view.ViewPager.populate(ViewPager.java:1252)
       at android.support.v4.view.ViewPager.populate(ViewPager.java:1120)
       at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1646)
       at android.view.View.measure(View.java:17396)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
       at android.view.View.measure(View.java:17396)
       at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
       at android.view.View.measure(View.java:17396)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
       at android.view.View.measure(View.java:17396)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
       at android.view.View.measure(View.java:17396)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at android.view.View.measure(View.java:17396)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
       at android.view.View.measure(View.java:17396)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5365)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2505)
       at android.view.View.measure(View.java:17396)
       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2175)
       at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1316)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1513)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1200)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6401)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
       at android.view.Choreographer.doCallbacks(Choreographer.java:603)
       at android.view.Choreographer.doFrame(Choreographer.java:573)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
       at android.os.Handler.handleCallback(Handler.java:733)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:157)
       at android.app.ActivityThread.main(ActivityThread.java:5335)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
       at dalvik.system.NativeStart.main(NativeStart.java)

FragmentWithTitle:
public class FragmentWithTitle {
    public FragmentWithTitle(Fragment mFragment, CharSequence mTitle) {
        this.fragment = mFragment;
        this.title = mTitle;
    }

    public Fragment getFragment() {
        return fragment;
    }

    public void setFragment(Fragment fragment) {
        this.fragment = fragment;
    }

    public CharSequence getTitle() {
        return title;
    }

    public void setTitle(CharSequence title) {
        this.title = title;
    }

    private Fragment fragment;
    private CharSequence title;
}

A: The FragmentPagerAdapter already caches the Fragments for you. Each fragment is assigned a tag, and then the FragmentPagerAdapter tries to call findFragmentByTag. It only calls getItem() if the result from findFragmentByTag is null.
You're probably getting this error because you're adding the same fragment instance to the list. You should create a new instance for each page.
Example form document :
//...
      public static class MyAdapter extends FragmentPagerAdapter {
            public MyAdapter(FragmentManager fm) {
                super(fm);
            }

            @Override
            public int getCount() {
                return NUM_ITEMS;
            }

            @Override
            public Fragment getItem(int position) {
                return ArrayListFragment.newInstance(position);// IMPORTANT
            }
        }
    //..

Refer :FragmentPagerAdapter
Main thread : Retrieve a Fragment from a ViewPager


text:
Q: how to retain checkbox status during pagination in struts i am developing web application in struts 1.3 i am using display tag to display data i have checkbox in table display.i am   new in dispaly tag, pagination all I want to maintain the state of checkboxes across pages. What happens is when i check one checkbox and then go to say 2nd page then check one checkbox there and when i return to previous page the checked box is again unchecked. Means the status of the checkbox is not maintained.If it is maintained then it should show checked. when i goto next or previous page my action class is called everytime
i am not understanding how handle this . Any kind of help would be greatly appreciated.

A: Generally, solving this problem has several ways if struts framework does not provide the feature.

*

*pass the checked value to page2 and pass back when switch from page2 to page1.

*save the checked value in cookie and add code in page1 to reload the checked value in cookie.

*save the checked status in server session.
Hope it would be helpful to you.


text:
Q: SQL; How to insure data integrity in complex situations I have three tables named, Customer , Product , Sale . I need to know which products has been presented in which Sales and which customers have been attended to which Sales. So here is what we have so far:
Customer (Id, Name)

Product (Id, Name)

Sale(Id, Title, Date)

CustomerSale(Id, CustomerId, SaleId) //intermediate table

ProductSale(Id, ProductId, SaleId)   //intermediate table

Also I need to know which customer likes (just imagine they can up-vote products!) which products in each Sale and also I need to know which customer mark which product as useful in each Sale. So I have two solutions:
Scenario 1: simply make an intermediate table between those two intermediate tables!
CustomerProduct(Id, customerSaleId, productSaleId, doesLikes, isUseful)

Scenario 2: make an intermediate with FK to three tables (Customer, Product, Sale)!
CustomerProduct(Id, SaleId, CustomerId, ProductId, doesLikes, isUseful)

Problem:
None of the above solutions insure data integrity because in scenario1 it is possible to insert customerSaleId and productSaleId which does not refer to the same Sale. In scenario2 it is possible to insert an invalid (Sale, Customer, Product) triple. because you cannot be sure whether the product is presented in that Sale or not moreover you cannot be sure the customer has attended to that sale or not.
So is there any better solution?

A: If you ignore the surrogate keys on CustomerSale and ProductSale and have scenario 2 reference the compound unique keys on these tables of (CustomerId, SaleId) and (ProductId, SaleId) respectively would this give you what you want?

A: I change your structure to this
Customer (Id, Name)

Product (Id, Name)

Sale(Id, CustomerId, Title, Date)

ProductSale(Id, ProductId, SaleId)

CustomerProduct(Id, productSaleId, doesLikes, isUseful)

isn't it better?


text:
Q: How to create small maven project using command line I was trying to create new maven project to check whether maven is working.

So I tried this.
mvn archetype:create

  -DgroupId=your.simple.java.gid

  -DartifactId=your-simple-java-aid

But Sadly I got a huge error saying

NoClassDefFoundError for org/codehaus/plexus/util/xml/XmlStreamReader

Please help me with this.

I tried various question but they all helping to create projects using IDE.

Thank you.

A: Instead of using create use generate.
mvn archetype:generate  -DgroupId=your.simple.java.gid  -DartifactId=your-simple-java-aid

This will create the project in Interactive mode. It will ask you different input from you while generating your project.
You can ignore the Interactive mode by setting it to false. This will be batch mode.
mvn archetype:generate  -DgroupId=your.simple.java.gid  -DartifactId=your-simple-java-aid -DinteractiveMode=false

You can take a look here for more details: Maven in 5 Minutes


text:
Q: BigCommerce API - SKU insertion error with product_option_id I'm using BigCommerce's API and trying to create a Product (from scratch) which has unique Options, Option Sets, and SKU inventories.  After creating the options, option sets, and product, I attempt to POST a SKU with the following JSON:
{"sku": "FM-MIX46-RA1", "inventory_level": 10,
 "options": [{"option_value_id": 229,"product_option_id": 76},
             {"option_value_id": 226, "product_option_id": 75}]
}

The product_option_id values correspond to the id of Option objects, while the option_value_id values correspond to the id of child Value objects sharing the same Option id.
The JSON response received from BigCommerce is as follows:
{'status': 400,
 'message': "The field 'product_option_id' is invalid.",
 'details': {'product_option_id': 76}
}

There are several queries in SO from users struggling to access the Product or SKU (using one or the other) in order to update inventory levels and I want to emphasize that my problem is markedly different, as my SKU objects do not exist and I have no issues with the logical design of the data model or a language binding which sits above the REST API.

A:
The product_option_id values correspond to the id of Option
  objects while the option_value_id values correspond to the id of
  child Value objects sharing the same Option id.

Here is your problem: Its not the id of the option but product_option_id
request "products/{product_id}/options"
to get the id of the option you are after


text:
Q: "left everything to" or "left everything on"? Wich of the two sentence is the right one? why?

a) He never tried to mend things on his own and left everything to her
b) He never tried to mend things on his own and left everything on her

A: In general, in the context of doing work, "leave (something) to (someone)" just says that you will not do it and expect that the other person will do it instead.  Depending on the situation and relationship, this isn't necessarily a bad thing, it may just be a normal and expected course of events, so it doesn't imply anything about how the other person feels or is affected by it (it could be good or bad).
However, saying "leave (something) on (someone)" usually has more of an implication that it is a burden to them in some way.  So your second sentence conveys the impression that this is not a good situation, and he is likely being inconsiderate towards her by expecting her to do the work instead of him.
Both can be used and technically mean the same thing, it's just a question of the feeling that the sentence conveys.  This may also vary somewhat based on context (for example, in a lot of contexts, the burden may be obvious enough that you don't need to use "on" to show it).


text:
Q: String concatenation? I am trying to understand string concatenation.
Why doesn't the fourth line give the same result as the second one?
counter = 0
"#{counter+1}. test" gives "1. test"
counter = 0
"#{++counter}. test" gives "0. test"

A: ++ just looks like the increment operator. It's actually two unary + operators, so it's just the same as plain old counter

A: Because, ++ is not an operator for Ruby like C or Java.

A: There is no ++ operator in Ruby. What ++counter says is "give me the positive result of the positive result of 0" which is 0.

A: ++ is not an operator in Ruby. If you want to use a pre-increment operator then use:
counter += 1

A: In Ruby, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ......  or +x == +++x == +++++x == ......
To increment a number, simply write x += 1.
To decrement a number, simply write x -= 1.
Proof :
x = 1
+x == ++++++x # => true
-x == -----x # => true
x # => 1 # value of x doesn't change.

A: In C
++counter //Pre Increment
counter++// Post Incremet

But In Ruby ++ has no existence ,
So if you want to increment a variable then you have to simply write
counter = counter + 1

In your case you have to write just
 "#{counter = counter + 1}. test" gives "1. test"

And will increment the value counter  by 1


text:
Q: jQuery Captcha using Drag-n-Drop: How bot-proof is this? I am currently employing a CAPTCHA technique which requires a visitor to rearrange some items into the "correct" order before proceeding. Here is a jsFiddle with my technique.
I am wondering exactly how bot-proof this is?
Is it possible someone could inject some JS like this into my page to programmatically reorder the items?
$("div.cItem"):contains('0').appendTo('#captcha');
$("div.cItem"):contains('1').appendTo('#captcha');
$("div.cItem"):contains('2').appendTo('#captcha');
$("div.cItem"):contains('3').appendTo('#captcha');
$("div.cItem"):contains('4').appendTo('#captcha');
$("div.cItem"):contains('5').appendTo('#captcha');

UPDATE
Sorry bout the link to the non-functional jsfiddle link. That is fixed.

A:
Is it possible someone could inject some JS like this into my page to
  programmatically reorder the items?

Yes. It would be fairly trivial to create a script to automatically reorder the divs.
That said, bots do not typically use Javascript. They just create a POST request. If it is possible to submit the form without Javascript enabled, then it is not very effective.
If you require Javascript to be enabled to submit the form, that is terrible for accessibility.
But to address the general idea: you should consider that computers are much better at rearranging lists of numbers than humans are. If you want it to cater to humans and not computers, you should have users rearrange something harder for computers to calculate. I don't know what would be best, maybe arranging pictures of animals from smallest to largest or something like that.

A: I'm sorry but that is pretty non bot proof. All a bot will need to do is assemble a post and post it back  completely avoifing your humad  check

A: I'd just programatically build whatever POST values you're looking for. :|
You could get crazy, have the sever generate them, pass UUIDs to all items, store it in the session, etc. etc. but if it's anything easy (like numbers) you can just run OCR against it.

A: I think there aren't a lot of bots (classic ones using curl, ...) using javascript, so I think this is fair one.
OT: Can I use it for my project? It looks nice and bullet-proof :P

A: No client-side verification is bot-proof.  Anyone who studies your page can work-around it easily since the logic to bypass it is right in your page javascript.  To make something bot-proof, you need server-side verification of a human action.

A: That's impossible to say from your example, as it only contains the user interface.
What would make it bot proof is the way that you send the result to the server. A bot would not use the Javascript on the page to bypass the CAPTCHA, it would just try to return the right result to the server. The result should be impossible to determine by itself, i.e. you should not just send "012345" back to the server. The identities of the blocks should be random, and their number not easily determined by just reading the content of the elements.
Side note: Sorting on random is not a very good way to shuffle items. A Fisher-Yates shuffle is easy to implement.


text:
Q: Send video file to save on android phone using C program Using C program, I want to send a video file to my android mobile and save (or download) it on the phone.
Right now I have made an android app from which I can send messages/text to C server. (using socket programming)
And i want my C server to send video back to my android phone(client)  when it receive the message "send video"
Guide me please. How can I achieve this ? Any related links would be appreciated...
Please help!

A: Here is one article which can help you to achieve what you are looking for-
Java and C socket communication
I have worked on it once(long time back). They are using a Java client here, you can use your Android app. It's a brilliant article.


text:
Q: Returning ObjectID as a string from ASP.NET Core How to you get a string representation of the ObjectId returned via ASP.NET Core.
I have the following result of an action in my controller:
return new ObjectResult(new { session, user });

One of the user properties is the UserId that is of the ObjectId type.
However, this gets returned in the response as
"id": {
  "timestamp": 1482840000,
  "machine": 6645569,
  "pid": 19448,
  "increment": 5052063,
  "creationTime": "2016-12-27T12:00:00Z"
}

I would like the response to simply be 58625d5201c4f202609fc5f3 that is the string representation of the same structure.
Are there any easy way to do this for all returned ObjectIds?
EDIT
Adding some more data
Here are the user class. ObjectId is MongoDB.Bson.ObjectId
public class User
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string PasswordHash { get; set; }
    public string PasswordSalt { get; set; }
}

The get method in my controller. Controller is Microsoft.AspNetCore.Mvc.Controller.
[HttpGet("{id}", Name = "GetUser")]
public async Task<IActionResult> Get(ObjectId id)
{
    var user = await _repository.GetOne<User>(id);
    if (user == null) return NotFound();
    return new ObjectResult(user);
}

And this is the method from my repository:
public async Task<T> GetOne<T>(ObjectId id)
{
    var collectionname = typeof(T).Name;
    var collection = _database.GetCollection<T>(collectionname);
    var filter = Builders<T>.Filter.Eq("_id", id);
    var result = await collection.Find(filter).ToListAsync();
    return result.FirstOrDefault();
}

A: You have to explicitly write a ObjectID to JSON convertor. Please check the link below:
https://stackoverflow.com/a/37966098/887976


text:
Q: Azure AD bearer Token in header to authenticate request to web API - Problem with update method May I know how we UDPATE record with bearer token. Below is my code of Service.js and authProvider.js. Rite now, it authorizes the API but doesn't update the record. When I inspect in Dev tools, the Request Method shows 'GET' instead of 'PUT' for update. Whereas my GET method (authFetch with GET) works fine though (I am able to retrieve record from the database with authorization). Can anyone point me in the right direction?
service.js:
 export async function getItem(ItemNo) {
    return await authFetch(config.apiBaseUrl + `/item/${ItemNo}`, 'GET');
 }

 export async function updateItem(ItemNo, data) {
    return await authFetch(config.apiBaseUrl + `/item/${ItemNo}`, 'PUT', data);
 }

authProvider.js:

import { MsalAuthProvider, LoginType } from 'react-aad-msal';

//authFetch will return fetch method with ID Token in Authorization header.
export const authFetch = async (url, method, body) => {
const token = await authProvider.getIdToken();
return fetch(url, {
    method: body,
    headers: {
        Authorization: 'Bearer ' + token.idToken.rawIdToken,
        'Content-Type': 'application/json',
    },
    body: method === 'PUT' ? JSON.stringify(body) : undefined
});

};
In the component:
FetchItem.js:
    async updateTutorial) {
    await updateItem(this.state.currentItem.itemNo,
        this.state.currentItem).then(
            (response) => {
                if (response.ok) {
                    response.json()
                        .then((responseData) => {
                            this.setState({
                                isLoading: false,
                                message: "Item updated successfully!"
                            })
                        });
                }
                else if (response.status === 401) {
                    throw new Error("User not authorized");
                }
                else {
                    throw new Error("Not working");
                }
            })
        .catch((err) => {
            console.error(err);
            this.setState({ isLoading: false, currentItem: 'Error: ' + err.message });
        });
}

A: You could try by changing your authFetch method to something like:
export const authFetch = async (url, method, body) => {
    const token = await authProvider.getIdToken();
    return fetch(url, {
        method: body,
        headers: {
            Authorization: 'Bearer ' + token.idToken.rawIdToken,
            'Content-Type': 'application/json',
            //'Accept': 'application/json' // Add this line in addition
        },
        body: method === 'PUT' ? JSON.stringify(body) : undefined
    });
};

and then call them like following:
 export async function getItem(Serienr) {
    return await authFetch(config.apiBaseUrl + `/item/${ItemNo}`, 'GET');
 }

 export async function updateItem(ItemNo, data) {
    return await authFetch(config.apiBaseUrl + `/item/${ItemNo}`, 'PUT', data);
 }

Please note that the code above is untested so you may run into issues.


text:
Q: Strange mouse bug on linux On the laptop is sometimes spontaneously mouse runs across the screen . Movements are not like lucid . This continues even when you connect the wireless mouse . Now I use arch.

A: By my experience mouse related problems are in most cases due to mechanical or physical problems like the material of the table or stuff stuck on the sensor.
Try if this still happens when the mouse is disconnected, if it is a laptop it might be because you are touching the touch-pad without knowing.
As Erick pointed, check if it happens only on Linux and if its really a problem of the OS or the mouse itself.
You may also want to check this thread on superuser.

A: Does it happen only on Linux?
I had a problem like this once, when my laptop was connected to an not-well-grounded power outlet in University (all plugs in a particular room were like that). The electrostatic was interfering with the touchpad.


text:
Q: realizar consulta con ajax y mostrar en input text Deseo obtener un valor de una tabla a través de una consulta. El resultado lo obtengo pero en un DIV, lo deseo en una caja de texto.
Index.php

 <title>Ejemplo sencillo de AJAX</title>

<?php
include 'prueba_consulta.php';
?>

<form method="post">
  <input type="text" name="nombre" size="30" name="" id="nombre">
  <input type="button" name="" value="enviar" onclick="enviar()">

  </form>
<input type="text" value="<?php echo($row['nombre_site']);?>">

Prueba_consulta.php

<?php
//************ conexion a BD ***************
    $con = mysql_connect("localhost","root","");
    mysql_select_db("mantenimiento",$con);

 $filtro=$_POST["nombre"];
 $rs= mysql_query("SELECT * FROM registro_energia_temp WHERE nombre_site like '%$filtro%' order by id_energia desc ;");

$row = mysql_fetch_assoc($rs);

$nombre_site= $row['nombre_site'];
echo $nombre_site; //este valor se completa en el DIV y deseo mostrarlo en la caje de texto
?>

De antemano muchas gracias. Exitos!!!

A: Para mostrar el valor en un input debes hacer lo siguiente:
<input type="text" id="idinput">

$.ajax({
    type:'post',
    url: 'prueba_consulta.php',
    data: datos,
    //data: {nombre:n},
    success: function(d){
      $("#idinput").val(d);
    }
});

Simplemente es asignarle un id a tu input, capturarlo y con .val() darle su valor !


text:
Q: Proving $b-1\geq n(b^{1/n}-1)$ Question
Prove $b-1\geq n(b^{1/n}-1)$ from $b^n-1\geq n(b-1)$ where $n$ is an integer and $b>1,y>0$.
Attempt
Why does putting $n = 1/n'$ doesn't provide the required expression?
$$b^n-1\geq n(b-1) $$
$$ b^{1/n'}-1\geq 1/n'(b-1)$$
$$ n'(b^{1/n'}-1)\geq (b-1)$$
$$ n(b^{1/n}-1)\geq (b-1)$$
P.S. I am aware of how to solve the question (Substitute $ b=b^{1/n'} $). Just interested to know why this method doesnt work.
If the argument is $1/n'$ is not an integer for integer $n'$ then why does the substitution $ b=b^{1/n'} $ works?

A: Because $n' < 1$ when $n > 1$.  You can't apply the same inequality for $n$ and substitute with $n'$ if they are not both greater or both less than $1$.
The inequality sign is reversed in the Bernoulli inequality when the exponent is less than $1$:
$$b^n \geqslant 1 + n(b-1), \\ b^{1/n} \leqslant 1 + \frac{1}{n} (b-1).$$
Also the exponent can be any real positive real number.

A: Let $b^{\frac{1}{n}}=t$.
Thus,
$$b-1=t^n-1=(t-1)(t^{n-1}+...+1)\geq(t-1)n=n\left(b^{\frac{1}{n}}-1\right).$$


text:
Q: How to connect Kafka with Camel Spring Boot What options do I have for connecting Kafka with Spring Boot Camel?
I'm running ActiveMQ Artemis and Camel to make JMS/MQTT and REST routes to/from clients.
I would like to add Kafka to that duo to stream/exchange data (video+audio, files/text).
So far I downloaded Kafka Confluent Platform (free trial) and I'm testing what they offer. In Confluent Platform I see it is possible to add connectors as a "plugins". I assume that way I can add Camel connector but that seems bad solution to me because I would like to play with the routes and see what is under the hood and here I don't see that is possible, or am I wrong?
Other option I'm thinking of, is to download Apache Kafka, Zookeeper, add Kafka Spring Boot dependency to Camel pom.xml and then make Camel routes like in samples here. Am I on the right track?

A: Kafka-Broker
If you want to play around, I recommend to install Kafka (it also brings Zookeeper) on your development machine. It is easiest to use a package manager for your operating system. For example if you work on Windows, you can install Scoop.
Then you can install the current version of plain Kafka (not confluent platform) with a one-liner:
scoop install kafka

After installation you can start first zookeeper, then kafka with the provided bat/sh scripts in the bin folder.
Camel
In your Camel project (no matter if Spring Boot or not) you only need to add camel-kafka to your dependencies.
The route endpoint URI for a Kafka broker running on your local machine is
kafka:[topic-name]?brokers=localhost:9092

You can use such URIs for consumer (from("kafka:...")) or producer (.to("kafka:..."))


text:
Q: Getting a run time error when calling a function that uses a "for" loop to fill the data of a global structure I'm new to programming and have been playing around with functions. So I've decided to make a simple program that gets the user's score for the movies he/she has watched.
The code in question is incomplete; but I ran into an error while testing along the way:
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;

struct movie_show
{
    char movie_title[50];
    float movie_story, movie_characters, movie_art;
    float average_score;
};

/*************************************************************************/

int main()
{
    printf("[MOVIE RATER]\n\n");

    NumMovie();
    RatingMovie();

    printf("\n\n");
    getch();
    return 0;
}

/*************************************************************************/

void NumMovie()
{
    int num_movie;

    printf("How many movies would you like to rate: ");
    scanf(" %d", &num_movie);

        if(num_movie < 1)
        {
            exit(0);
        }

    RatingMovie(num_movie);

}

/**************************************************************************/

void RatingMovie(int num_movie)
{
    int i;
    struct movie_show mov_show[num_movie];

    for (i = 0; i < num_movie; i++)
    {

        printf("movie #%d", i + 1);
        getchar();
        printf("\nTitle: ");
        fgets(mov_show[i].movie_title, 50, stdin);
        scanf(" %s", mov_show[i].movie_title);

        printf("\nBased on a 1-10 rating scale, how would you rate the: ");
        printf("\nStory: ");
        scanf(" %f", &mov_show[i].movie_story);

    }

}

This function in particular makes the program stop after executing the loops:
void RatingMovie(int num_movie)
{
    int i;
    struct movie_show mov_show[num_movie];

    for (i = 0; i < num_movie; i++)
    {

        printf("movie #%d", i + 1);
        getchar();
        printf("\nTitle: ");
        fgets(mov_show[i].movie_title, 50, stdin);
        scanf(" %s", mov_show[i].movie_title);

        printf("\nBased on a 1-10 rating scale, how would you rate the: ");
        printf("\nStory: ");
        scanf(" %f", &mov_show[i].movie_story);

    }

}

Thank you in advance.

A: In your main(), you call
   RatingMovie();

But RatingMovie's definition is
void RatingMovie(int num_movie);

Indicates RatingMovie() expects an int as a parameter.
Since you did not declare RatingMovie() before caling it in main(), the compiler at that point thinks RatingMovie takes no parameter and returns an int.
At runtime, when your program calls RatingMovie() from main(), RatingMovie(int num_movie) receives garbage as its num_movies parameter, resulting in undefined behavior.  In  this case your program crashes, probably because num_movie is negative or really big.
Other issues are imho:

*

*You call RatingMovie() twice in your code.  Pick one.

*struct movie_show mov_show[num_movie];  num_movie is not a constant, this is non-standard C.  Use a constant for the maximum of movies, or allocate an array with calloc() or malloc()

*calling exit(0); from NumMovie()  is not very elegant.  There must be a more elegant way of handling exit as part of the normal flow of your app.

If you move all of your function bodies before main(), and reorder your functions and fix all issues until your compiler issues no more warnings, your program should run fine.