text:
Q: How to get the correct value of / and % operators? I want to do the following things:
I use a variable int a to keep the input from the console, and then I do the following:
int b = a / 16;

When a is 64 or 32, I get 4 or 2. But if a is 63, I expect to get 4, but I get 3. Are there any ways in C to get a rounded value?
Edit. More details:
rang 1 to 16 should get 1,
rang 17 to 32 should get 2,
rang 33 to 48 should get 3,
rang 49 to 64 should get 4

A: When you use the division operator / with two int arguments, it will returns an int representing the truncated result.
You can get a rounded-up division without using floating point numbers, like this :
int a;
int den = 16;
int b = (a + den - 1) / den;

Which will give you what you expect :
a ∈      [0], b =        0 / 16 = 0,
a ∈  [1, 16], b = [16, 31] / 16 = 1,
a ∈ [17, 32], b = [32, 47] / 16 = 2,
a ∈ [33, 48], b = [48, 63] / 16 = 3,
a ∈ [49, 64], b = [64, 79] / 16 = 4,
...

Note that this only work if a and b are positives, and beware of the possible overflow of a + den.
If a + den is suspected to possibly overflow, then you could use another version of this expression :
int b = (a - 1) / den + 1;

The only downside is that it will return 1 when a = 0. If that's an issue, you can add something like :
int b = (a - 1) / den + 1 - !a;

Note that you can also handle negative values of a the same way (round away from zero) :
int b = (a > 0) ? (a - 1) / den + 1 : (a - den + 1) / den;

A: Integer division / in C does not do rouding, instead, it does truncation.

A: Solution
int ans, newNo;
int no = 63; // Given number
int dNo = 16; // Divider

newNo = (no % dNo) ? (dNo - (no % dNo) + no) : no; // Round off number

ans = newNo / dNo;

Edit
Optimize solution
ans = (no / dNo) + !!(no % dNo);

A: You can try using following
 int b = (int)ceil((double)a/16);

A: whatever you are trying is conceptualy not correct but still if you want the same result as you said in your question , you can try for standard function double ceil(double x) defined in math.h
Rounds x upward, returning the smallest integral value that is not less than x.

A: The simplest way to get what you want is to use float numbers.
#include <math.h>
#include <stdio.h>

int main(void)
{
  double a = 63.0;
  double b = 16.0;

  printf("%d", (int) round(a / b));

  return 0;
}

Carefully pay attention when casting from float numbers to int, and vise versa. For example, round(63/16) is incorrect. It returns a double, but achieves nothing, since the literals 63 and 16 are integers. The division is done before the value is passed to the function. The correct way is to make sure that one or both operands are of type double: round(63.0 / 16.0)

A: Since C int division always rounds towards zero, a simple trick you can use to make it round evenly is to add "0.5" to the number before the rounding occurs. For example, if you want to divide by 32, use
x = (a+16)/32;

or more generally, for a/b, where a and b are both positive:
x = (a+b/2)/b;

Unfortunately negative numbers complicate it a bit, because if the result is negative, then you need to subtract 0.5 rather than add it. That's no problem if you already know it will be positive or negative when you're writing the code, but if you to deal with both positive and negative answers it becomes messy. You could do it like this...
x = (a+((a/b>0)?1:-1)*(b/2)) / b;

but by that stage it's starting to get pretty complex - it's probably better to just cast to float and use the round function.
--
[Edit] as zakinster pointed out, although the question asked for 'round' values, the examples given actually require ceil. The way to do that with ints would be:
x = (a+b-1)/b;

again, if the answer can be negative this gets complicated:
x = (a+((a/b>0)?1:-1)*(b-1)) / b;

I'll leave my original response for even rounding just in case someone is interested.


text:
Q: what does the flag IRQF_SAMPLE_RANDOM specify while registering interrupt handlers? In request_irq() to register interrupt handlers, why we use the flag IRQF_SAMPLE_RANDOM and what is entropy pool?

A: The entropy pool collects randomness for the /dev/random and /dev/urandom devices.
In outdated kernels, you would have used IRQF_SAMPLE_RANDOM to tell the kernel that the times at which your device generates interrupts are unpredictable.
Since kernel version 3.6, the kernel handles interrupt randomness automatically, and this flag no longer exists.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read from a file using fstream void Tutorial() {
    fstream myFile;
    myFile.open("Tutorial.txt", ios::in);
    if (myFile.is_open()) {
        string line;
        while (getline(myFile, line))
        {
            std::cout << line << endl;
        }
        myFile.close();
    }
}

I have a file inside the folder called tutorial.txt, but it does not print out the characters in the console when the function is called.

A: Set the working directory here (right click , properties on the project)


text:
Q: GCC/G++ : Enable -std=c++11 from environment variable I have some OpenCV/C++ application which compiles with a CMake definitions file, in which I did not find a way to pass flags to the compiler.
I know that there are the flags C_INCLUDE_PATH CPLUS_INCLUDE_PATH, and all the rest of their friends...
But, is there an environment variable for definition of any other flags, in which I'd be able to define -std=c++11 ?

A: If you're using CMake, equally easy and nicer solution will be to pass
-DCMAKE_CXX_STANDARD=11 -DCMAKE_CXX_STANDARD_REQUIRED=ON

to CMake.

A: The easiest but certainly not nicest solution if you want to force it by hand would be:
add_compile_options(-std=c++11)

However CMake should be able to pick the necessary standard for you. Have a look to this answer:
How to detect c++11 support of a compiler with cmake


text:
Q: Wordpress order categories by ID I am new to get terms and wanted to know if someone can help me.
How can I get this to show my categories in order or id that I want?
I want to show a number of categories in a specific order from a drop down.
Thanks!

        <?php
            $categories = get_terms( 'event-category' );

            $dropdown_options = array(
                "theme" => "dropdown_base",
                "label" => "Events by Category",
                'orderby' => 'ID',
'include' => '155',
                "links" => true
            );
        ?>
        Events by Category
        <select class="js-dropdown event_filter_select event_filter_category" id="event_filter_category" name="event_filter_category" data-dropdown-options="<?php my_json_attribute( $dropdown_options ); ?>">
            <option value="<?php my_page_link( 'calendar' ); ?>">All Categories</option>
            <?php
                foreach ( $categories as $category ) :
                    $link = get_term_link( $category->term_id );
                    $attr = ( strpos( $my_page_url, $link ) > -1 ) ? 'selected="selected"' : '';
            ?>
            <option value="<?php echo $link; ?>" <?php echo $attr; ?>><?php echo $category->name; ?></option>
            <?php
                endforeach;
            ?>
        </select>

A: wp_dropdown_categories() will list by id by default. It utilizes get_terms() as well, and provides a hook to toward the end if you wish to filter the html of $output further than the parameters allow. (I've added the source below).
It has the following parameters:

*

*'show_option_all'
      (string) Text to display for showing all categories.

*

*'show_option_none'
  (string) Text to display for showing no categories.

*'option_none_value'
  (string) Value to use when no category is selected.

*'orderby'
  (string) Which column to use for ordering categories. See get_terms() for a list of accepted values. Default 'id' (term_id).

*'order'
  (string) Whether to order terms in ascending or descending order. Accepts 'ASC' or 'DESC'. Default 'ASC'.

*'pad_counts'
  (bool) See get_terms() for an argument description. Default false.

*'show_count'
  (bool|int) Whether to include post counts. Accepts 0, 1, or their bool equivalents. Default 0.

*'hide_empty'
  (bool|int) Whether to hide categories that don't have any posts. Accepts 0, 1, or their bool equivalents. Default 1.

*'child_of'
  (int) Term ID to retrieve child terms of. See get_terms(). Default 0.

*'exclude'
  (array|string) Array or comma/space-separated string of term ids to exclude. If $include is non-empty, $exclude is ignored. Default empty array.

*'echo'
  (bool|int) Whether to echo or return the generated markup. Accepts 0, 1, or their bool equivalents. Default 1.

*'hierarchical'
  (bool|int) Whether to traverse the taxonomy hierarchy. Accepts 0, 1, or their bool equivalents. Default 0.

*'depth'
  (int) Maximum depth. Default 0.

*'tab_index'
  (int) Tab index for the select element. Default 0 (no tabindex).

*'name'
  (string) Value for the 'name' attribute of the select element. Default 'cat'.

*'id'
  (string) Value for the 'id' attribute of the select element. Defaults to the value of $name.

*'class'
  (string) Value for the 'class' attribute of the select element. Default 'postform'.

*'selected'
  (int|string) Value of the option that should be selected. Default 0.

*'value_field'
  (string) Term field that should be used to populate the 'value' attribute of the option elements. Accepts any valid term field: 'term_id', 'name', 'slug', 'term_group',    - 'term_taxonomy_id', 'taxonomy', 'description', 'parent', 'count'. Default 'term_id'.

*'taxonomy'
  (string|array) Name of the category or categories to retrieve. Default 'category'.

*'hide_if_empty'
  (bool) True to skip generating markup if no categories are found. Default false (create select element even if no categories are found).

*'required'
  (bool) Whether the  element should have the HTML5 'required' attribute. Default false.

function wp_dropdown_categories( $args = '' ) {
    $defaults = array(
        'show_option_all'   => '',
        'show_option_none'  => '',
        'orderby'           => 'id',
        'order'             => 'ASC',
        'show_count'        => 0,
        'hide_empty'        => 1,
        'child_of'          => 0,
        'exclude'           => '',
        'echo'              => 1,
        'selected'          => 0,
        'hierarchical'      => 0,
        'name'              => 'cat',
        'id'                => '',
        'class'             => 'postform',
        'depth'             => 0,
        'tab_index'         => 0,
        'taxonomy'          => 'category',
        'hide_if_empty'     => false,
        'option_none_value' => -1,
        'value_field'       => 'term_id',
        'required'          => false,
    );

    $defaults['selected'] = ( is_category() ) ? get_query_var( 'cat' ) : 0;

    // Back compat.
    if ( isset( $args['type'] ) && 'link' == $args['type'] ) {
        _deprecated_argument( __FUNCTION__, '3.0.0',
            /* translators: 1: "type => link", 2: "taxonomy => link_category" */
            sprintf( __( '%1$s is deprecated. Use %2$s instead.' ),
                'type => link',
                'taxonomy => link_category'
            )
        );
        $args['taxonomy'] = 'link_category';
    }

    $r = wp_parse_args( $args, $defaults );
    $option_none_value = $r['option_none_value'];

    if ( ! isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] ) {
        $r['pad_counts'] = true;
    }

    $tab_index = $r['tab_index'];

    $tab_index_attribute = '';
    if ( (int) $tab_index > 0 ) {
        $tab_index_attribute = " tabindex=\"$tab_index\"";
    }

    // Avoid clashes with the 'name' param of get_terms().
    $get_terms_args = $r;
    unset( $get_terms_args['name'] );
    $categories = get_terms( $r['taxonomy'], $get_terms_args );

    $name = esc_attr( $r['name'] );
    $class = esc_attr( $r['class'] );
    $id = $r['id'] ? esc_attr( $r['id'] ) : $name;
    $required = $r['required'] ? 'required' : '';

    if ( ! $r['hide_if_empty'] || ! empty( $categories ) ) {
        $output = "<select $required name='$name' id='$id' class='$class' $tab_index_attribute>\n";
    } else {
        $output = '';
    }
    if ( empty( $categories ) && ! $r['hide_if_empty'] && ! empty( $r['show_option_none'] ) ) {

        /**
         * Filters a taxonomy drop-down display element.
         *
         * A variety of taxonomy drop-down display elements can be modified
         * just prior to display via this filter. Filterable arguments include
         * 'show_option_none', 'show_option_all', and various forms of the
         * term name.
         *
         * @since 1.2.0
         *
         * @see wp_dropdown_categories()
         *
         * @param string $element Taxonomy element to list.
         */
        $show_option_none = apply_filters( 'list_cats', $r['show_option_none'] );
        $output .= "\t<option value='" . esc_attr( $option_none_value ) . "' selected='selected'>$show_option_none</option>\n";
    }

    if ( ! empty( $categories ) ) {

        if ( $r['show_option_all'] ) {

            /** This filter is documented in wp-includes/category-template.php */
            $show_option_all = apply_filters( 'list_cats', $r['show_option_all'] );
            $selected = ( '0' === strval($r['selected']) ) ? " selected='selected'" : '';
            $output .= "\t<option value='0'$selected>$show_option_all</option>\n";
        }

        if ( $r['show_option_none'] ) {

            /** This filter is documented in wp-includes/category-template.php */
            $show_option_none = apply_filters( 'list_cats', $r['show_option_none'] );
            $selected = selected( $option_none_value, $r['selected'], false );
            $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$selected>$show_option_none</option>\n";
        }

        if ( $r['hierarchical'] ) {
            $depth = $r['depth'];  // Walk the full depth.
        } else {
            $depth = -1; // Flat.
        }
        $output .= walk_category_dropdown_tree( $categories, $depth, $r );
    }

    if ( ! $r['hide_if_empty'] || ! empty( $categories ) ) {
        $output .= "</select>\n";
    }
    /**
     * Filters the taxonomy drop-down output.
     *
     * @since 2.1.0
     *
     * @param string $output HTML output.
     * @param array  $r      Arguments used to build the drop-down.
     */
    $output = apply_filters( 'wp_dropdown_cats', $output, $r );

    if ( $r['echo'] ) {
        echo $output;
    }
    return $output;
}


text:
Q: Plotly: How to change the trace order, or switch the sides of the axes in plotly? I am trying to get the line to display over the bar. It seems that whatever trace has secondary_y=True will be drawn on top of the one where secondary_y=False.
That's fine, but for this particular data set, the bar axis should be on the right, because otherwise this graph is confusing. The line is the one that is in the 1-3 range, and the bar is the one that is in the 0-35k range.
In other words, it should look just like this, but with y-axes switched. Is there some way to switch the axes, or control the order in which it draws the traces, so that I can force the line to be on top of the bars?

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from plotly.offline import init_notebook_mode,  plot
init_notebook_mode()

rdf = pd.read_csv('us_covid_data_latest.csv', dtype={'fips':str})
incidence = pd.pivot_table(rdf, values='cases', index = 'date', aggfunc=np.sum)
incidence['actual_inc'] = incidence['cases'].diff()

def tail_plot_plotly(tail):

    fig = make_subplots(specs=[[{"secondary_y": True}]])

    fig.add_trace(
        go.Bar(
            x= incidence['date'].tail(tail),
            y= incidence['actual_inc'].tail(tail)
            ),
        secondary_y = False
        )

    fig.add_trace(
        go.Scatter(
            x= incidence['date'].tail(tail),
            y= incidence['R_t'].tail(tail)
            ),
        secondary_y = True
        )

    plot(fig)

tail_plot_plotly(50)

A: It's not easy providing a complete solution without a sample of your dataset, but I still think I've figured it out. I'm in a bit of a hurry right now, so I'll make it short:
Bars are big numbers, lines are small numbers. Out of the box, a fig = make_subplots(specs=[[{"secondary_y": True}]]) would provide this:

Line trace on top = Good. Bar numbers to the left = Bad.
Changing the order of which yoy apply the different traces to the figure won't help. But you can freely specify on which side of the plot you'd like your primary and secondary y axis to appear like this:
fig.update_layout(dict(yaxis2={'anchor': 'x', 'overlaying': 'y', 'side': 'left'},
                  yaxis={'anchor': 'x', 'domain': [0.0, 1.0], 'side':'right'}))

Add that to the mix, and you'll get:

Line trace on top = Good. Bar numbers to the right = Good.
Complete code with a data sample:
# imports
import plotly.graph_objects as go
import numpy as np
from plotly.subplots import make_subplots

# set figure twith multiple y axes
fig = make_subplots(specs=[[{"secondary_y": True}]])

# blue line with numbers from 1 to 3
fig.add_trace(
    go.Scatter(x=[0, 1, 2, 3, 4, 5],
               y=[1.5, 1.0, 1.3, 2.7, 1.8, 2.9]),secondary_y=True)

# red bars with big numbers
fig.add_trace(
    go.Bar(x=[0, 1, 2, 3, 4, 5],
           y=[np.nan, np.nan, np.nan, 100000, 20000, 250000]))

# update layout to put axes and values in the desired positions
fig.update_layout(dict(yaxis2={'anchor': 'x', 'overlaying': 'y', 'side': 'left'},
                  yaxis={'anchor': 'x', 'domain': [0.0, 1.0], 'side':'right'}))

fig.show()


text:
Q: Kolmogorov complexity vs. intuitive notion of simplicity Consider the infinite sequence $1,2,4,8,16,...$ If one were asked how the sequence continues the answer would likely be $32,64,..,2^k,..$ and one would implicitly assume the question to be about the "simplest" solution. Mathematically speaking the question is ill posed as there is no universal definition of "simple".
Suppose we are given a finite, increasing sequence $(a_i)$. We define the simplest "infinite expansion" of $(a_i)$ to be the infinite language $L\subseteq\mathbb{N}$ for which we have the shortest Turing machine that recognizes $L$, and (assuming the natural ordering on $L$) $(a_i)$ would be the starting fragment of $L$.
I would like to understand how well this definition agrees with the intuitive (vague) notion of simplicity. Has this been studied before and are there any examples of simplest solutions for some given starting fragment?

A: For Kolmogorov complexity to make sense one needs a Turing-complete language. Javascript is nice and compact but inconvenient because it doesn't have arbitrary precision, so let's use Python instead. Define a sequence to be a function on the natural numbers starting from $0$. We say that a sequence $f$ is represented in Python3 by a program $P$ iff $P$ halts and the final value of the variable f is a procedure that represents $f$.
Here are some Python3 expressions in order of increasing length (counting new-line as 1 symbol):
Program A0 (length 12; represents $(1,\cdots$)
f=lambda n:1

Program A1 (length 14; represents $(1,2,\cdots$)
f=lambda n:n+1

Program A2 (length 15; represents $(1,2,4,\cdots$)
f=lambda n:1<<n

Program A3 (length 22; represents $(1,2,4,\cdots$)
def f(n):
 return 1<<n

You can see that, for the sequence of powers of $2$, with just the first $1$ or $2$ elements Python3 complexity would favour the wrong sequence (Programs A0,A1). But with just $3$ elements it will favour the right sequence (Program A2). This is because Python3 was designed to be convenient for programmers, so of course you would expect it to favour powers of $2$...
For a more interesting example, consider the following Python3 expressions for initial segments of prime numbers:
Program B0 (length 12; represents $(2,\cdots$)
f=lambda n:2

Program B1 (length 14; represents $(2,3,\cdots$)
f=lambda n:n+2

Program B2 (length 19; represents $(2,3,5,\cdots$)
f=lambda n:n+2+n//2

Program B3 (length 22; represents $(2,3,5,7,\cdots$)
f=lambda n:(n<1)+1+2*n

Program B3 (length 28; represents $(2,3,5,7,11,\cdots$)
f=lambda n:[2,3,5,7,11][n%5]

Program B4 (length 29; represents $(2,3,5,7,11,13,\cdots$)
f=lambda n:(n<1)+1+2*(n+n//4)

Program B5 (length 34; represents $(2,3,5,7,11,13,17,19,23,\cdots$)
f=lambda n:(n<1)+1+2*(n+n//4+n//6)

Program B6 (length 41; represents $(2,3,5,7,11,13,17,19,23,29,31,\cdots$)
f=lambda n:(n<1)+1+2*(n+n//4+n//6+n//9*2)

Program B7 (length 49; represents $(2,3,5,7,11,13,17,19,23,29,31,37,\cdots$)
f=lambda n:(n<1)+1+2*(n+n//4+n//6+n//9*2+n//11*2)

Program B8 (length 55; represents $(2,3,5,7,11,13,17,19,23,29,31,37,41,43,\cdots$)
f=lambda n:(n<1)+1+2*(n+n//4+n//6+n//9*2+n//11*2-n//12)

Program B9 (length 59; represents primes up to $47$)
f=lambda n:[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47][n%15]

(I think such repetition is optimal for all initial segments in-between.)
Program B10 (length 101; represents primes up to $107$)
f=lambda n:[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107][n%28]

Program B11 (length 104; represents primes)
def f(n):
 p=2
 while n>0:
  n,d=n-1,2
  while d>1:
   p,d=p+1,p-1
   while d>1 and p%d>0:d-=1
 return p

If anyone can shorten any of these, let me know in the comments! But if what I have above is optimal, then one needs the first $29$ elements of the sequence of primes for Python3 complexity to favour the correct sequence! Even if what I have is not optimal, I am sure that one needs at least the first $15$ elements. That is much longer than one might expect!


text:
Q: array sorting using PHP Is there a way to use descriptors in PHP to do the following sort:
Array 1:

$array1 = ["blah", "quack", "yot"];

Array 2
$array2 = [1,9,6]; Essentially, I'm trying to describe blah with 1, quack with 9, and yot with 6. Basically, there are a total of 1 blahs, 9 quacks, and 6 yots. When I sort the arrays, I want to produce the following arrays:
Array 1 Sorted:
$array1 = ["quack","yot","blah"];

Array 2 Sorted:
$array2 = [9,6,1];

A: array_multisort($array2, SORT_DESC, $array1);

http://ideone.com/4Afyu
http://php.net/array_multisort

A: You can sort arrays with usort.

A: Well, you can restructure your data into an associative array.
$var = array ('blah'=>1, 'quack'=>9, 'yot'=>6);
So that your data is in one array. Then you can use asort or any php sorting function to manipulate the array.


text:
Q: Как изменить код страницы сайта работающего на next.js? Есть сайт который работает на nextjs, я хочу на главную страницу этого сайта добавить код гугл аналитики, но никак не могу найти где редактируется секция head...
Буду благодарен за помощь!
Вот так выглядит корневой каталог этого сайта:


text:
Q: How to use v-on:click to change multiple content - Vuejs and Liquid I would like to change text and image when I click on a button, I had tried this but I get stuck and I don't know how to use it to change multiple elements,
{% for variant in product.variants %}
{{ variant.title }} -
<input type="radio" {% if forloop.first %}checked{% endif %} class="variant_id" id="variant_{{- variant.id }}" name="productVariants" value="{{ variant.id }}"/>

{{ variant.price | money_with_currency }}

{{ variant.sku }}

{{ variant.image | img_url: master }}

{% endfor %}

{% raw %}{{ price }}{% endraw %}
{% raw %}{{ image }}{% endraw %}

Current look on the store
The price is now showing by default I have to click the radio button to show the price, I want it to be shown by default,
This is how it looks like after I click on the radio button
export default {
  data () {
    return {
       price: document.getElementsByClassName('variant_price').innerHTML,
       sku: document.getElementsByClassName('variant_sku').innerHTML,
       img: document.getElementsByClassName('variant_img').innerHTML,
    }
  },
  methods:  {
    changeMessage(message) {
      this.message = message
    }
  },
}

I want when I click on the radio button it gives me the price and image, my skills on JS is so bad, please I need help

A: In order to change another element using v-on:click on a button you should add to these elements a parameter ref="nameOfRef" and then select them in the method you called on the v-on:click like: this.$refs.nameOfRef
Example:

Hello world

      <button type="button" v-on:click="hideElements()">Hide!</button>
      <button type="button" v-on:click="showElements()">Show!</button>

A: Try to use mounted() hook to set your defaults.
export default {
  data () {
    return {
       price: document.getElementsByClassName('variant_price').innerHTML,
       sku: document.getElementsByClassName('variant_sku').innerHTML,
       img: document.getElementsByClassName('variant_img').innerHTML,
    }
  },
  mounted(){
    //set default here, like this
    this.changeMessage(message);
  }
  methods:  {
    changeMessage(message) {
      this.message = message
    }
  },
}

Also, could you elaborate it a little bit more so that I can help you in this regard


text:
Q: A lot has changed ___ Larry came back from his summer vacation A lot has changed ___ Larry came back from his summer vacation.

a. since
b. after
c. when
d. then

May I ask what is the most suitable answer for this question? This is because intially I chose a. since but the answer is wrong. Anyone can help me in understanding the question? Why since is not suitable in this question? Thank you in advance.


text:
Q: Webcam nightmare on LINUX I have a computer relatively new with Fedora 10. I have bought a webcam, plugged it in, run cheese and the webcam works perfectly. So, it is supported by the kernel.
Than, the hard part...
I have tried to use X-LITE, Skype and now QNext and the camera does not works on these apps. All I see is a black or scrambled colored noise pattern.
Qnext gave me this errro message
Device 'v4l:5' detection failed: java.lang.Error: Can't open video card 5
      Video device 'v4l:6' detection failed: java.lang.Error: Can't open video card 6
      Video device 'v4l:7' detection failed: java.lang.Error: Can't open video card 7
      Video device 'v4l:8' detection failed: java.lang.Error: Can't open video card 8
      Video device 'v4l:9' detection failed: java.lang.Error: Can't open video card 9
Finished detecting Video capture - 0 devices found

The camera shows perfectly as /dev/video0
when I plug it in.
So, if the kernel supports it, what is the matter with linux? WTF!
I have tested on UBUNTU, on another box, and I have the same problem.
Any suggestions?
thanks for your time.

A: It may be that the other programs you are running do not support cameras that only support V4L2 by default (e.g. the application does not support V4L2)
Try the following:
Run your application from the command-line, but prefix your command with the following:
LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so

This should allow compatibility with applications that use V4L1.
Also, please make sure that no other application is using the camera. Using 1 camera in more than 1 application is usually not supported.

A: You may need to adjust your kernel module for various bits of improper behaviour by some camera models. try:
rmmod uvcvideo

modprobe uvcvideo quirks=2

There are other quirks values ... 2 happens to work for me for a no-name camera.

A: In my limited experience, the application you are most likely to have success with is Ekiga.  It's a standard part of Ubuntu.
That said, Webcam support in Linux is pretty rough.  Sorry.


text:
Q: i am trying to fetch the json post data from android app to php web service but it can't fetch. the code show below which i used I have created this code to fetch the data from android app. after fetching the json data i am decode them and then i fetch the key variable that is base 64 code of image and ori_name variable which is image name. after that i am creating image file at server side from base 64 code and store the file in server. if image is store in server then iam storing the image name and image path in one database. when i am executing this code with android app it only return nil at android side. is here any solution for fetching data? and note the android app is developed by my friend who use my created this service. he getting the nil value when he use it. please help me to solve this issue.
<?php
//process client request(via URL)
header("content-Type:application/json");
$data=$_REQUEST['jdata'];//request json data
$imgdata=json_decode($data);//decode json data
$basecode=$imgdata->{'key'};//fetch base64 code of image
$imgname=$imgdata->{'ori_name'};//fetch image name
$response=get_url($basecode,$imgname);//cal function for store image at server
return deliver_response($response);
function deliver_response($status)
{
header("HTTP/1.1");
$response['status']=$status;
$json_response=json_encode($response);
return $json_response;//return json response to android app
}
function get_url($basecode,$imgnm)
{
$decoded= base64_decode($basecode);//convert base 64 code to string format

$location=$_SERVER['HTTP_HOST']."/Clients/krishinternational/MobileService/images/".$imgnm;
$output_file="../images/".$imgnm;//define output file location
$ifp = fopen($output_file, "wb"); //create file
    $rs=fwrite($ifp, $decoded); //write image in file
    if($rs!=False)//check weather file is written or not
    {
        fclose($ifp);
        $conn =mysqli_connect('host','user','password','db_name');//creating database connection
        if ($conn->connect_error)
        {
        die("Connection failed: " . $conn->connect_error);
        }

        $query="insert into tblimage values('".$imgnm."','".$location."')";//query to store image path in database
        if ($conn->query($query) === TRUE)
        {
        //echo "New record created successfully";
        mysqli_close($conn);
        return True;//if successfully inserted then return true
        }
        else
        {
        return False;//if not succeed then return false
        }
      }
        else
       {
        return False;
       }
    }
    ?>

A: Thanks Indra I got the result testing by Rest Client. the error was i am requesting the json data from android app but the actually i have to use file_get_contents.
$input=file_get_contents("php://input");

thanks indra


text:
Q: Extra points appearing at Frame while using Mesh with ListLinePlot Consider this ListLinePlot
ListLinePlot[Exp[#] & /@ Range[0, 1, 0.05], PlotRange -> {1, 2},
             Frame -> True, Mesh -> Full]

How to get rid of this extra on the upper frame?
(Is it a bug!)
One walk around is using a suitable PlotRangePadding along y axis, but I want to avoid that (because I have a lot of sets with different range and I don't want to specify different padding for each of them manually)
This does not appear if I use PlotMarkers instead of Mesh.
ListLinePlot[Exp[#] & /@ Range[0, 1, 0.05], PlotRange -> {1, 2},
              Frame -> True, PlotMarkers -> {Automatic, 10}]

Is it possible to get the same output with Mesh?

A: A workaround:
ListLinePlot[Exp[#] & /@ Range[0, 1, 0.05],
  PlotRange -> {1, 2},
  Frame -> True,
  Mesh -> All] /. Point[{a__, _, b_}] :> Point[{a, b}]

Use Mesh -> All and delete the next to last point


text:
Q: How to use a stream between a flutter app and a flask api to check for user states? I'm developing a Flutter app in which I want to query user states from the Flask REST API. For example, whether the user is verified and logged in. These states determine which screen will be loaded.
In Flutter. I want to use the StreamBuilder something like this:
@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: StreamBuilder<CurrentUser?>(
            stream: //TODO: stream method,
            builder: (content, snapshot) {
              if(snapshot.connectionState == ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
              }
              if(snapshot.hasError) {
                print(snapshot.error)
              }
              if (snapshot.hasData) {
                //TODO: page router
              } else {
                return const LoginPage();
              }
            }));

note: The StreamBuilder should update or get a CurrentUser object via flask when the state changes.
If the state does not change, it will continue to listen. If the user is not logged in, the object will be null.
In flask I want to create a route for the stream. When a state changes, the change of the user object will be sent using this route.
@app.route('/stream')
def stream():
    ...
    return changed_user_state

If necessary, other methods should also be able to respond via this stream, if a state changes.
@app.route('/other-route')
    def change_state():
        return changed_user_state via the stream

My concern is very theoretical and I don't know if it can be implemented in this way. If not, I would be grateful for any better idea.  If it can be implemented in this way, I would be very grateful for a few code snippets. I don't know where to start. Thanks in advance.


text:
Q: Code Ingiter POST data empty I'm just have a trouble when POST a multipart form with codeigniter. The form is contain text field and 8 field of file upload. the problem is, the file is uploaded successfully with no error, but the field of text is empty in my controller.
I tried to print_r the POST data and get an empty array. But sometimes when I'm using google chrome, It's not got any problem.
Any solution?

A: <form name="form" action="some action page.php"  method="post" enctype="multipart/form-data">

 <input type="text" name="inputfieldvalue"  value="Input Field">
<input type="file" name="uploadedfile" id="uploadedfile">
<input type="submit" value="Submit" >
</form>

// suppose your form is like this as above then to check textfield value
<?php echo $_POST['inputfieldvalue']; ?>

// pass the name attribute whatever you have given to $_POST[your name field value]. like this

A: Complete example should be working.
your form target action to function my_form in My_controller controller. Lest try input with name WTF
<form name="form" action="my_controller/my_form"  method="post" enctype="multipart/form-data">

 <input type="text" name="WTF"  value="Input Field">
<input type="submit" value="Submit" >
</form>

your cotroller action in My_controller.php file (CI Controller folder) should look le this
<?php
 defined('BASEPATH') OR exit('No direct script access allowed');

class My_controller extends CI_Controller {

  function __construct() {
    parent::__construct();
  }

  public function index(){

    /* do something for page my_controller if you want */

  } // end of index

  function my_form() { // = my_controller/my_form
   $here_is_it = $this->input->post('WTF'); // call value of input with name WTF

   /* test it */
   print_r($here_is_it);
  }

Extra, to make sure everything it's okay. You can Enable auto load feature in Codeigniter. follow this tutorial

A: I Just check it for a while and the problem is not in the php or my html form code. But the problem is in my php.ini config. By increase upload max file size fix the problem. I just confused before because the form sometime work well and sometimes give an empty value.
Thanks in advance


text:
Q: How to prove the relationship between Stern's diatomic series and Lucas sequence $U_n(x,1)$ over the field GF(2)? I found the bit count of Lucas sequence $U_n(x,1)$ over the field GF(2) is Stern's diatomic series, I want to know the reason?
https://oeis.org/A002487 : Stern's diatomic series
https://oeis.org/A168081 : Lucas sequence $U_n(x,1)$ over the field GF(2)

A: I always work mod 2. Let $f(n)$ be the bit count (number of nonzero
coefficients) of $U_n(x,1)$.  $U_n(x,1)$ satisfies
  $$ U_{2n}(x,1) = xU_n(x,1)^2 $$
$$ U_{2n+1}(x,1) = (U_n(x,1)+U_{n+1}(x,1))^2. $$
From the first equation $f(2n)=f(n)$, and only odd powers of $x$
can have nonzero coefficients. From the second equation, only even
powers of $U_{2n+1}$ can have nonzero coefficients. Hence no
cancellation occurs when we add $U_n(x,1)$ and $U_{n+1}(x,1)$, so
$f(2n+1)=f(n)+f(2n+1)$. Thus $f(n)$ satisfies the same recurrence and
same initial conditions $f(0)=0$ and $f(1)=1$ as Stern's diatomic sequence.
Addendum. The two formulas above can be proved by induction on
$n$. Namely, writing just $U_n$ for $U_n(x,1)$,
  $$ U_{2n}=xU_{2n-1}+U_{2n-2} = x(U_{n-1}+U_n)^2+xU_{n-1}^2
      =xU_n^2 $$
and
  $$ U_{2n+1} = xU_{2n}+U_{2n-1} = x^2U_n^2+(U_{n-1}+U_n)^2
           =U_n^2+(xU_n+U_{n-1})^2=U_n^2+U_{n+1}^2. $$


text:
Q: Partial collection counter alias Rails can render partial collection with counter:
= render partial: 'item', collection: @items

inside _item.html, rails provides iteration counter for the items. (here)
= item_counter

How to make an alias for item_counter e.g. partial_counter? Or anything that will make it become more DRY? It's quite ineffisient writing item_counter, product_counter, category_counter, user_counter, .... thx

A: = render partial: 'item', collection: @items, as: 'item'

UPDATED: Alias counter only:
Unfortunately there is no any other Rails' ways to do what you looking for. You have to define new local variable and assign counter value in all partials by hands:
<% counter = local_assigns.detect {|var, value| var.match(/_counter\z/)}.last %>

<%= counter %>


text:
Q: Python 2: Conditional statement behaviour of lists with greater/smaller Can someone explain to me what is happening here?
>>> [] > 0
True
>>> [] > 0.1
True
>>> [] < 0
False
>>> [] < 0.1
False
>>> [] > 'string'
False
>>> [] < 'string'
True

Why and how does this work?

A: So you are using Python2, where you can compare between list and strings and numbers. This helps to sort them out.
Python2
   [0]>1
=> True

However since Python3 this has been removed.
Python3
   [0]>1
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unorderable types: list() > int()

Hope that explains, why list has been made to be greater than number is purely subjective and depends on the creators.


text:
Q: Apply control charactes to file reddirect Tried various existing answers, but didn't find any which entirely works. This is one line example, and show how it fails, maybe some extra switch or step can solve this?
This is the content of file I am trying to save to txt file with control characters applied before making to disk: fooo^H^H^H^Hbarr^H^H^H^H    ^H^H^H^Hok
Best tool found til now is col -b but here is example where is fails.
I have tried:cat mem.txt | col -b > mem2.txt but result is okrr I don't know why it ignores those 4 spaces which should clean barr but it does.
Source problem is that I am trying to redirect clean log from /usr/bin/time -f'%E' sudo memtester 2M 1 to file on disk but I am unable to clean it from junk from progress prints. This is only one program giving me this problems, I have several more so if this one has some mode not to print progress it will probably not solve my headaches.
EDIT This sed works for memtester case, but not in general, so for now best solution is:
| sed -re ':b; s,[^\x08]\x08,,g; tb' | col -b >


text:
Q: OpenGL ES 2.0 Load scene (shaders and textures) asynchronously I write Android game that using OpenGL ES 2.0.  For example, a some game scene is drawing. How I can load another scene in background and when it loaded switch them. In background scene needs to load texture, generate their IDs and compile GL programs (shaders). But if I just create new Thread game crushes because game entities haven't access to GL context. And if I try to make it in GLSurfaceView.queueEvent get same error.
How I can do it? I found nothing by this theme.
P.S. Sorry for my English.

A: My advice is to keep the texture generation on the main thread.
Just do the image loading on a different thread.
Once the images are all loaded, notify the main thread, so that the main thread can do the actual creation of GL resources.
The file IO is probably slower than the actual gl texture creation anyway.
Also, for loading scenes, it pays to do the collision mesh generation on a helper thread, as that can be quite costly as well for large triangle meshes.


text:
Q: how to collapse a row of a table using ng-repeat and angular I've got a table built in html using angular 1.5 framework I want to toggle the row expansion when the glyphicon (plus sign is clicked/toggled)
Here is what I have from the html structure

                    Activity
                    Complete
                    Status
                    Starts
                    Ends

                {{pp.activityName}}

                    <uib-progressbar animate="false" value="dynamic" type="success">{{pp.percentComplete}}%</uib-progressbar>

                ActiveInactive
                {{pp.startDate | date: 'MM/dd/yyyy'}}
                {{pp.endDate | date: 'MM/dd/yyyy'}}

Name:

Deadline:

Extra Info:

Comments:

                            View Alerts

Is there a way to collapse and expand (hide/show) the
 section id'd as extraInfo without using JQuery?
I'd appreciate any suggestions on what to try.
-cheers

A: Yes. It's easy to do in angularjs. Create any variable as an obj/array. Use the $index of ng-repeat to track iterating object's toggle information. You won't even have to write single code in js.
See the html of this DEMO. In this DEMO, toggle is the array that keeps information.

A: Just to expand on Saad's answer I wanted to post the code here in case the plunker ever died etc. Basically what Saad suggests is to use $index of each ng-repeat item which based upon the documentation each repeat has a scope unto itself and independent of the entire collection. So what happens here, on the initialization of the repeat is we use ng-init and create a scoped object of toggle[$index] for each item on the repeater. We then toggle on each click (true or false ) to render the suppressed section.
Here is an example of the html markup

                        {{pp.activityName}}

                            <uib-progressbar   value="pp.percentComplete" type="success" title="Your activity progress" >
                                    {{pp.percentComplete}}%
                            </uib-progressbar>

                        ActiveInactive
                        {{pp.startDate | date: 'MM/dd/yyyy'}}
                        {{pp.endDate | date: 'MM/dd/yyyy'}}

                                    Name: {{pp.summary.name}}

                                    Deadline: {{pp.summary.deadline | date: MM/dd/yyyy}}

                                    Extra Info: {{pp.summary.extraInfo}}

                                    Comments: {{pp.summary.comments}}

                                    View Alerts

and as Saad stated no work is needed in the controller as the html markup and angular handle it for you in the DOM.
Hope this helps.

A: You can create a simple controller for your glyph button and and add a visible/hide class with ngclass.
With the css class you can change the display/opacity/height if your element.


text:
Q: Determine the convergence of $\sum_{n=2}^{\infty} \sin \left(n \pi+\frac{1}{\ln n}\right)$. I have to assess the convergence of
$$
\displaystyle
\sum_{n=2}^{\infty} \sin \left(n \pi+\frac{1}{\ln n}\right)
$$
I thought that it converges, because
$$
\displaystyle
\begin{eqnarray}
\sin (n \pi+\frac{1}{\ln n}) & = & \sin (n \pi) \cos \left(\frac{1}{\ln n}\right)+\cos (n \pi) \sin \left(\frac{1}{\ln n}\right)\\ & = & (-1)^n \sin \frac{1}{\ln n}
\end{eqnarray}
$$
And since $\sum_{n=2}^{\infty}(-1)^n\sin \frac{1}{\ln n}$ converges, so $\sum_{n=2}^{\infty} \sin \left(n \pi+\frac{1}{\ln n}\right)$ converges, too.
But I'm not sure $\sum_{n=2}^{\infty}(-1)^n\sin \frac{1}{\ln n}$ is conditional convergent or absolute convergent.
Is this approach right?

A: $\sum(-1)^{n}\sin(\frac{1}{\ln(n)})$ converges by Leibniz Test .
But $\sum\sin(\frac{1}{\ln(n)})$ is divergent by comparing with $\frac{1}{\ln(n)}$.
That is $$\lim_{n\to\infty}\frac{\sin(\frac{1}{\ln(n)})}{\frac{1}{\ln(n)}}=1$$ .
And $\sum\frac{1}{\ln(n)}$ diverges by Cauchy Condensation test.(Or just by simple comparison with $\frac{1}{n}$ as mentioned in the comments.)


text:
Q: Best Practices for Performing Sequential Operations What is the best way to perform a couple of tasks together and if one task fails then the next tasks should not be completed? I know if it were the database operations then I should have used Transactions but I am talking about different types of operations like the following:
All tasks must pass:
SendEmail
ArchiveReportsInDatabase
CreateAFile
In the above scenario all the tasks must pass or else the whole batch operation must be rollback.

A: Rollbacks are tough - AFAIK, there's really only 2 ways to go about it. Either a 2 phase commit protocol, or compensating transactions. You really have to find a way to structure your tasks in one of these fashions.
Usually, the better idea is to take advantage of other folks' hard work and use technologies that already have 2PC or compensation built in. That's one reason that RDBMS are so popular.
So, the specifics are task dependent...but the pattern is fairly easy:
class Compensator {
   Action Action { get; set; }
   Action Compensate { get; set; }
}

Queue<Compensator> actions = new Queue<Compensator>(new Compensator[] {
   new Compensator(SendEmail, UndoSendEmail),
   new Compensator(ArchiveReportsInDatabase, UndoArchiveReportsInDatabase),
   new Compensator(CreateAFile, UndoCreateAFile)
});

Queue<Compensator> doneActions = new Queue<Compensator>();
while (var c = actions.Dequeue() != null) {
   try {
      c.Action();
      doneActions.Add(c);
   } catch {
      try {
        doneActions.Each(d => d.Compensate());
      } catch (EXception ex) {
        throw new OhCrapException("Couldn't rollback", doneActions, ex);
      }
      throw;
   }
}

Of course, for your specific tasks - you may be in luck.

*

*Obviously, the RDBMS work can already be wrapped in a transaction.

*If you're on Vista or Server 2008, then you get Transactional NTFS to cover your CreateFile scenario.

*Email is a bit trickier - I don't know of any 2PC or Compensators around it (I'd only be slightly surprised if someone pointed out that Exchange has one, though) so I'd probably use MSMQ to write a notification and let a subscriber pick it up and eventually email it. At that point, your transaction really covers just sending the message to the queue, but that's probably good enough.

All of these can participate in a System.Transactions Transaction, so you should be in pretty good shape.

A: in C#
return SendEmail() && ArchiveResportsInDatabase() && CreateAFile();

A: Another idea:
try {
    task1();
    task2();
    task3();
    ...
    taskN();
}
catch (TaskFailureException e) {
    dealWith(e);
}

A: A couple of suggestions:
In a distributed scenario, some sort of two-phase commit protocol may be needed.  Essentially, you send all participants a message saying "Prepare to do X".  Each participant must then send a response saying "OK, I guarantee I can do X" or "No, can't do it."  If all participants guarantee they can complete, then send the message telling them to do it.  The "guarantees" can be as strict as needed.
Another approach is to provide some sort of undo mechanism for each operation, then have logic like this:
try:
    SendEmail()
    try:
        ArchiveReportsInDatabase()
        try:
             CreateAFile()
        except:
            UndoArchiveReportsInDatabase()
            raise
    except:
        UndoSendEmail()
        raise
except:
    // handle failure

(You wouldn't want your code to look like that; this is just an illustration of how the logic should flow.)

A: If your language allows it, this is very tidy:

*

*Put your tasks in an array of code blocks or function pointers.

*Iterate over the array.

*Break if any block returns failure.

A: You didn't mention what programming language/environment you're using.  If it's the .NET Framework, you might want to take a look at this article.  It describes the Concurrency and Control Runtime from Microsoft's Robotics Studio, which allows you to apply all sorts of rules on a set of (asynchronous) events:  for example, you can wait for any number of them to complete, cancel if one event fails, etc.  It can run things in multiple threads as well, so you get a very powerful method of doing stuff.

A: You don't specify your environment.  In Unix shell scripting, the && operator does just this.
SendEmail () {
  # ...
}
ArchiveReportsInDatabase () {
  # ...
}
CreateAFile () {
  # ...
}

SendEmail && ArchiveReportsInDatabase && CreateAFile

A: If you're using a language which uses sort-circuit evaluation (Java and C# do), you can simply do:
return SendEmail() && ArchiveResportsInDatabase() && CreateAFile();

This will return true if all the functions return true, and stop as soon as the first one return false.

A: Exceptions are generally good for this sort of thing. Pseudo-Java/JavaScript/C++ code:
try {
    if (!SendEmail()) {
        throw "Could not send e-mail";
    }

    if (!ArchiveReportsInDatabase()) {
        throw "Could not archive reports in database";
    }

    if (!CreateAFile()) {
        throw "Could not create file";
    }

    ...

} catch (Exception) {
    LogError(Exception);
    ...
}

Better still if your methods throw exceptions themselves:
try {
    SendEmail();
    ArchiveReportsInDatabase();
    CreateAFile();
    ...

} catch (Exception) {
    LogError(Exception);
    ...
}

A very nice outcome of this style is that your code doesn't get increasingly indented as you move down the task chain; all your method calls remain at the same indentation level. Too much indentation makes the code harder to read.
Moreover, you have a single point in the code for error handling, logging, rollback etc.

A: To really do it right you should use an asyncronous messaging pattern. I just finished a project where I did this using nServiceBus and MSMQ.
Basically, each step happens by sending a message to a queue. When nServiceBus finds messages waiting in the queue it calls your Handle method corresponding to that message type. This way each individual step is independently failable and retryable. If one step fails the message ends up in an error queue so you can easily retry it later.
These pure-code solutions being suggested aren't as robust since if a step fails you would have no way to retry only that one step in the future and you'd have to implement rollback code which isn't even possible in some cases.


text:
Q: How to line-break cites correctly (hanging-over problem)? while using Bibtex, I experienced an frustrating issue with line-breaks on cites in my block text.
I have chosen to use the following bibtex implementation:
\bibliographystyle{plain}
\bibliography{library}

No voodoo here.
Nevertheless, this leads to the following composition:

The cite is not line-broken correctly. I assume many other users have already experienced that hanging-over problem either.
Can someone help me how to fix that LaTeX is compiling the cite correctly in a way that it nicely integrates itself into block structure?
EDIT:
Rephrasing makes it hard to monitor the whole 300 pages every time I recompile the document due to some minor modifications. I know that many use suggest to rephrase the text but I would like to ask for a more professional solution here.


text:
Q: NSLog() to both console and file I would like to redirect NSog() to file, but still to see the output in console.
I am aware that stderr can be redirected to file using:
freopen("file.log", "a+", stderr);

but after redirecting it to file, the log is no more shown in the console output.
I could build a custom wrapper around NSLog() but I would not get logged crash logs that are written to stderr in the moment of app crash.
I was also experimenting with dup() and other methods for duplicating file descriptors, but the output was ether in file or in console, never in both.
Similar questions was asked here:
Write stderr on iPhone to both file and console
but without accepted answer, or with suggestion to use a NSLog() wrapper.
Has anyone an idea on how to manage this work?
Thanx in advance.
UPDATE: The most important part of redirecting is to have system error logs (stderr) written to both console and file.

A: According to the docs, you will need a custom log facility.
You need at a minimum, a function that takes variadic arguments and printd to NSLog and fprintf, something like:
void myLog(NSString* format, ...)
{
    va_list argList;
    va_start(argList, format);
    NSString* formattedMessage = [[NSString alloc] initWithFormat: format arguments: argList];
    va_end(argList);
    NSLog(@"%@", formattedMessage);
    fprintf(myFileDescriptor, "%s\n", [formattedMessage UTF8String]);
    [formattedMessage release]; // if not on ARC
}

Or there are Cocoa logging frameworks.
Looking for a Specific Cocoa Logging Framework

A: The way we have implemented is:
if (!isatty(STDERR_FILENO)) {
    // Redirection code
}

This is based on general assumption that if a console is attached, you do not need to store those logs in the file since you are already debugging. So whenever the console is attached, logs will be printed there, otherwise saved to a file.


text:
Q: Does New Relic supports openJDK12? has been compiled by a more recent version of the Java Runtime (class file version 56.0), this version of the Java Runtime only recognizes class file versions up to 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$100(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:93)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
PS <path>

Does new relic has different version of jar for openJDK 12 ?
I am running with new relic 5.10.0 version

A: The Java agent for New Relic supports OpenJDK and AdoptOpenJDK JVM versions 7 to 15 for Linux, Windows, and OS X:

*

*Requirements to install the agent
What happens when you restart the application? Does the error prevent startup or does it recover and continue and begin reporting?


text:
Q: Flex-direction column not working as expected I have the following markup:

CSS (desktop):
.container {
  display: flex;
}

On a desktop view they're displayed in a row, like that:

But on mobile view, i want them to re-reorder:

I've tried the following styles:
// here's media query for mobile devices
.container {
  flex-direction: column;
  flex-wrap: wrap;
  align-items: stretch // so my items would be filling width
}

.logo {
  order: 1;
  flex: 1 0 50%;
}

.search {
  order: 2;
  flex: 0 1 100%;
}

.button {
  order: 1;
  flex: 1 0 50%;
}

But my results are:

Is this even possible with a flexbox?

A: You should look into "flex-grow" which allows flex items to grow if necessary in order to take up as much space as is available in its container. If all flex-items (in your case: .logo, .search, .button) have a flex-grow value of 1, the remaining space in .container will be distributed to its children equally.
Also, you should use
    flex-direction: row;

in your case if you want them to stretch horizontally
Check out this fiddle for reference! https://jsfiddle.net/hgs5w19y/2/

A: You need to use flex-grow (great resource for understanding flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/)
HTML

Logo

Search

Button

CSS
.container {
  background-color: #ccc;
  display: flex;
  width: 300px;
  flex-wrap: wrap;
  text-align: center;
}

.container > div {
  background-color: grey;
  margin: 10px 20px;
  padding: 10px 20px;
}

.logo {
  order: 1;
  flex-grow: 1;
}

.search {
  order: 2;
  flex-grow: 2;
}

.button {
  order: 1;
  flex-grow: 1;
}

A: No need of direction nor so many rules, just set a breakpoint and reset .search behavior

.container {
  display: flex;
  flex-wrap: wrap;
}

.container>div {
  flex: 1;
}

div.search {
  order: 1;
  flex-basis: 100%;
}

@media screen and (min-width:731px) {
  div.search {
    order: 0;
    flex: 1
  }
}

/* demo purpose */

.container {
  background: gray;
}

.container>div {
  padding: 1em;
  margin: 1em;
  background: lightgray;
}

.container>div:before {
  content: attr(class);
  color: black;
}

breakpoint value is to be updated to yours (here set at 731 for the demo) , to see behavior, run the snippet in full page, or play with the demo https://codepen.io/gc-nomade/pen/mYXZdY


text:
Q: Check whether element's parent has a li tag with php Basically, I want to check whether the parent of a link is an <li> element.
I'm using the Simple DOM Parser library. I get the links like this ($brokenlink is a URL):
$html = file_get_html($file);
$matches = $html->find("a[href=$brokenlink]");

I then loop through $matches
foreach ($matches as $value) {

}

My logic would go:
If the parent of $value is not 'li',
Do:
Thanks

A: It would be trivial to run through a NodeList of anchors using DOMXPath and DOMDocument:
// Create a new DOMDocument, load up our HTML
$doc = new DOMDocument();
$doc->loadHTML($html);

// Create a new DOMXPath object, and get our links
$xpath = new DOMXPath($doc);
$links = $xpath->query("//a[not(parent::li)][@href='$brokenURL']");

// Cycle over each anchor, check parentNode's nodeName
foreach ($links as $link) {
    echo "'{$link->nodeValue}' is not the child of a list item.";
}

Demo: http://codepad.org/UCtR49p4

A: Since you are using simple_html_dom, you can use $value->parent() to get the parent node, and tag to get the tag name:
$html = file_get_html($file);
$matches = $html->find("a[href=$brokenlink]");
foreach ($matches as $value) {
    $parent = $value->parent();
    if($parent->tag != 'li') {
        //not a child of li, do something...
    }
}

You can get more by reading the manual, which has everything you need.

A: According to the simplehtml manual, the parent of an element is available as $e->parent(). So you could do this:
$html = file_get_html($file);
$anchors = $html->find("a[href=$brokenlink]");

for ($anchors as $a) {
    if ($a->parent()->tag !== 'li') {
        // do something
    }
}


text:
Q: What can you do with integers in GLSL ES? There seems to be an extremely limited amount of things you can do with integers in GLSL ES 2.0.
For example:

*

*No bitwise operations are supported.

*No intrinsic functions seems to accept int types

So, it seems the only thing you can really do with integers is:

*

*Assign integer to integer

*Access array element by index

*Basic arithmetic (-, +, *, /), but only between other integers. No operator exists which allows you to add a float and int together.

*Compare them between each other.

*Convert them to other types

*vec constructors allow you to pass integers

Is that really it? Are there any intrinsic functions that take int parameters other than vec constructors? Are there any operations you can do between float and int?

A: You are correct, use cases of integers are limited. Per OpenGL ES Shading Language spec, 4.1.3:

Integers are mainly supported as a programming aid. At the hardware level, real integers would aid efficient implementation of loops and array indices, and referencing texture units. However, there is no requirement that integers in the language map to an integer type in hardware. It is not expected that underlying hardware has full support for a wide range of integer operations. An OpenGL ES Shading Language implementation may convert integers to floats to operate on them. Hence, there is no portable wrapping behavior.

Since there's no guarantee GLSL ES integer type maps to a hardware integer type, it's only useful for compile-time type checking with little to no effect at runtime. All places that require integers are listed in the spec.


text:
Q: How to emit event to app root in react native I'm trying to implement toast message (notification) on my React Native app.
I'm Thinking about implement my Toast component inside app root, and when a button is clicked (somewhere in the app), the app root will know about it and make the toast visible.
I don't want to use a library because I have complicated UI for this and I want to include buttons inside the toast.
This is the root component - App.js:
import { Provider } from 'react-redux';

import {Toast} from './src/components/Toast';
import store from './src/store/Store.js';
import AppNavigator from './src/navigation/AppNavigator';
import StatusBar from './src/components/StatusBar';

export default function App(props) {
    return (
        <Provider store = { store }>
          <View style={styles.container}>
            <StatusBar barStyle="default"/>
            <AppNavigator />
            <Toast></Toast>
          </View>
        </Provider>
    );
}

EDIT:
AppNavigator.js:
// this is how I connect each page:
let HomePage = connect(state => mapStateToProps, dispatch => mapDispatchToProps(dispatch))(HomeScreen);
let SearchPage = connect(state => mapStateToProps, dispatch => mapDispatchToProps(dispatch))(SearchScreen);

const HomeStack = createStackNavigator(
    {
        Home: HomePage,
        Search: SearchPage,
    },
    config
);

const mapStateToProps = (state) => {
    return {
        // State
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        // Actions
    }
};

export default tabNavigator;

Any ideas how can I do it? Thanks.

A: For this, i would suggest to use a component to wrap your application where you have your toast. For example:
App.js
render(){
    return (
      <Provider store = { store }>
          <View style={styles.container}>
              <AppContainer/>
          </View>
    </Provider>
    )
}

Where your AppContainer would have a render method similar to this:
render(){
    return (
        <Frament>
            <StatusBar barStyle="default"/>
            <AppNavigator />
            <Toast></Toast>
        </Fragment>
        )
}

Then (as you are using redux) you can connect your AppContainer. After that, just make this component aware of changes on redux using componentDidUpdate
componentDidUpdate = (prevProps) => {
    if(this.props.redux_toast.visible !== prevProps.redux_toast.visible){
        this.setState({
            toastVisible : this.props.redux_toast.visible,
            toastMessage: this.props.redux_toast.message
        })
    }
}

This is just an example on how it could be done by using redux, I don't know how your toast or redux structure is, but it should be an available solution for your use case.
EDIT.
This is how it should look like:
//CORE
import React from 'react';

//REDUX
import { Provider } from 'react-redux';
import store from './redux/store/store';
import AppContainer from './AppContainer';

export default () => {
  return (
    <Provider store={store}>
        <AppContainer />
    </Provider>
  )
}

AppContainer.js:
import React, { Component } from "react";
import { View, Stylesheet } from "react-native";
import StatusBar from "path/to/StatusBar";
import AppNavigator from "path/to/AppNavigator";
import Toast from "path/to/Toast";
import { connect } from "react-redux";

class AppContainer extends Component {
    constructor(props){
        super(props);
        this.state={
            toastVisible:false,
            toastMessage:""
        }
    }
    componentDidUpdate = (prevProps) => {
        if(this.props.redux_toast.visible !== prevProps.redux_toast.visible){
            this.setState({
                toastVisible : this.props.redux_toast.visible,
                toastMessage: this.props.redux_toast.message
            })
        }
    }

    render(){
        return (
            <View style={styles.container}>
                <StatusBar barStyle="default"/>
                <AppNavigator />
                <Toast visible={this.state.toastVisible}
                    message={this.state.toastMessage}
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1
    }
})

const mapStateToProps = state => ({ ...yourMapStateToProp })

const mapDispatchToProps = state => ({ ...mapDispatchToProps })

export default connect(mapStateToProps, mapDispatchToProps)(AppContainer)

Rest of the code remains untouched, you need to dispatch an action that changes a props that your appContainer's componentDidUpdate is listening to (in the example i called it redux_toast.visible).


text:
Q: How to take fields value from another table? I have a table field in which I want to calculate the price of an order. In that table I have a field where you choose what dishes did the client order. And I need to get the prices of those exact dishes from another table and then sum them up. I want to calculate in field SASK and take prices from table VALGIARASTIS. So what should the formula be?
For example in field dish I choose Balandeliai,Bulviniai blynai, Cepelinai formula should take those names and get prices of it from table VALGIARASTIS and sum them up.
Here's a screenshot for you to understand.

A: The solution will not be a formula.  It will be a VBA function that receive an array from the multi-value combo box, uses it to build a filter for the data in the VALGIARASTIS table, and uses an aggregate query to SUM() the price values.
For the first part, you can refer to these links:

*

*http://allenbrowne.com/ser-50.html

*http://support.microsoft.com/kb/135546
Once you have the means to filter a recordset, you can run an SQL query on the results using the SUM() function to get your total.  You can run a DAO cursor through the recordset and get your total that way, but SQL is better.


text:
Q: Positioning Graphics draw I'm trying to draw some polygons and lines usinng e.Graphics.DrawPolygon (or DrawLine). But I have a little problem specifying the coordinates where to draw. I am drawing onto a PictureBox using its Paint event. The elements draw correctly relatively to each other (creating the required final picture), but seem always to draw in the upper-left corner of the PictureBox. When creating the points to draw, when I just try to multiply the coordinates, it draws it at the same place but bigger (size is multiplied, instead of location coordinates).
Here is my code:
//some for loop
{
//getting the coordinates
Point toAdd = new Point((int)xCoord, (int)yCoord); // creating the point from originaly a double, here i tried to multiply..
tmpPoints.Add(toAdd); // tmpPoints is a List<Point>
}
points.Add(tmpPoints.ToArray()); //List<Point[]>

drawBuffer = points; //saving to a public List<Point[]>
points.Clear();
this.Invalidate();

here part of the pictureBox1_Paint method:
for (int i = 0; i < drawBuffer.Count; i++)
        {
                //some other stuff like deciding which color to use, not very important
                Brush br = new SolidBrush(polyColor);
                e.Graphics.FillPolygon(br, drawBuffer[i]);
                brush.Dispose();
        }

I have checked using breakpoint, the coordiinates are the same ratio (what was 100 pixels wide is still 100 pixels wide), they are at coordinates like x 3000 and y 1500, but it just draws itself in the upper-left corner. When i multiply the coordinates 3 times (see the code for the place where i multiplied), it draws at the same place but 3 times bigger (doesn't make sense after checking the coords...)
So, my question is - how do I set the location correctly, or is there any other way to do this?
Like this (I know, this is nonsense, just an example)
foreach(Polygon poly in e.Graphics)
{
poly.Location = new Point(poly.Location.X * 2, poly.Location.Y * 2);
}

A: When you multiply the coordinates of the points, they're scaled around the point (0, 0), the top-left corner of the canvas:

In order to scale it around its center (and I suppose you expected it to work this way), you need to calculate some kind of center of the polygon. For simplicity, it can be even an arithmetic mean of the coordinates, on X and Y axes respectively. If you already have the coordinates of the center, translate the coordinates of every point by a reversed vector made from the center coordinates (this is how it would look like if you drew it after this operation - the polygon's center is in the center of the coordinate system):

Now, do your scaling:

and move it back by the vector of polygon's center coordinates:

A: when you multiply
poly.Location = new Point(poly.Location.X * 2, poly.Location.Y * 2);
you are doing a stretch operation when you add
poly.Location = new Point(poly.Location.X + 50, poly.Location.Y +50); you are doing a translation operation.

A: If you want to shift everything without modifying the stored coords then just translate the graphics before drawing:
    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.TranslateTransform(100, 100); // shift the origin somehow
        // ... draw the polygons as before ...
    }


text:
Q: Android orientation change I am using this code to detect layout orientation changes but the following code uses the same portrait layout instead of layout kept in layout-land.
 public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
    Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}

}
  <activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden"
      android:label="@string/app_name">

A: If you override onConfigurationChanged method then onCreate method does not called while Screen Orientation changed. Your activity is not restarted. That's why you are getting same layout.
You need to call setContentView(R.layout.your_layout) in onConfigurationChanged method.


text:
Q: Problem: OpenScript does not go to the next iteration after handling of Exception I have built my own error handing in OpenScript osing standard Java
try{
}

catch () {
}

Everything works correctly, It handles exception correctly.
But the problem is that afterwards script does not go to the next iteration, but just calls the public void finish() throws Exception {}
How can I make script go to the next iteration after successfully handling of the exception?

A: Ok, I found the solution.
The situation is that if OpenScript generates one of its own exceptions (e.g. form is not found), than even if you catch it using standard java syntax, then this execution handling seems to be working, but script does not go to the next iteration.
So, the solution is as follows: (it is actually described in documentation):
beginStep("Trying to execute code, which may go wrong", 0);

// Setting error recovery to warning, so the script will not halt
setErrorRecovery(FormsErrorRecovery.ERR_FORMS_FT_ERROR, ErrorRecoveryAction.Warn);

/*
Some code, which can generate error (e.g. form is not found) needs to go here
*/

// setting error recovery back to Fail, so the script will halt at unexpected error
setErrorRecovery(FormsErrorRecovery.ERR_FORMS_FT_ERROR, ErrorRecoveryAction.Fail);

endStep();

// The hasLastError variable is automatically set to true if there was an error in the previous beginStep() --- endStep() block.

if(!hasLastError()){

/* code goes here to be executed if there was no error */

}

else {
 /* code goes here to execute if there was an error */
}


text:
Q: combine two repositories into one, both have branches I have two separate repositories - backend and frontend. I'd like to combine them, so I'm thinking about something like:
git clone git@server.com:backend.git
git clone git@server.com:frontend.git
cd frontend
mkdir frontend
git mv !(frontend) frontend
git commit -a -S -m "Moving frontend into its own subdirectory"

cd ../backend
git remote add frontend ../frontend
git fetch frontend
git checkout -b feature/merge-front-back
git merge -S --allow-unrelated-histories frontend/master
git push origin feature/merge-front-back
git remote rm frontend

...now, after verifying merge:
git checkout master
git merge feature/merge-front-back

so my 1 question is: is it good plan? do you see any flaws or better way?
And 2 question.. what about frontend branches?
Most of them I don't need right now (maybe never), but would like to have option in the future to merge with them.
Do I need repeat above process but for each frontend branch separately, merge frontend/branches/feature1 to backend/branches/front-back-merge-feature1, and so on?
(I asssume backend branches will don't have a problem when merging to "new" master branch containing frontend directory and history)

A:
is it good plan? do you see any flaws or better way?

By  "is it a good plan", I assume you mean "is this set of commands a good way to do what I've set out to do".  In that regard, there are other ways, but I wouldn't say one is better or worse.
There is a step missing if you want the final repo to have the frontend branches; I'll address that below.
More generally - I will provide the caveat, that almost always whatever problem someone tries to solve by combining multiple projects into one repo, is replaced by bigger problems dealing with the combined structure.  Whether these are logically separate projects is something you'll have to determine, but as a rule, I've seen combining repos be a move in the wrong direction more often than not.
But if you're set on your belief that they should be one repo, then those commands (at a glance) seem as good as any.  I guess the obvious question is, why not try them?  The only thing that can be damaged is the newly-created clones.

what about frontend branches?

When you fetch from frontend, your combined repo will get "remote tracking refs" for each of the frontend branches.  So for the frontend branch master you will get remotes/frontend/master.
However, those will be deleted when you remove the remote.  For master that doesn't necessarily matter (since you've merged frontend/master into master).  For the other branches, you need to tell git to keep a ref to them - and, of course, it will be convenient if the ref it keeps is a branch.  One way to do that would be
git fetch frontend refs/heads/*:refs/heads/frontend/*

Here you're creating a frontend namespace for branches, and adding all branches from frontend into that namespace.  (As long as you don't already have either a branch named frontend or an already-existing frontend branch namespace in the backend repo, it's fine.  If you do have one of those for some reason, you would have to use a different name for the namespace.)
These newly-created refs are under refs/heads so they will be treated as proper branches (rather than remote tracking refs), and they won't be deleted when you remove the origin.  From that point on, they are no different than your backend branches.
You might encounter problems when merging a frontend branch to master in the future, or you might not.  git will try to resolve the conflicts resulting from all the files moving; but remember that git doesn't really track file moves - instead it reconstructs them heuristically after the fact - so this mechanism isn't perfect.
If you're worried about such problems - or if you do some test merges and discover that there will be unacceptable levels of problem - then an option would be to rewrite the history of the frontend/* branches to look like the files "always were" under a frontend/ folder.  If I were to do that, I would do that before combining the repositories; i.e. right after cloning frontend I would rewrite the clone's history instead of creating a new commit to move the files.
(You suggest repeating, for each branch, the type of procedure you performed on master.  I'm not confident that would work well, though you could test it.  The problem is that while master is being handled as a merge of unrelated histories, subsequent merges from other frontend branches will not be.  For those merges to work correctly, git would still have to correctly interpret the file moves - and in fact will have to interpret them correctly on both "sides" of the merge.)
If you opt to rewrite the frontend history, the most straightforward approach is to use git filter-branch with a --tree-filter script that moves the files to the subdirectory.  See the git filter-branch docs for details.  (https://git-scm.com/docs/git-filter-branch)


text:
Q: Change Price of configurable quote item with observer I want to change the price of a configurable product I put in my quote. I use the observer sales_quote_add_item but it won't work for configurable products.
I expect the observer method to run twice (for the simple and configurable record that's put in the database) but it's only called once (for the simple product). The record for configurable still has the old prices.
Can anyone tell me how I can change the price for the complete quote-item in such a way that it will also be seen on cart overview, invoices and emails?

A: I figured it out myself. You need to observe the event checkout_cart_product_add_after. In the observer you need the following:
public function change_price(Varient_Event_Observer $observer) {
    // get the quote
    $item = $observer->getQuoteItem();

    // checks for parent item
    if ($item->getParentItem()) {
        $item = $item->getParentItem();
    }

    // your price logic here
    $new_price = 999;

    $item->setCustomPrice($new_price);
    $item->setOriginalCustomPrice($new_price);
    $item->getProduct()->setIsSuperMode(true);
}


text:
Q: Execute different nodejs scripts at a given time I am looking for a good solution on fire different javascript files with nodejs at a given time on a Server running on Ubuntu.
I have about 10 different scripts and each should be fired 15 times a day! My first approach was to use at but this gets really messy with that much events.
Now I thought about using Node-Schedule what some of you guys here on SO suggested but I'm not sure if that's the best solution for my task ...
If Node-Schedule should still be the best approach - what structure would you use?
var schedule = require('node-schedule');
var d1 = new Date(2015, 10, 20, 18, 55, 0);
var d2 = new Date(2015, 10, 20, 18, 58, 0);

var xd1 = schedule.scheduleJob(d1, function(){
    test.js;
});

var xd2 = schedule.scheduleJob(d2, function(){
    test.js;
});

Doesn't seems that DRY ... ;)

A: If you need to run your scripts on a daily basis, this date based scheduling is not the best solution. The cron style scheduling is a better fit.
For example
var xd1 = schedule.scheduleJob('0 * * * *', function(){
    test.js;
});

will run your function every hour (0:00, 1:00, 2:00 and so on = 24 times a day).
And
var xd1 = schedule.scheduleJob('0 */2 * * *', function(){
    test.js;
});

will run your function every two hours (0:00, 2:00, 4:00 and so on = 12 times a day).
Is the 15 times a day a hard requirement? You can't define this kind of interval very easy with the cron syntax, without splitting it up into different cronjobs (= define more job with the same function call).
This example would run 15 times a day, but it is not balanced throughout the day:
var xd1 = schedule.scheduleJob('*/25 */5 * * *', function(){
    test.js;
});

A: I wouldn't create a node program just to schedule another node program. Use plain cron.
If you can run your job 16 times a day instead of 15 times, it would be every 90 minutes which you can schedule with these two cron expressions:
' 0 0/3 * * * node test.js'
'30 1/3 * * * node test.js'

If it has to be 15 times, this schedule has pretty good distribution (at most once an hour, at least every other hour, 15 times per day):
'0 0/2,1,9,17 * * * node test.js'

Any difficulty understanding this schedule, use this site. If you need your 15 invocations to be spaces equally (every 96 minutes), I'm afraid you'd need to break them into 5 schedules:
 0 0,8,16  * * * node test.js
36 1,9,17  * * * node test.js
12 3,11,19 * * * node test.js
48 4,12,20 * * * node test.js
24 6,14,22 * * * node test.js


text:
Q: How to calculate "compound" Markov transition matrix in Stata or R? By "compound" I mean the transition matrix satisfies the Markov property,namely I have two columns s_t and s_t+k that represent state of each individual in two period t and t+k respectively.
What I want is to find the matrix M that
s_t+k = M^k * s_t

so that matrix M satisfies the Markov property.
My default working language is Stata, in which commands like tab, svy:tab or xttran can generate one period transition matrices, but these matrices do  not necessarily satisfy the Markov property. So I wonder how to achieve my goal in Stata or other common language like R or Python.
PS:This problem raise from a paper which research many countries' GDP_per_capita transition dynamics from 1960 to 2010. Say, at the beginning of each decades, we group all countries into 5 groups (from 1:extremely poor country to 5: high-income country), so we have a distribution of countries with 5 states. It's easy if I simply estimate the decade-to-decade transition matrix using markovchain class. However, the author claim that (page11, footnote4)

"The  decade  average  transition  matrix  is  estimated  based  on
  the  5-decade transition  matrices  from  1960  to  2010  by employing
  a numerical optimization program. Instead of taking the simple average
  for the five transition matrices (which suffers from Jensen's
  Inequality), we estimate a transition matrix that can give us an exact
  5 decade duration transition  matrix (entry in 1960 and exit in 2010)
  by taking its power 5."

A: In R you can use the markovchain package to get the transition matrix that satisfies markov property. You can use the following example code...
library(markovchain)
data(rain)
mysequence<-rain$rain
createSequenceMatrix(mysequence)
myFit<-markovchainFit(data=mysequence,,method="bootstrap",nboot=5, name="Bootstrap Mc")
myFit

The myFit is your  estimated transition matrix. This example uses the Alofi rainfall dataset.

A:
  The multiplication of matrix in R is not * but %*%.
  I wrote a simple function in R to solve the problem.
    trans_mat = function(k,s_t,M){
      for(i in 1:k){
       M = M % * % M
         }
      return(M%*%s_t)}

now, what you need to do is to type in k(how long the period you want),s_t(the original state), and M(markov property).
    s_t+k  = trans_mat(k,s_t,M)

A: The markovchain package directly implements the power for any markovchain object:
require(markovchain)
#creating the MC
myMatr<-matrix(data=c(0.2,0.8,.6,.4),ncol=2,byrow=TRUE)
myMc<-as(myMatr,"markovchain")
#5th power of the MC
myMc5<-myMc^5
myMc5


text:
Q: Exercise 14, section 9 of Hammack's Book of Proof. The exercise asks the reader to prove or disprove the following statement.
If $A$ and $B$ are sets, then $\mathscr{P}(A) \cap \mathscr{P}(B) = \mathscr{P}(A \cap B)$.
I know one way to prove such a statement is to simply produce a series of equalities that transform the LHS of the equation into the RHS. However, I am not sure if my translation of the powersets into set builder notation is valid. More specifically, the book never gives an example of a quantifier used in a set builder so I tried to translate from the book's definition of a subset written in English (as opposed to symbolic notation). Bellow is my proof.
Proof. Observe the following sequence of equalities.
\begin{align}
\mathscr{P}(A) \cap \mathscr{P}(B) &= \{ X: X \subseteq  A \land X \subseteq B\} &(\text{def. of powerset}) \\
&= \{ X: \forall x \in X, x \in A \land x \in B \} &(\text{def. of subset}) \\
&= \{ X:\forall x \in X, x \in A \cap B \} &(\text{def. of intersection}) \\
&= \{ X: X \subseteq A \cap B \} &(\text{def. of subset}) \\
&= \mathscr{P}(A \cap B) &(\text{def. of powerset})
\end{align}
The proof is complete. $$\tag*{$\blacksquare$}$$
Any feedback on the validity of this proof or on ways it could be better written is greatly appreciated.

A: The proof is correct, and if you're required to use that rather artificial format, it's just fine. You probably are required to give that much detail, but if you're not restricted to that format, it could be given in a form closer to normal mathematical writing:

$X\in\wp(A)\cap\wp(B)$ iff $X\in\wp(A)$ and $X\in\wp(B)$, which is the case iff $X\subseteq A$ and $X\subseteq B$. But that is true iff $X\subseteq A\cap B$, i.e., iff $X\in\wp(A\cap B)$, so $\wp(A)\cap\wp(B)=\wp(A\cap B)$.


text:
Q: Is the minikube VM shared folder safe for online use of the cluster? I'm running minikube on a MacOSX host with a VirtualBox hypervisor. It shares a folder (/Users) with the host. What for and how safe is this,  safe enough to run my cluster online?
I guess it is deifficult to escape a container and then a pod and then the VM, but I got in there simply with minikube ssh and, I wasn't aware of the shared folder and that the shell allows me to explore the host.

A: No, it is not safe. Imagine having a pod deployed with a container image that was built with a USER daemon directive in the Dockerfile, which makes the container run under the daemon user. What if an attacker gets access to your image registry and pushes a different image under the same tag? The attacker's image is configured to run as the root user. When Kubernetes schedules a new instance of your pod, the Kubelet will download the attacker's image and run whatever code they put into it.
Although containers are mostly isolated from the host system, running their processes as root is still considered a bad practice. For example, when a host directory is mounted into the container, if the process running in the container is running as root, it has full access to the mounted directory, whereas if it's running as non-root, it won't.
To prevent the attack scenario described previously, you can specify that the pod's container needs to run as a non-root user, as shown in the following listing.
apiVersion: v1
kind: Pod
metadata:
  name: pod-run-as-non-root
spec:
  containers:
  - name: main
    image: alpine
    command: ["/bin/sleep", "999999"]
    securityContext:
      runAsNonRoot: true


text:
Q: Nginx: How to escape argument value for proxy_pass We have such a location configuration:
location ~ ^/suggest/(?<search>.+) {
    proxy_pass https://internal.host/v1/products?suggest=$search;
}

The problem is that internal.host receives $search as is, which means that anyone from the outside can pass &another_param=value as a value of $search and thus gain unauthorized access to the remote endpoint.
The question is: how to escape the argument value?

A: location ~ ^/app/(.*)$ {
    proxy_pass       http://192.169.154.102:9999/some_dir/$1;
}

This examples results in:
test.com/app/request/xxxxx => http://192.168.154.102:9999/some_dir/xxxxx

Not that the example needs to be adjusted to fit your needs.
Please review this link for more information on proxy_pass(ing) with arguments. Additionally your web application/script that takes in the arguments should perform a check on the parameters given. Before anything is done with the parameters, perform checks and/or filtering of the parameter passed! Please also do some checks, if the above method does limit the parameter, which it should - but please check.
Example from: Nginx proxy_pass: examples for how does nginx proxy_pass map the request.


text:
Q: Handling oauth redirects in angular 2+ SPA preventing refresh So basically what I have is an angular 4 SPA. I am trying to integrate the gmail api which uses oauth. I have to specify a redirect url while connecting to the authorization url.
The SPA needs to go to the authorization url(which is external url of google in this case) which will ask user to give permission. Then once permission is given, the gmail api will redirect to our application(SPA).
I am wondering how do I implement this flow without having a page reload/refresh.Since we have to go to the authorization url, we would need to leave our angular SPA.
Also if there is a redirect, then surely the redirect url will be loaded in the browser. So how do I avoid this page refresh on redirection in oauth?


text:
Q: Unix script with || not working I am writing a unix script which looks like
#!/bin/ksh

switch=$1
echo $switch
if [ $switch != "on" ] || [ $switch != "off" ]
then
     echo "Some message blah "
     exit 0
fi

I run the script as ksh test.ksh on and pass an argument at runtime But the code is not working. Regardless of me passing 'on' or 'off' on the console i get Some message blah. Please let me know how to rectify this.
Thanks in advance,

A: Your condition will always evaluate to true since $switch cannot be on and off at the same time. In natural language it could be worded as:

if $switch is not "on" or $switch is not "off" then...

One of these two conditions will always be true. Perhaps you meant to use && instead of ||?


text:
Q: Twitter REST API: Possible to Hotlink Twitter Images? Why No Image Display In Firefox? I am trying to extract images from Twitter REST API and display those images.
Insodoing I have come to a logical impasse with my PHP/HTML code not displaying the images in the browser of my localhost PHP built-in developer server.  I prefer Firefox as more secure (private) browser, so I first develop in Firefox.
I thought that the issue of images not displaying was perhaps issue of Twitter not allowing hotlinking to their images, however I just tested this same code (below) in both Chrome and Internet Explorer browsers, and all the images appear fine.
So my [updated] question is:  why are these images not appearing in either Firefox or Firefox Developer Edition browsers?  Twitter clearly doesn't have an issue with hotlinking to their images that have been extracted via their API as demonstrated by images showing up fine in both Chrome and Internet Explorer browsers.
Who has the answer to this interesting issue?
<!DOCTYPE html>

        <?php

        // USED TO DEBUG WHY HTTPS WAS NOT WORKING IN THE BEGINNING
        // var_dump(stream_get_wrappers());

        ?>

        <?php

            // REQUIRE TWITTEROAUTH LIBRARY
            require "twitteroauth/autoload.php";

            // I HAVE HACKED AROUND WITH THIS, BUT DON'T SEE WHY ABRAHAM IS NECESSARY SINCE THERE IS NO FOLDER NAMED ABRAHAM,
            // BUT CODE DOES NOT WORK WITHOUT THIS, SO LEAVE IT IN!  :)
            use Abraham\TwitterOAuth\TwitterOAuth;

            // DECLARE VARIABLES OF KEYS, SECRET, TOKEN, & TOKEN_SECRET
            $CONSUMER_KEY = "12345";
            $CONSUMER_SECRET = "12345";
            $access_token = "12345";
            $access_token_secret = "12345"

            // DEFINE NEW CONNECTION VARIABLE: I.E. CONNECTION TO TWITTER VIA TWITTEROAUTH
            $connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $access_token, $access_token_secret);

            // CREATE MULTIPLE-PARAMETER QUERY AS ARRAY
            $query = array(
              "q" => "#MickeyMouse",
              "count" => "1000",
              "include_entities" => "true"
            );

            // MAKE CONNECTION TO TWITTER, GET METHOD FOR "SEARCH/TWEETS", PASS ARRAY AS QUERY
            $result = $connection->get("search/tweets", $query);

            // TEST OUTPUT FOR DEBUGGING
            //var_dump($result);

            // CREATE VARIABLES:  NEW EMPTY ARRAYS
            $ArrayPhotoURLs = array();

            // FOR LOOP,
            foreach ($result->statuses as $content) {

                // IF EACH TWEET/STATUS HAS MEDIA,
                if (isset($content->entities->media)) {

                    // THEN GET THOSE MEDIA URLS
                    foreach ($content->entities->media as $media) {
                        $media_url = $media->media_url; // Or $media->media_url_https for the SSL version.

                        // AND ASSIGN/APPEND EACH MEDIA URL TO THE ARRAY OF MEDIA URLs
                        $ArrayPhotoURLs[] = $media_url;

                        // TEST OUTPUT FOR DEBUGGING
                        //print(gettype($media_url));
                        //print_r($media_url);
                        //var_dump($media_url);
                    }

                }

            }

            // TEST OUTPUT FOR DEBUGGING
            //var_dump($ArrayPhotoURLs);

            // COUNT IMAGES IN ARRAY OF TWITTER IMAGE URLS - TO BE USED BELOW TO CREATE DYNAMIC LIST / ANCHOR / IMG ITEMS
            $imagecount = count($ArrayPhotoURLs);

            // TEST OUTPUT FOR DEBUGGING
            echo $imagecount;
        ?>

<?php // HTML LAYOUT CODE BEGINS HERE ?>

                <?php
                    // FOR LOOP, PRINT HTML WITH URL AS BOTH A HREF & IMG SRC PARAMETERS & ANCHOR TEXT
                    foreach ($ArrayPhotoURLs as $PhotoURL) {

                        echo '',
                        '', $PhotoURL,
                        '
';
                    }
                ?>

A: For those in a similar bind:
Firefox apparently treats the domain pbs.twimg.com as a tracker and blocks all connections made to this subdomain. Consider disabling Tracking Protection in your browser or implement a server-side shim to preload the images.
See:
https://bugzilla.mozilla.org/show_bug.cgi?id=1458915


text:
Q: SSRS show average column in metrics report I have to show average columns on right and bottom of a SSRS matrix report under.
        B       C       D       E       F       G       H       I       TOTAL
ABC     0       0       0       0       0       0       2       0       2       7.14%
PQR     0       0       0       1       0       0       0       0       1       3.57%
KLM     5       4       5       0       4       4       0       0       22      78.57%
HIJ     0       0       0       0       0       0       0       0       0       0.00%
XYZ     1       1       0       0       0       0       0       1       3       10.71%
TOTAL   6       5       5       1       4       4       2       1       28      100.00%
    21.43%  17.86%  17.86%  3.57%   14.29%  14.29%  7.14%   3.57%   100.00%

I have completed all other columns i.e. Total, but stuck to get average in last row and last column.
Thanks

A: Try this to get average value:
=Avg(Fields!MyFieldName.Value)


text:
Q: How do I make sure grub is only installed once? I currently have Windows on one partition, and Ubuntu on another. I'd like to install Quimo, and possibly Mint and/or Lubuntu as well.
How do I make sure that only Ubuntu has Grub, and that the others don't install it too, or, if more appropriate, make sure that Ubuntu is the only one that is used?

A: The installation of grub has 2 parts: the resource files, and the boot loader. Each OS installation has its own resource files, but the boot loader is always installed on the master boot record. Effectively, the boot loader that is installed later will overwrite the former. In that sense, you can have only one full functional grub at a time.
I guess the tricky part (and your real question) is, how to make several Os'es work together in a multiboot fashion. This can be done in 2 ways:
The first is to make the main grub installation load the other OS'es. This is done my modifying the grub config (specifically the file /boot/grub/grub.cfg) to include instructions on how to load additional OS'es. On some distributions (I think Ubuntu) this can be done automatically by an OS prober. This method is not very nice, as it requires changes to the main installation every time you upgrade the kernel, but it works.
The second is to make secondary OS'es install their boot loader on a partition rather than the MBR, and tell the main grub installation to chainload the secondary installations. I have a separate question on this (didn't really work for me so please add an answer if you make it). This method is elegant and is my preferred, however setting it up can be tricky depending on your luck.

A: As a practical answer on how to do what @phunehehe wrote, i would suggest that during the installation precess of the other distros you have a choice (usually under an advanced button) to untick the option to install Grub on the MBR, and hence you can be sure that your current Grub isn't replaced.
But in order to make the Ubuntu's Grub to be aware on the new distros, you have to probe the disk for the other OSs installation with a program like os-prober, that does it automatically for you when you run the sudo grub-mkconfig -o /boot/grub/grub.cfg (of course after backing up the grub.cfg file). and sudo update-grub at the end.
In case it has hard time to find your OSs, you can create custom file (40_custom) and in it point to your other OSs kernel and initrd files, see this ubuntu wiki article about Grub2 it includes all the information you need.


text:
Q: mongodb replicaset host name change error I have a mongodb replicaset on ubuntu.. In replica set, hosts are defined as localhost. You can see ;
{
    "_id" : "myrep",
    "version" : 4,
    "members" : [
            {
                    "_id" : 0,
                    "host" : "localhost:27017"
            },
            {
                    "_id" : 2,
                    "host" : "localhost:27018"
            },
            {
                    "_id" : 1,
                    "host" : "localhost:27019",
                    "priority" : 0
            }
    ]

}
I want to change host adresses with real ip of server. But when i run rs.reconfig, I get error :
{
    "assertion" : "hosts cannot switch between localhost and hostname",
    "assertionCode" : 13645,
    "errmsg" : "db assertion failure",
    "ok" : 0

}
How can i solve it ?
Thank you.

A: There is a cleaner way to do this:
use local
cfg = db.system.replset.findOne({_id:"replicaSetName"})
cfg.members[0].host="newHost:27017"
db.system.replset.update({_id:"replicaSetName"},cfg)

then restart mongo

A: The only way I found to change host names is recreating replica set.. To make it right db directories need to be cleaned.. Then starting all servers with replication mode after that creating new repset with new host names fixed it.


text:
Q: I don't understand this vector declaration statement Why LOG and 0 are used in this statement?
LOG = 35;
 vector<int> cnt(LOG, 0); //here cnt is a vector name

A: The statement is constructing a std::vector, so you should look at help documentation for the vector constructor.
In this case, LOG and 0 are being used specifically in the two-parameter override of the constructor.

*

*LOG is used to specify the initial size of the vector;

*0 is used to specify the initial value of the elements.

In other words, the expression declares a vector named cnt being of size 35 with all elements initialized to 0.