text:
Q: Include custom taxonomy term in search I have two custom taxonomies applied to two custom post types. the terms list on the sidebar just fine and will list all posts associated with it. However, if you search one of the terms in specific, it doesn't bring up a post with that term.
Example: http://dev.andrewnorcross.com/das/all-case-studies/
Search for term "PQRI"
I get nothing. Any ideas? I've tried using various search plugins but they either break my custom search parameters or just don't work.

A: Is this the standard WordPress search? Because that doesn't seem to include taxonomies (not even standard, like categories and tags) in the search. The code searches in post_title and post_content, but if you want to include anything else you should hook into the posts_search filter.

A: I tried the solution of Onetrickpony above https://wordpress.stackexchange.com/a/5404/37612, which is great, but I found one issue there, which did not work for me, and I would make one small  modification:

*

*if I searched for a string in the title of the taxonomy - it works great

*if the taxonomy has special characters e.g. with german "Umlauts" (ö,ä,ü) and one searches for oe, ae, ue insteda of using the special char - you need to add the search in the slug of the taxonomy -
OR t.slug LIKE '%".get_search_query()."%'

*if you search for a combination of a search query and a taxonomy filter - this also works fine

*But the problem is, when you try to use only the taxonomy filter - the search hook append an empty string to the query if no text is searched for, and for that reason you get ALL posts in the result, instead of only those from the filtered taxonomy.
A simple IF statement solves the problem. So the whole modified code would be this (works perfectly fine for me!)

function custom_search_where($where){
  global $wpdb;
  if (is_search() && get_search_query())
    $where .= "OR ((t.name LIKE '%".get_search_query()."%' OR t.slug LIKE '%".get_search_query()."%') AND {$wpdb->posts}.post_status = 'publish')";
  return $where;
}

function custom_search_join($join){
  global $wpdb;
  if (is_search()&& get_search_query())
    $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id";
  return $join;
}

function custom_search_groupby($groupby){
  global $wpdb;

  // we need to group on post ID
  $groupby_id = "{$wpdb->posts}.ID";
  if(!is_search() || strpos($groupby, $groupby_id) !== false || !get_search_query()) return $groupby;

  // groupby was empty, use ours
  if(!strlen(trim($groupby))) return $groupby_id;

  // wasn't empty, append ours
  return $groupby.", ".$groupby_id;
}

add_filter('posts_where','custom_search_where');
add_filter('posts_join', 'custom_search_join');
add_filter('posts_groupby', 'custom_search_groupby');

A: I would recommend the Search Everything plugin too, but if you want to implement this using WP's search function, here's the code I'm using in my Atom theme:
// search all taxonomies, based on: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23

function atom_search_where($where){
  global $wpdb;
  if (is_search())
    $where .= "OR (t.name LIKE '%".get_search_query()."%' AND {$wpdb->posts}.post_status = 'publish')";
  return $where;
}

function atom_search_join($join){
  global $wpdb;
  if (is_search())
    $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id";
  return $join;
}

function atom_search_groupby($groupby){
  global $wpdb;

  // we need to group on post ID
  $groupby_id = "{$wpdb->posts}.ID";
  if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby;

  // groupby was empty, use ours
  if(!strlen(trim($groupby))) return $groupby_id;

  // wasn't empty, append ours
  return $groupby.", ".$groupby_id;
}

add_filter('posts_where','atom_search_where');
add_filter('posts_join', 'atom_search_join');
add_filter('posts_groupby', 'atom_search_groupby');

It's based on the Tag-Search plugin: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23

A: I found the answer from onetrickpony to be great but it treats any search as a single term and also won't deal with a search phrase enclosed with quotation marks. I modified his code (specifically, the atom_search_where function) a bit to deal with these two situations. Here is my modified version of his code:
// search all taxonomies, based on: http://projects.jesseheap.com/all-projects/wordpress-plugin-tag-search-in-wordpress-23

function atom_search_where($where){
    global $wpdb, $wp_query;
    if (is_search()) {
        $search_terms = get_query_var( 'search_terms' );

        $where .= " OR (";
        $i = 0;
        foreach ($search_terms as $search_term) {
            $i++;
            if ($i>1) $where .= " AND";     // --- make this OR if you prefer not requiring all search terms to match taxonomies
            $where .= " (t.name LIKE '%".$search_term."%')";
        }
        $where .= " AND {$wpdb->posts}.post_status = 'publish')";
    }
  return $where;
}

function atom_search_join($join){
  global $wpdb;
  if (is_search())
    $join .= "LEFT JOIN {$wpdb->term_relationships} tr ON {$wpdb->posts}.ID = tr.object_id INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id=tr.term_taxonomy_id INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id";
  return $join;
}

function atom_search_groupby($groupby){
  global $wpdb;

  // we need to group on post ID
  $groupby_id = "{$wpdb->posts}.ID";
  if(!is_search() || strpos($groupby, $groupby_id) !== false) return $groupby;

  // groupby was empty, use ours
  if(!strlen(trim($groupby))) return $groupby_id;

  // wasn't empty, append ours
  return $groupby.", ".$groupby_id;
}

add_filter('posts_where','atom_search_where');
add_filter('posts_join', 'atom_search_join');
add_filter('posts_groupby', 'atom_search_groupby');

A: I have the same level of information like Jan. I know it's possible to extend search with plugins as well.
Probably Search Everything (Wordpress Plugin) is what you are looking for. According to the feature list, it now supports custom taxonomies.

A: I have the same problem going on with the WooCommerce cart plugin.. My search results are not including the custom taxonomy term, 'product_tag', because it not a standard post tag. I found a solution in this other StackOverflow thread about the matter:
https://stackoverflow.com/questions/13491828/how-to-amend-wordpress-search-so-it-queries-taxonomy-terms-and-category-terms
The code example by tkelly worked for me when replacing the term author in his example with product_tag as per our needs for the cart plugins.


text:
Q: Show that the following function has a gauge-integral and calculate its value. We define:
$$f: I = [0,1] \rightarrow \mathbb{R}: x \mapsto f(x) = \sin(x)1_{[0,1] - \mathbb{Q}} + x1_{[0,1]\cap\mathbb{Q}} $$
where $1_A$ is the characteristic function on A.
Show that $f$ has a gauge integral on [0,1] and calculate it.
I've come across this problem and I don't have a clue on how to solve it. I thought about using the definition of gauge integral but that would require me to "guess" what the value of $\int_I f$ actually is. Having no clue what $\int_I f$ is worth I've been thinking about using Cauchy's criterion instead but without much success.
Any help or clues appreciated.

A: It's easily to show gauge-integrability using one math trick.
All the folowing will be done in assumption that gauge-integral is Henstock-Kurzweil integral. (H.-K. integral).
We know that if $f$ and $g$ are H.-K. integrable then $f+g$ also H.-K. integrable.
So, let's rewrite your function as
$$
\sin(x) + (x-\sin(x))1_{[0,1]\cap\mathbb{Q}}
$$
First part, $f = \sin(x)$ is Riemann integrable (and consequently H.-K. integrable with gauge $\delta_1(x)$ equals some constant value, depending on $\varepsilon$).
Second part, $g = (x-sin(x))1_{[0,1]\cap\mathbb{Q}}$ is H.-K. integrable with gauge $$\delta_2(x) = \bigg(\frac{\varepsilon}{2^{k+1}}\bigg)1_{[0,1]\cap\mathbb{Q}} + 1_{[0,1]\setminus\mathbb{Q}}$$
where $k$ means number of rational number.
For any $\tau=\{\xi_i,\Delta_i\}_{i=1}^n$ - $\delta_2$-partition of $[0,1]$ sum $$\bigg|\sum_{i=1}^n g(\xi_i)|\Delta_i|\bigg| \leq \sum_{k=1}^\infty g(r_k)2\delta(r_k) < \sum_{k=1}^\infty \frac{2\varepsilon}{2^{k+1}} = \varepsilon$$
where $r_k$ means $k$-th rational number. That's why $\int_{[0,1]}g(x)dx = 0$
So, your function is integrable as sum of integrable functions. If you want an explicit formula for gauge, you can try to construct it from $\delta_1$ and $\delta_2$.

A: Because $f$ is Lebesgue-integrable, then the gauge integral is the same that the Lebesgue integral. Now, for this:
$\int_I f=\int_I sin(x)=-cos(1)+1$
The first $=$ works because the Lebesgue integral over a $0$-measure set is $0$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display the stars according to the ratings in html view in ASP.NET MVC? I am building an asp.net mvc application. I display the ratings of a resource on a page using stars. Depending on the average rating the equivalent number of stars should be displayed.
I have written out the following code:
 // displays 1 star
 // display 1 empty star

// Displays the average ratings float value
@foreach(var resource in ViewBag.Resources)
{

@resource.Ratings

}

I want something like this to be displayed
@foreach(var resource in ViewBag.Resources)
{
  @resource.Ratings *  (1-@resource.Ratings) *
}

How can this be done? Thanks

A: @for (int i = 0; i < Int32.Parse(@resource.Ratings); i++)
{

}
@for (int i = Int32.Parse(@resource.Ratings); i < 5; i++ )
{

}
@resource.Ratings stars

A: Use JavaScript Library for displaying stars in efficient way and good UI, you have many options
Five stars rating
bootstrap-star-rating


text:
Q: Binding to parent datacontext to work with a PropertyChangedEventHandler I'm having difficulties on updating a listbox with a change in the list it is bound to.
The main window has the datacontext set through code-behind:
public partial class MainWindow : Window
{
    private ConfigurationListViewModel _ConfListVM;
    public MainWindow()
    {
        _ConfListVM = new ConfigurationListViewModel();
        InitializeComponent();
        DataContext = _ConfListVM.ConfList;
        this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
        ConfigMng.CreatedConfigurationEvent += new EventHandler(OnCreateConfiguration);
    }

    void OnCreateConfiguration(object sender, EventArgs e)
    {
        _ConfListVM.Add("Test");
    }

}

public class ConfigurationListViewModel
{
    public ConfigurationList ConfList = new ConfigurationList();
}

public class ConfigurationList : INotifyPropertyChanged
{
    private ObservableCollection<Configuration> _ObservableConfList = new ObservableCollection<Configuration>();
    public ObservableCollection<Configuration> ObservableConfList { get { return _ObservableConfList; } set { _ObservableConfList = value; } }

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public ConfigurationList()
    {
        ObservableConfList.Add(new Configuration("aaa"));
        ObservableConfList.Add(new Configuration("bbd"));
    }

    public void Add(Configuration Conf)
    {
        ObservableConfList.Add(Conf);
        OnPropertyChanged(Conf.ConfName);
    }
}

}
In the Main Window XAML I set the User Control:
<GroupBox Header="Configurations" >
    <local:ConfigurationMng x:Name="ConfigMng"/>
</GroupBox>

And in the ConfigurationMng I have the following ListBox, that I bound to the list ConfList
<ListBox Name="lbConfigurationList" ItemsSource="{Binding ObservableConfList, UpdateSourceTrigger=PropertyChanged, diag:PresentationTraceSources.TraceLevel=High}">
I can see correctly in the ListBox the 2 element I created with the constructor, but when I manually add another element, PropertyChanged is always null.
I think I understood that I have to set a DataContext (but I thought that if not manually specified, it should use its parent one);
I tried then to set it manually:
<ListBox Name="lbConfigurationList" DataContext="{Binding [??????], RelativeSource={RelativeSource AncestorType={x:Type Window}}}" ItemsSource="{Binding ObservableConfList, UpdateSourceTrigger=PropertyChanged, diag:PresentationTraceSources.TraceLevel=High}">

but I got stuck on understanding on what should I bind it.
Am I now in MainWindow's datacontext? So i'm in the scope _ConfList.ConfList? I should write just Binding and I should be in the correct DataContext, right?
Nope, even the manually added Configurations disappear.
What am I missing here?
Edit: ConfigurationMng's CodeBehind:
public partial class ConfigurationMng : UserControl
{
    public event EventHandler CreatedConfigurationEvent;

    public ConfigurationMng()
    {
        InitializeComponent();
    }

    private void AddConfiguration(object sender, RoutedEventArgs e) //Called with a button pression
    {
        if (this.CreatedConfigurationEvent != null)
        {
            this.CreatedConfigurationEvent(sender, e);
        }
    }
}

Solved, the problem seems that the main ConfigurationListViewModel wasn't implementing the INotifyPropertyChanged interface, so he just wasn't notifying the listbox of the change.
I can't write the actual solution since I rewrote this part of the project

A: You are correct that it will inherit the parent's DataContext.
<ListBox Name="lbConfigurationList" DataContext="{Binding [??????], RelativeSource={RelativeSource AncestorType={x:Type Window}}}" ItemsSource="{Binding ObservableConfList, UpdateSourceTrigger=PropertyChanged, diag:PresentationTraceSources.TraceLevel=High}">

Since your assumption that parent datacontext is inherited, you don't need to explicitly set the DataContext for ListBox. You just need to make sure that your ItemsSource is defined like this
ItemsSource="{Binding ConfList.ObservableConfList, UpdateSourceTrigger=PropertyChanged, diag:PresentationTraceSources.TraceLevel=High}"

You are binding to an ObservableCollection which you don't need INotifyPropertyChanged in your ViewModel because the collection alreay takes care of that. If you want to handle the added/deleted elements then you can use the CollectionChanged of the collection.
Also, your Model Configuration should implement INotifyPropertyChanged if you would want to listen on each item.
From what I can see, your architecture is adding more complexity. Why did you need to create a separate class just to have an ObservableCollection? You can just put it in the ViewModel and leave your Configuration as your model.


text:
Q: Why doesn't disk io occur to read file system metadata despite clearing dentry and inode with drop_cache command? As the title says, I am confused about "echo # > /proc/sys/vm/drop_caches" and blockdev --flushbufs.

http://pages.cs.wisc.edu/~remzi/OSTEP/file-implementation.pdf

According to OSSTEP, If the target inodes are not cached in memory, disk IO should be occur to read the inode, which will make a dentry data structure on memory.
To my knowledge, echo 3 > /proc/sys/vm/drop_caches is to drop(clear) page cahche, inodes and dentry.
I have experimented with blktrace to figure out whether disk io is really occurring to read the inode.
1) echo 3 > /proc/sys/vm/drop_caches
> 259,0   38        1     0.000000000 40641  Q   R 109314048 + 32 [cat]
> 259,0   38        2     0.000004096 40641  G   R 109314048 + 32 [cat]
> 259,0   38        3     0.000027108 40641 UT   N [cat] 1
> 259,0   38        4     0.000027862 40641  I   R 109314048 + 32 [cat]
> 259,0   38        5     0.000036393 40641  D   R 109314048 + 32 [cat]
> 259,0   38        6     0.006268251     0  C   R 109314048 + 32 [0]

However, there is no disk io to read inode. I can only see the disk io to read 16KB data block.
2) echo 3 > /proc/sys/vm/drop_caches and blockdev --flushbufs /dev/nvme0n1
259,0    1        1     0.000000000   325  Q  RM 74232 + 8 [cat]
259,0    1        2     0.000004854   325  G  RM 74232 + 8 [cat]
259,0    1        3     0.000026263   325  D  RM 74232 + 8 [cat]
259,0    1        4     0.006292470     0  C  RM 74232 + 8 [0]
259,0    1        5     0.006382162   325  Q  RM 109052160 + 8 [cat]
259,0    1        6     0.006385621   325  G  RM 109052160 + 8 [cat]
259,0    1        7     0.006393322   325  D  RM 109052160 + 8 [cat]
259,0    1        8     0.006455750     0  C  RM 109052160 + 8 [0]
259,0    1        9     0.006511245   325  Q  RM 109117696 + 8 [cat]
259,0    1       10     0.006512342   325  G  RM 109117696 + 8 [cat]
259,0    1       11     0.006514627   325  D  RM 109117696 + 8 [cat]
259,0    1       12     0.006591933     0  C  RM 109117696 + 8 [0]
259,0    1       13     0.006624544   325  Q  RM 109117704 + 8 [cat]
259,0    1       14     0.006625538   325  G  RM 109117704 + 8 [cat]
259,0    1       15     0.006627567   325  D  RM 109117704 + 8 [cat]
259,0    1       16     0.006688973     0  C  RM 109117704 + 8 [0]
259,0    1       17     0.006764838   325  Q   R 109314048 + 32 [cat]
259,0    1       18     0.006766035   325  G   R 109314048 + 32 [cat]
259,0    1       19     0.006768078   325 UT   N [cat] 1
259,0    1       20     0.006768755   325  I   R 109314048 + 32 [cat]
259,0    1       21     0.006773426   325  D   R 109314048 + 32 [cat]
259,0    1       22     0.006854480     0  C   R 109314048 + 32 [0]

I found block access (+8(512*8=4KB)) to read inode.
A quick look at how blockdev --flushbufs works in the kernel code shows that it clears the superblock.
Why doesn't disk io to read inodes with drop_cache alone?
The ULK book says that inodes or superblocks are cached in buffer-cache.
The book ULK says that inodes and superblocks are cached in buffer-cache.
Is this the reason for this?
Thank you


text:
Q: Set focus on specific cell of last row of a table when text box value changes What I wanted to do !!
I have a one text-box on page, on page load focus will be set into text-box i will scan one item and it's digits will be inserted into text-box.Based on values it will add one row in html table.At the same time i wanted set focus on "CODE" cell text-box.
So every time I scan something it will insert a row into below table and every time i wanted to set focus on cell of CODE column of last row.Here in code column we will scan the value and it will be displayed on the same cell.
Further more if possible I wanted to set focus back to the text-box after scanning value in code cell value.So basically its back and forth scanning process.

<input type="text" name=" " value=" ">

        Id
        Name
        Code
        Text

        (null)
        (null)

          <input type="text" name="f02" size="15" maxlength="2000" value="" class="u-TF-item u-TF-item--text" id="f02_0000" />

          <input type="text" name="f03" size="15" maxlength="2000" value="" class="u-TF-item u-TF-item--text" id="f03_0000" />
          <input type="hidden" name="f01" value="" class="u-TF-item u-TF-item--hidden" id="f01_0000" />
          <input type="hidden" name="f04" value="" class="u-TF-item u-TF-item--hidden" id="f04_0000" />
          <input type="hidden" id="fcs_0000" name="fcs" value="">
          <input type="hidden" id="fcud_0000" name="fcud" value="D" />

        90001
        Samsung Galaxy J3 Pro

          <input type="text" name="f02" size="15" maxlength="2000" value="123456" class="u-TF-item u-TF-item--text" id="f02_0001" />

          <input type="text" name="f03" size="15" maxlength="2000" value="1" class="u-TF-item u-TF-item--text" id="f03_0001" />
          <input type="hidden" name="f01" value="" class="u-TF-item u-TF-item--hidden" id="f01_0001" />
          <input type="hidden" name="f04" value="1" class="u-TF-item u-TF-item--hidden" id="f04_0001" />
          <input type="hidden" id="fcs_0001" name="fcs" value="9F677BEDD6F6624C586A9DA8BB60AA3DC1746ED2">
          <input type="hidden" id="fcud_0001" name="fcud" value="U" />

            1 - 3

To be more clear.
Scan value from a sticker it will insert value into text-box and it will add a rwo into table now same time it will set focus to cell column CODE of last row of here again we will scan value from sticker and after scanning it should set focus back to the textbox.

A: Here you go with a solution

$('table.t-Report-report')
  .find('tr')
  .last()
  .find('input[type="text"]')
  .first()
  .focus();

$('input').first().focus();

<input type="text" name=" " value=" ">

      Id
      Name
      Code
      Text

      	(null)
      (null)
      <input type="text" name="f02" size="15" maxlength="2000" value="" class="u-TF-item u-TF-item--text " id="f02_0000" />
      <input type="text" name="f03" size="15" maxlength="2000" value="" class="u-TF-item u-TF-item--text "  id="f03_0000" /><input type="hidden" name="f01" value="" class="u-TF-item u-TF-item--hidden "  id="f01_0000" /><input type="hidden" name="f04" value="" class="u-TF-item u-TF-item--hidden "  id="f04_0000" /><input type="hidden" id="fcs_0000" name="fcs" value=""><input type="hidden" id="fcud_0000" name="fcud" value="D" />

        90001
        Samsung Galaxy J3 Pro
        <input type="text" name="f02" size="15" maxlength="2000" value="123456" class="u-TF-item u-TF-item--text "  id="f02_0001" />

          <input type="text" name="f03" size="15" maxlength="2000" value="1" class="u-TF-item u-TF-item--text " id="f03_0001" />
          <input type="hidden" name="f01" value="" class="u-TF-item u-TF-item--hidden "  id="f01_0001" /><input type="hidden" name="f04" value="1" class="u-TF-item u-TF-item--hidden "  id="f04_0001" /><input type="hidden" id="fcs_0001" name="fcs" value="9F677BEDD6F6624C586A9DA8BB60AA3DC1746ED2"><input type="hidden" id="fcud_0001" name="fcud" value="U" />

		1 - 3

Hope this will help you.

A: With Length > 0

$(document).on('click', '#btn_process', function() {
  var tr = $('#init_row_invoice').clone(true);
  $('table.t-Report-report tbody').append(tr.show());
  $(tr).find('input[type=text][name=f03]').val('123');
  if ($(tr).find('input[type=text][name=f03]').val().length > 0) {
    $(tr).find('input[type=text][name=f02]').focus();
  } else {}
});

<input type="text" name=" " value=" "><input id="btn_process" type="submit" value="process" /?

        Id
        Name
        Code
        Text

        (null)
        (null)
        <input type="text" name="f02" size="15" maxlength="2000" value="" class="u-TF-item u-TF-item--text " id="f02_0000" />

          <input type="text" name="f03" size="15" maxlength="2000" value="" class="u-TF-item u-TF-item--text " id="f03_0000" />
          <input type="hidden" name="f01" value="" class="u-TF-item u-TF-item--hidden " id="f01_0000" />
          <input type="hidden" name="f04" value="" class="u-TF-item u-TF-item--hidden " id="f04_0000" />
          <input type="hidden" id="fcs_0000" name="fcs" value=""><input type="hidden" id="fcud_0000" name="fcud" value="D" />

        90001
        Samsung Galaxy J3 Pro
        <input type="text" name="f02" size="15" maxlength="2000" value="123456" class="u-TF-item u-TF-item--text " id="f02_0001" />
        <input type="text" name="f03" size="15" maxlength="2000" value="1" class="u-TF-item u-TF-item--text " id="f03_0001" /><input type="hidden" name="f01" value="" class="u-TF-item u-TF-item--hidden "
            id="f01_0001" /><input type="hidden" name="f04" value="1" class="u-TF-item u-TF-item--hidden " id="f04_0001" /><input type="hidden" id="fcs_0001" name="fcs" value="9F677BEDD6F6624C586A9DA8BB60AA3DC1746ED2"><input type="hidden" id="fcud_0001"
            name="fcud" value="U" />

          1 - 3

With Length == 0

$(document).on('click', '#btn_process', function() {
  var tr = $('#init_row_invoice').clone(true);
  $('table.t-Report-report tbody').append(tr.show());
  $(tr).find('input[type=text][name=f03]').val('');
  if ($(tr).find('input[type=text][name=f03]').val().length > 0) {
    $(tr).find('input[type=text][name=f02]').focus();
  } else {}
});

<input type="text" name=" " value=" "><input id="btn_process" type="submit" value="process" /?

        Id
        Name
        Code
        Text

        (null)
        (null)
        <input type="text" name="f02" size="15" maxlength="2000" value="" class="u-TF-item u-TF-item--text " id="f02_0000" />

          <input type="text" name="f03" size="15" maxlength="2000" value="" class="u-TF-item u-TF-item--text " id="f03_0000" />
          <input type="hidden" name="f01" value="" class="u-TF-item u-TF-item--hidden " id="f01_0000" />
          <input type="hidden" name="f04" value="" class="u-TF-item u-TF-item--hidden " id="f04_0000" />
          <input type="hidden" id="fcs_0000" name="fcs" value=""><input type="hidden" id="fcud_0000" name="fcud" value="D" />

        90001
        Samsung Galaxy J3 Pro
        <input type="text" name="f02" size="15" maxlength="2000" value="123456" class="u-TF-item u-TF-item--text " id="f02_0001" />
        <input type="text" name="f03" size="15" maxlength="2000" value="1" class="u-TF-item u-TF-item--text " id="f03_0001" /><input type="hidden" name="f01" value="" class="u-TF-item u-TF-item--hidden "
            id="f01_0001" /><input type="hidden" name="f04" value="1" class="u-TF-item u-TF-item--hidden " id="f04_0001" /><input type="hidden" id="fcs_0001" name="fcs" value="9F677BEDD6F6624C586A9DA8BB60AA3DC1746ED2"><input type="hidden" id="fcud_0001"
            name="fcud" value="U" />

          1 - 3

Check the length like:
$(tr).find('input[type=text][name=f03]').val().length > 0

Set focus
$(tr).find('input[type=text][name=f02]').focus();


text:
Q: Can not produce with dockerized producer into Kafka Did anyone encounter this error ?
io.confluent.kafka.schemaregistry.client.rest.exceptions.RestClientException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n at [Source: (sun.net.www.protocol.http.HttpURLConnection$HttpInputStream); line: 1, column: 2]; error code: 50005\n\tat io.confluent.kafka.schemaregistry.client.rest.RestService.sendHttpRequest(RestService.java:226)

I have this stack trace when I try to produce messages into kafka.
FYI, the kafka stack (kaka, schema-registry and zookeeper) and the producer are dockerized with a docker-compose file.
Any help is appreciated !

A: I'm using a proxy, I added my IP address to http.nonProxyHosts and it works.
The problem was the schema-registry returning HTML rather than JSON, that's why I had this annoying error.


text:
Q: control the output of dunn test I'm using dunn.test() from the package dunn.test, and I don't want it to print anything to the std output (console) because I'm doing it many times, and I want to see if I have any warnings before that.
So I canceled the printing of kruskal wallis test, and the printing of the table like this-
dunn.test(x = data, g = grouping, kw = FALSE, table = FALSE)

but it still prints a newline after each test, is there any way to prevent it from printing the new line? or a way to catch the newline from being printed?
reproducible example of dunn.test-
library(dunn.test)
df <- data.frame(d = c(rnorm(100), rnorm(100, 5)),
                 group1 = rep(c('a','b','c','d'),50),
                 group2 = rep(c('a','b','c','d'),each =50))
test1 <- dunn.test(x = df$d, df$group1)
test2 <- dunn.test(x = df$d, df$group2)
test3 <- dunn.test(x = df$d, df$group1, kw = FALSE)
test4 <- dunn.test(x = df$d, df$group1, kw = FALSE, table = FALSE) # still prints a newline

A: You can use the capture.output()  function to hide the output
capture.output(dunn.test(x = df$d, df$group1))

Any error or warning raised will still be displayed.

A: This answer worked, but the captured output was still printed. Here is a reprex of what worked for me:
library(dunn.test)

capture.output(df <-
  as.data.frame(dunn.test(
    x = iris$Sepal.Length,
    g = iris$Species,
    table = FALSE,
    kw = FALSE,
    label = FALSE,
    alpha = 0.05
  )), file = "NULL")

df
#>       chi2         Z            P   P.adjusted            comparisons
#> 1 96.93744 -6.106326 5.097522e-10 5.097522e-10    setosa - versicolor
#> 2 96.93744 -9.741785 1.000049e-22 1.000049e-22     setosa - virginica
#> 3 96.93744 -3.635459 1.387433e-04 1.387433e-04 versicolor - virginica

Created on 2020-04-17 by the reprex package (v0.3.0.9001)
Note that no message was printed and the output was also assigned to a dataframe.


text:
Q: setxkbmap: Multiple layouts with different variants Using setxkbmap from a user's .xinitrc, I'd like to configure:

*

*German keyboard layout (de) without dead keys (variant nodeadkeys).

*French keyboard layout (fr) with dead keys (variant basic).
So far I only managed to specify the same variant for both:
setxkbmap de,fr nodeadkeys

Is it possible to specify different variants?

A: As per xorg docs and archwiki:

You must specify as many variants as the number of specified layouts.
  If you want the default variant, specify an empty string as the
  variant (the comma must stay)

i.e.
setxkbmap -layout "L1,L2, ... ,Ln" -variant "V1,V2, ... ,Vn"

In your case:
setxkbmap -layout "de,fr" -variant "nodeadkeys,basic"


text:
Q: why setresuid / setresgid works different in Python versus C It some experiments it seems that setresuid / setresgid works differently in C versus Python and I don't quite know why. If I have the following short C program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    setresuid(999, 999, 999);
    setresgid(999, 999, 999);
    system("/some/program");
    return 0;
}

And the binary has the setuid bit set and the binary is in group 999 and owner 999, running this binary as another user will run /some/program as user 999 which is what you would expect as I believe the idea behind the setuid bit is to allow a program to be run with the group / owner permissions of the file.
On the other hand, if I have the following short Python program:
#!/usr/bin/python
import os
import subprocess

os.setresuid(999,999,999)
subprocess.check_output('/some/program', shell=True)

and the python script has the setuid bit set, is in group 999 and owned by user 999, running the script as another user gives the error:
Traceback (most recent call last):
  File "/foo/bar/sample.py", line 5, in <module>
    os.setresuid(999,999,999)
OSError: [Errno 1] Operation not permitted

Any idea why this might be?

A: Executing an interpreted script is different from executing a compiled binary. In the case of an interpreted script, what is actually being execed is the interpreter, not the script itself. For this reason, setuid on a script does not have any affect. You have to setuid the interpreter, which is python in this case. This is not recommended.


text:
Q: PHP parsing xml file error I am trying to use simpleXML to get data from http://rates.fxcm.com/RatesXML
Using simplexml_load_file() i had errors at times as this website always has weird strings/numbers before and after the xml file.
Example:
2000<?xml version="1.0" encoding="UTF-8"?>
<Rates>
    <Rate Symbol="EURUSD">
    <Bid>1.27595</Bid>
    <Ask>1.2762</Ask>
    <High>1.27748</High>
    <Low>1.27385</Low>
    <Direction>-1</Direction>
    <Last>23:29:11</Last>
</Rate>
</Rates>
0

I then decided to use file_get_contents and parse it as a string with simplexml_load_string(), afterwards which I use substr() to remove the strings before and after. However, sometimes the random strings will appear in between the nodes like this:
<Rate Symbol="EURTRY">
    <Bid>2.29443</Bid>
    <Ask>2.29562</Ask>
    <High>2.29841</High>
    <Low>2.28999</Low>

137b

 <Direction>1</Direction>
    <Last>23:29:11</Last>
</Rate>

My question is, is there anyway i can deal with all these random strings at a go with any regex functions regardless of where they are placed? (think that will be a better idea rather than to contact the site to get them to broadcast proper xml files)

A: I believe preprocessing XML with regular expressions might be just as bad as parsing it.
But here is a preg replace that removes all non-whitespace characters, from the beginning of the string, from the end of the string, and after closing/self-closing tags:
$string = preg_replace( '~
    (?|           # start of alternation where capturing group count starts from
                  # 1 for each alternative
      ^[^<]*      # match non-< characters at the beginning of the string
    |             # OR
      [^>]*$      # match non-> characters at the end of the string
    |             # OR
      (           # start of capturing group $1: closing tag
        </[^>]++> # match a closing tag; note the possessive quantifier (++); it
                  # suppresses backtracking, which is a convenient optimization,
                  # the following bit is mutually exclusive anyway (this will be
                  # used throughout the regex)
        \s++      # and the following whitespace
      )           # end of $1
      [^<\s]*+    # match non-<, non-whitespace characters (the "bad" ones)
      (?:         # start subgroup to repeat for more whitespace/non-whitespace
                  # sequences
        \s++      # match whitespace
        [^<\s]++  # match at least one "bad" character
      )*          # repeat
                  # note that this will kind of pattern keeps all whitespace
                  # before the first and the last "bad" character
    |             # OR
      (           # start of capturing group $1: self-closing tag
        <[^>/]+/> # match a self-closing tag
        \s++      # and the following whitespace
      )
      [^<]*+(?:\s++[^<\s]++)*
                  # same as before
    )             # end of alternation
    ~x',
    '$1',
    $input);

And then we simply write back the closing or self-closing tag if there was one.
One of the reasons this approach is not safe is that closing or self-closing tags might occur inside comments or attribute strings. But I can hardly suggest you use an XML parser instead, since your XML parser can't parse the XML either.


text:
Q: htaccess prevent use of global SSL redirect in chrome I have sites which I'm adding SSL for latest compliance, these have protected admin folders, the global root redirect
    #redirect to ssl site
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

causes visitors using a old http: link to admin to reach 404 page as the redirect happens to early.
Iv'e fixed this for firefox by adding a stop rule prior to the global
# stop processing for admin
RewriteRule ^(admin)($|/) - [L]

and a specific redirect
RewriteCond %{HTTPS} off
RewriteRule ^admin/(.*)$ https://www.mysite.co.uk/admin/$1?%{QUERY_STRING} [NE,r=301,L]

however in chrome the directory stop fails and the specific redirect ignored, so chrome visitors get a 404 instead of being redirected.
I have tried multiple additions to the global but none work
    #redirect to ssl site
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^admin(.*)  [NC]
RewriteCond %{REQUEST_URI} !(.*)admin(.*)  [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/].*)$ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

Why is firefox and chrome behaving differently, I thought it was apache doing the processing, how do I make chrome behave like firefox?

A: I doubt that Firefox behaves differently from Chrome. It is more likely that there is a cached redirect in Chrome which causes it to visit a former redirect target directly without visiting the original URL. This happens if a 301 redirect is used instead of a 302 one since 301 means permanent redirect and the browser will remember this one.
To get rid of this problem you need to clear the browsers cache so that it no longer remembers and uses the no longer valid redirect.

A: Having posted this and despite having searched extensively another post came up and the final answer on that fixed the issue, so the solution has two parts, in the root I added:
RewriteCond %{HTTPS} ^off$ [NC]
RewriteCond %{REQUEST_URI} /admin/*
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [R,L]

Then in the admin folder:
<If "%{HTTPS} == 'on'">
  AuthType       Basic
  AuthName      "Authorization Required"
  AuthUserFile   /var/www/vHost/etc/HTTP-Basic-Auth/htaccess-Users
  require       valid-user
</If>
<Else>
  ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
</Else>

However I still don't understand why chrome is behaving differently to firefox for this.


text:
Q: remove duplicate values for a key in hash I have the following code
chdir("c:/perl/normalized");
$docid=0;
my %hash = ();
@files = <*>;
foreach $file (@files)
  {
    $docid++;
    open (input, $file);
    while (<input>)
      {
    open (output,'>>c:/perl/tokens/total');
    chomp;
    (@words) = split(" ");
    foreach $word (@words)
    {
    push @{ $hash{$word} }, $docid;

    }
      }
   }
foreach $key (sort keys %hash) {
    print output"$key : @{ $hash{$key} }\n";
}

close (input);
close (output);

This is a sample output in a file
of : 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 4 4 4 4 5 6 6 7 7 7 7 7 7 7 7 7

it is true since the term "of" for example existed 10(ten ones) times in the first document
however is there a way to remove the repeated values; i.e instead of ten ones I want just one
Thank you for your help

A: To avoid adding the dups in the first place, change
foreach $word (@words)

to
foreach $word (uniq @words)

If you want to leave the dups in the data structure, instead change
print output"$key : @{ $hash{$key} }\n";

to
print output "$key : ", join(" ", uniq @{ $hash{$key} }), "\n";

uniq is provided by List::MoreUtils.
use List::MoreUtils qw( uniq );

Or you can use
sub uniq { my %seen; grep !$seen{$_}++, @_ }


text:
Q: Validate form through  tag click I am currently working with jquery validation and forms. I came across a great plugin HERE which so far works perfectly. I am running into a wall since I have a form split into sections inside jquery tabs. I have placed in these tabs  tags that act as buttons Next and Previous. Instead of clicking submit to validate, I would like to validate the fields when clicking  Next or Provious.  I have tried binding  to on click validate but I get no result. How can I validate the form by clicking on an  tag? Here is a mockup Example
//jquery tabs- Next and Previous

//Jquery Validation

//Jquery Bind  to validate

HTML

            <form id="formID" class="formular" method="post">
            Name:

            <input value="" class="validate[required] text-input" type="text" name="req" id="req" />

                Favorite sport 2:
                <select name="sport2" id="sport2" multiple class="validate[required]">
                    <option value="">Choose a sport</option>
                    <option value="option1">Tennis</option>
                    <option value="option2">Football</option>
                    <option value="option3">Golf</option>
                </select>

            </form>

A: You're dynamically adding  tags so you'll need to use live() on() (live is deprecated, thanks jbabey), as opposed to bind.
That way, any matching elements now or added in future will be properly bound.

A: As .live() is deprecated, you should use .on() as follows:
$(document).on("click", ".next-tab, .prev-tab", function(() {
           $tabs.tabs('select', $(this).attr("rel"));
           return false;
       });


text:
Q: Retrofit 2 Raw JSON request using RequestBody I use Retrofit 2 library, and I need to send POST JSON request like this:
{
   "datetime": 0,
   "body": {
       "gymId": "17C1B14C-C21F-41EE-BF75-F0E7843DB638",
       "customerName": "test",
       "customerEmail": "test@test.ru",
       "content": "test"
   }
}

How i can send this request use RequestBody?
 Call<ApiClubRequest> clubContact(@Body RequestBody requestBody);

Or can easily make such a request?
This is my interface class with OkHttp settings.
public class RestClient {

private static ClassApiInterface WordClassApiInterface ;
private static String baseUrl = "http://my adddress" ;

public static WorldClassApiInterface getClient() {
    if (WordClassApiInterface == null) {
        OkHttpClient okClient = new OkHttpClient();
        okClient.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                return response;
            }
        });

        Retrofit client = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiInterface = client.create(ApiInterface.class);

    }
    return ClassApiInterface ;
}

public static  Call<ApiClubRequest> clubcontact(String gymId, String customerName, String
        customerEmail, String content){
    ClubContactRequest request = new ClubContactRequest();
    request.gymId = gymId;
    request.customerName = customerName;
    request.customerEmail = customerEmail;
    request.content = content;
    return ApiInterface.clubContact(request);
}

  @Headers("Content-Type: application/json")
    @POST("/hotline")
    Call<ApiClubRequest> clubContact(@Body ClubContactRequest requestBody);

}
}

A: Create a request class and create fields with the same name as in the JSON:
public class ClubContactRequest {

    public String gymId;
    public String customerName;
    public String customerEmail;
    public String content;
}

Modify the POST @Body:
Call<ApiClubRequest> clubContact(@Body ClubContactRequest requestBody);

Then implement the request:
public Call<ApiClubRequest> clubcontact(String gymId, String customerName, String customerEmail, String content){
    ClubContactRequest request = new ClubContactRequest();
    request.gymId = gymId;
    request.customerName = customerName;
    request.customerEmail = customerEmail;
    request.content = content;
    return yourApiInterface.clubContact(request);
}


text:
Q: I got a missing value error on if condition     realfunction1<-function(x){
  (5*x[1]-x[2])^4+(x[1]-2)^2+x[1]-(2*x[2])+12
}
func1gradient <- function(gradient){
  x<-0
  y<-0
  x <- (20*(5*gradient[1]-gradient[2]))^3+2*(gradient[1]-2)+1
  y <- (-4*(5*gradient[1]-gradient[2]))-2

  gradient[1]<-x
  gradient[2]<-y
  return(gradient)
}

DFP<-function(Error,xk){

  k <- 0
  i <- 1
  alpha<-seq(from=-100,to=100,by=0.005)
  H0 <- matrix(c(1,0,0,1), nrow=2, byrow=TRUE)
  Hk <- H0
  repeat{

    dk <- (-1)*(Hk%*%func1gradient(xk))

    if(abs(dk[1]) <= Error && abs(dk[2]) <= Error){ ####ERROR LINE

      return(xk)

    }else{

      for(i in i:40001){

        vectortofindmin<-matrix(c(1:40001),nrow=40001)

        variables <- xk+(alpha[i]*dk)

        f1valuetutucu<-matrix(c(1:40001),nrow=40001)

        f1valuetutucu[i] <- realfunction1(variables)
      }

      indexalpha<-which.min(f1valuetutucu)

      xknew <- xk + (alpha[indexalpha]*dk)

      pk <- xknew - xk

      qk <- func1gradient(xknew) - func1gradient(xk)

      ## A
      divisionval<-(t(pk)%*%qk)
      divisionmatix<-matrix(c(divisionval,divisionval,divisionval,divisionval),nrow=2)

      A <- (pk%*%t(pk))/divisionmatrix

      ###

      divisionval2<-t(qk)%*%Hk%*%qk
      divisionmatrix2 <- matrix(c(divisionval2,divisionval2,divisionval2,divisionval2),nrow=2)
      B <- (Hk%*%qk)%*%t(Hk%*%qk)/divisionmatrix2
      ####
      Hknew <- Hk + A + B
      Hk <- Hknew
      xk<-xknew
    }
  }
}
DFP(Error=1e3,xk=matrix(c(33,12),nrow=2))

Here is my whole code, I tried every line of my code and it's working appropriately but I got an error on if line "missing value where TRUE/FALSE needed"  " if(abs(dk[1]) <= Error && abs(dk[2]) <= Error)". Can anyone help, why I got this error message? (I write Error=1e3 but I will reduce that error amount later, I am trying to reach working function:))
This code is representing the davidon-fletcher-powell method algorithm. If you have any addition or advice. I will be very appreciated.

A: I did two things:

*

*Fixed the typo that @Jan pointed out; and

*Inserted a quick tryCatch(...) and browser() into the repeat loop.
iserr <-  tryCatch({if (abs(dk[1]) <= Error && abs(dk[2]) <= Error) 1;F;}, error=function(e) TRUE)
if (iserr) {browser();1;}

(before the real if statement)
After that, I ran your DFP(...) and it popped up with a debugging session. I then broke apart the if conditional:
(abs(dk[1]) <= Error && abs(dk[2]) <= Error)
# [1] NA

This up-front is why you received that error. (And if you search SO with your error message [r] missing value where TRUE/FALSE needed, you'll see that your exact error is discussed in many questions.)
But you need to know why that conditional is not a real true/false, so we can look at some of the dependent variables. All of the following would alarm me in one form or another (though perhaps xk is okay?):
dk
#      [,1]
# [1,]  NaN
# [2,]  NaN
xk
#               [,1]
# [1,]  4.16513e+145
# [2,] -5.07341e+115
func1gradient(xk)
#                [,1]
# [1,]            Inf
# [2,] -8.330259e+146
Hk
#      [,1] [,2]
# [1,]  NaN  NaN
# [2,]  NaN  NaN

I'm not going to disect why each of those allegedly numeric variables are holding unexpected values, as that would require a bit of domain-knowledge on whatever you're doing here. It might be that you find the Inf not completely unexpected, but I expect that the NaN is surprising to you.
Go through your logic and code to find what is going wrong with each of those.
When playing with new math in functions, I often include some if statements that either stop prematurely or put me into a browser() debugging session. For instance,
if (any(is.null(z), is.nan(z), is.na(z))) { browser(); 1; }

might be a good thing for you to check on various components before you do things that can turn zeroes, very-positive, very low, or very-negative numbers into non-numbers. (The browser();1; is a little bit of a hack to work around some nuances of debugging in R.)
A slightly different tact might be something like:
if (!isTRUE(is.finite(z))) { browser(); 1; }

which should start a debugging session a little more aggressively.
You should target avoiding this type of code (e.g., browser()) in production, but while developing new R-based stuff and/or learning the nuances of R, it can save you many hours.


text:
Q: Upload Video and Thumbnail in Laravel 5.1 I'm totally a newbie in Laravel development. I have a few text files along with 1 video upload and thumbnail upload feature. I can save all the data into the DB, but I am stuck with video and thumbnail/image upload.
Controller
<?php

public function save(Request $request)
{
    // Any other fields to be saved here..
    $post = $request->all();
    $v = \Validator::make($request->all(),
        [
            'title' => 'required',
            'category' => 'required',
            'description' => 'required',
            'price' => 'required|Numeric',
            'discount' => 'Numeric',
            'thumbnail' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]
    );

    $file = Input::file('thumbnail');
    $destinationPath = 'images/';
    $filename = $file->getClientOriginalName();
    Input::file('thumbnail')->move($destinationPath, $filename);

    if ($v->fails()) {
        return redirect()->back()->withErrors($v->errors());
    } else {
        $data = array(
            'title' => $post['title'],
            'category' => $post['category'],
            'partner' => $post['partner'],
            'description' => $post['description'],
            'published' => $post['published'],
            'featured' => $post['featured'],
            'price' => $post['price'],
            'discount' => $post['discount'],
            'file' => "file",
            'thumbnail' => $filename
        );

        $i = DB::table('items')->insert($data);
        if ($i > 0) {
            \Session::flash('message', 'new Item Saved');
            return redirect('itemindex');
        }
    }
}

I added some code to test uploading images as a thumbnail but it failed.
View

A: First you need to upload files(video/poster) then you save the uploaded path into your database.
Laravels official documentation on file upload
    $uniqueName = (integer)microtime(); // For unique naming vaideo/poster
    $videoSrc = "";
    $thumbnailSrc = "";

    $file = $request->file('file');
    // Upload video
    $destinationPath = 'uploads/videos';
    $fileName = $uniqueName.'.'.$file->getClientOriginalExtension();
    $uploadSuccess = $file->move($destinationPath, $fileName);
    $videoSrc = '/'.$destinationPath.'/'.$fileName;

    $poster = $request->file('thumbnail');
    // Upload poster
    $destinationPath = 'uploads/posters';
    $fileName = "poster".$uniqueName.'.'.$poster-        >getClientOriginalExtension();
    $uploadSuccess = $poster->move($destinationPath, $fileName);
    $thumbnailSrc = '/'.$destinationPath.'/'.$fileName;

    $data = array(
        'title' => $post['title'],
        'category' => $post['category'],
        'partner' => $post['partner'],
        'description' => $post['description'],
        'published' => $post['published'],
        'featured' => $post['featured'],
        'price' => $post['price'],
        'discount' => $post['discount'],
        'file' => $videoSrc,
        'file' => "file",
        'thumbnail' => $thumbnailSrc,
       'thumbnail' => "thumbnail",
    );
    $i=DB::table('items')->insert($data);
    if($i>0)
    {
        \Session::flash('message','new Item Saved');
        return redirect('itemindex');
    }

(This code is for your else statement)


text:
Q: State-transition matrix I am studying the observability properties of a dynamical system and I get to the next equations:
$$x(t) \in \mathbb{R}^{n}$$
$$A(t) \in \mathbb{R}^{n\times n}$$
$$\Phi(t,t_{0}) \in \mathbb{R}^{n\times n}$$
$$$$
$$\dot{x}(t) = A(t)x(t) \hspace{1cm} x(t=0) = x_{0}$$
$$\frac{d\Phi(t,t_{0})}{dt} = A(t)\Phi(t,t_{0}) \hspace{1cm} \Phi(t=0) = I$$
What are the mathematical derivation to get to the point:
$$x(t) = \Phi(t,t_{0}) x_{0}$$
being $\Phi(t,\tau)$ the Peano–Baker series:
$$\mathbf{\Phi}(t,\tau) = \mathbf{I} + \int_\tau^t\mathbf{A}(\sigma_1)\,d\sigma_1 + \int_\tau^t\mathbf{A}(\sigma_1)\int_\tau^{\sigma_1}\mathbf{A}(\sigma_2)\,d\sigma_2\,d\sigma_1 + \int_\tau^t\mathbf{A}(\sigma_1)\int_\tau^{\sigma_1}\mathbf{A}(\sigma_2)\int_\tau^{\sigma_2}\mathbf{A}(\sigma_3)\,d\sigma_3\,d\sigma_2\,d\sigma_1 + ...$$
Here it is the proof that this solution is correct.
If we derive the equation proposed as the solution we get:
$$\dot{x}(t) = \frac{d\Phi(t,t_{0})}{dt} x_{0} = A(t)\Phi(t,t_{0}) x_{0} = A(t)x(t)$$
so the solution proposed $x$ is correct.
But my initial doubt still remains open. How can I mathematically get to the solution from the 2 equations?
The solution can be found in Linear System Theory, Wilson J. Rugh (Second Edition 1996) in Chapter 3.

A: $\Phi(t, t_0)$ is the matrix made by assembling columns out of the $x(t)$  with initial conditions at $t_0$. The first column has initial data
$x(t_0)=(1,0,0,\ldots,0)^T$; the second column is $x(t)$ with initial data $x(t_0)=(0,1,0,\ldots 0)^T$; and so on. Then, by the linearity of the equations of motion
$$
x(t)= \Phi(t, t_0) x(t_0)
$$
is the solution for general initial data.


text:
Q: Batch Job exit status using Spring Cloud Task I'm trying to setup a spring batch project to be deployed on Spring Cloud Data Flow server, but first I must "wrapp" it on a Spring Cloud Task application.
Spring Batch generates metadata (start/end, status, parameters, etc) on BATCH_ tables. Cloud Task do the same but on TASK_ tables.
Reading the documentation of Spring Cloud Task, it said that in order to pass the batch information to the task, it must be set
spring.cloud.task.batch.failOnJobFailure=true and also

To have your task return the exit code based on the result of the
  batch job execution, you will need to write your own
  CommandLineRunner.

So, any indications on how I should write my own CommandLineRunner ?
For now, only having set the propertie, if I force the task to fail, I'm getting Failed to execute CommandLineRunner .... Job UsersJob failed during execution for jobId 3 with jobExecutionId of 6


text:
Q: How does Stack Overflow make it so their apple-touch-icon doesn't have a border effect After going through the page source, I found:
<link rel="apple-touch-icon image_src" href="//cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png?v=41f6e13ade69">

But even after I did that, my image still has a bored effect. My image is also a transparent png. Any ideas?

Here is my attempt (10.10.1 OS X Yosemite, Safari: Version 8.0.2):

I used this website to generate the favico:
http://realfavicongenerator.net
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">

A: Two things in this answer:

*

*How I did to reproduce StackOverflow's behavior

*Why this may not be a good idea

How to reproduce StackOverflow's behavior
What I did:

*

*Download http:////cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png

*Submit this picture to RealFaviconGenerator (full disclosure: I'm the author of this site)

*Put the generated pics and HTML in a test web site

*Access it with Safari and add a bookmark

I got your expected result, ie. a transparent background.

This is basically what you did, so there must be something wrong. A few tips:

*

*There can be a lot of issues with favicon, whatever the browser. They often cache the old icon and do not load the new one. Sometimes they do not load your icon at all, but load it if you wait a few seconds. And so on. My advice: try to use another domain to make sure you start from a fresh state.

*Maybe your test web site as some additional stuff that can conflict with your actual test. For example, if you have a file apple-touch-icon.png in your root directory, Safari may load it, even if it is not declared in your HTML code.

Why this may not be a good idea
Mac OS Safari relies on the Touch icon, primarily designed for iOS. It is mainly used for the "Add to home screen" feature. In that case, iOS prevents transparency and fills transparent regions with black. Add StackOverflow.com to the home screen and you get:

Honestly the result is okay, but is this really what SO expected? Your choice.

A: I figured out the problem here.
The farthest one on the right has a TLD of .io
The center one has a TLD of .com
They are exact clones, the same code on. So it must be because the domain TLD is not .com/.net

Edit:
To further recap information I found about this. It seems like adding a www in front of my domain, allows it to be fully transparent.

*

*mysite.com works

*www.mysite.com works

*mysite.io doesn't work

*www.mysite.io works

A: Transparent Apple Touch icons are indeed possible. What you need to do is strip all excess information from the PNG using ImageOptim for Mac or a similar program on Windows. I did extensive research and stumbled on the answer by looking at the Apple Touch icon used by the Virtual DJ site. This icon keeps its transparent background on iOS and MacOS Sierra. I looked at the file size and realized how small it was compared to the custom apple touch icons with transparency that I made for my favorites in Safari. Next I looked at the file information using the inspector in Mac's Preview app. All of my custom apple touch icons had four tabs in the inspector section named General, exif, PNG and TIFF. The virtual DJ icon only had two tabs named PNG and General. Once I ran my custom images through ImageOptim the file sizes plummeted by over 90% and the extra TIFF and exif tabs disappeared from the inspector in Preview. Sure enough once I reloaded my custom images and launched Safari all of my Favorites tabs have transparent backgrounds!


text:
Q: How do modern OS's achieve idempotent cleanup functions for process deaths? Let's say that I have an OS that implements malloc by storing a list of segments that the process points to in a process control block. I grab my memory from a free list and give it to the process.
If that process dies, I simply remove the reference to the segment from the process control block, and move the segment back to my free list.
Is it possible to create an idempotent function that does this process cleanup? How is it possible to create a function such that it can be called again, regardless of whether it was called many times before or if previous calls died in the middle of executing the cleanup function? It seems to me that you can't execute two move commands atomically.
How do modern OS's implement the magic involved in culling memory from processes that randomly die? How do they implement it so that it's okay for even the process performing the cull to randomly die, or is this a false assumption that I made?

A: I'll assume your question boils down to how the OS culls a process's memory if that process crashes.
Although I'm self educated in these matters, I'll give you two ways an OS can make sure any memory used by a process is reclaimed if the process crashes.
In a typical modern CPU and modern OS with virtual memory:
You have two layers of allocation. Whenever the process calls malloc, malloc tries to satisfy the request from already available memory pages the kernel gave the process. If not enough pages are available, malloc asks the kernel to allocate more pages.
In this case, whenever a process crashes or even if it exits normally, the kernel doesn't care what malloc did, or what memory the process forgot to release. It only needs to free all the pages it gave the process.
In a simpler OS that doesn't care much about performance, memory fragmentation or virtual memory and maybe not even about memory protection:
Malloc/free is implemented completely on the kernel side (e.g: system calls). Whenever a process calls malloc/free, the kernel does all the work, and therefore knows about all the memory that needs to be freed. Once the process crashes or exits, the kernel can cleanup. Since the kernel is never supposed to crash, and keep a record of all the allocated memory per process, it's trivial.
Like I said, I'm self educated, and I didn't check how for example Linux or Windows implement it.


text:
Q: Button/DIV toggle I have a button, the label of which I want to change back and forth as it is clicked. I found this thread
How do you create a toggle button?
and this example
http://jsfiddle.net/LmULE/
which is great but I'm trying to figure out how to actually change the label (say, from "up"  to "down" when it is clicked).
Would appreciate any help.

A: I have chaned the fiddle
Updated Fiddle

A: You can check the class by using .hasClass();
if ($(this).hasClass("down"))
{
    $(this).html("Down!");
}
else
{
    $(this).html("Up!");
}

In your code:
http://jsfiddle.net/Before/XNQce/2/

A: That's simple.
$(document).ready(function(){
var i=0;
$('a#button').click(function(){
    $(this).toggleClass("down");
    if(i%2==0)$(this).html('divide by 2');
    else $(this).html('not divide by 2');
    i++;
});
});

using a variable you can check what state is your button in. Above code is just a crude of that type of state management.
check this http://jsfiddle.net/LmULE/100/


text:
Q: Is it correct to say "Cut the onion in two then place down the cut-side of the onion on the cutting board"?
I have an onion. I cut it in two.
As shown in the picture, you can see the flesh of the onion when you look at "the cut-side of the onion".
I want to keep the "the cut-side of the onion" in contact with the surface of the cutting board.
Is it correct to say "Cut the onion in two then place down the cut-side of the onion on the cutting board"?

A: While "put down" and "lay down" are common prepositional phrases, they don't have anything to do with the position of an object after it has been placed.
To be absolutely clear, you can say: "Put the onion's sliced surface in contact with the cutting board."
The standard, brief way to phrase that is: "Put the onion cut side down on the cutting board." One could argue that "down" is redundant.
Brief and precise: "Put the cut side against the cutting board."


text:
Q: Django path() throws 404 when URL ends in Slash Here is urls.py
path('about/', about, name='about'),

If I visit /about it gives 404 error, if if change it to path('about', about, name='about'), then if I visit /about works but /about/ gives 404 errors.
What am I doing wrong here, this wasn't not happening prior to Django 2.0

A: I would comment but I don't have enough reputation to do so yet. Anyways, the following might help:
Did you import your views? Because you're referencing the path() wrong. It should be like:
from . import views

urlpatterns = [

    path('about/', views.about, name='about'),

]


text:
Q: Keep an object state in different runs In this and this posts I describe the framework that I want to develop.
I want to implement a memoization strategy to speeedup some functions execution.
An important feature of this framework should be to "remember" the computed values of past runs: let's suppose we write a program where we execute a word count function f with the big text t as input. After we have computed r=f(t) (where r is the result), we follow the memoization logic, so we store (t,r) somewhere, let's say an unordered_map object um. After this, the program terminates.
At the next execution of the same program, the expensive execution of fisn't necessary, since um contains already (t,r), so the value r is returned.
The problem in all of this is how to "remember" um state in different executions.
IMPORTANT:
Obviously this is an example to make you understand a possible application of this framework, but any memoization application must work as well.
Write a c++ object to file is the only solution for this problem/scenario, or there is an other one?

A: The data must be stored somewhere outside the process in order to keep it after the process terminates. The file system is an obvious place to store the data, but it can also be stored by another process, such as a database management system, or an external cache (ex. https://memcached.org/).
Most backend options store the data as a character stream. You will need to understand how to (de)serialize the data.

A: Side-note: Can you keep the program running? Then you dont need to store the memos on disk.
Regardless of where you store the memos:
If this is really for word-count then forget memoization: You would need to read the whole text to find out if it is identical to a previous text. And then you could just count the words on the fly anyway.
If instead of word-count, that was just an example for some much more complicated computation: Instead of storing text -> computed-value memos you can store hash -> computed-value memos. You choose a hash depending on your situation: If you need to be somewhat sure that it is the same text, then use e.g. sha-1. If you need a really cheap 'hash' (e.g. when the stored computed-value serves only as an initial guess which will be improved upon anyway) then you could just use the number of bytes in the text-string as 'hash'.


text:
Q: Detect correct iPad orinatation I have to detect the orientation of the device and so something configuration based on it.
I write a simple function to handle it
public func isLandscape() -> Bool {
    return UIScreen.main.bounds.width > UIScreen.main.bounds.height
}

It works perfectly on iPhone, but on iPad it's not. Sometimes when iPad is on landscape, it shows that it's UIScreen.main.bounds.height is larger than UIScreen.main.bounds.width, which is super weird.
So for iPad, I change to it like that
public func isLandscape() -> Bool {
    if DeviceType.isPhone {
        return UIScreen.main.bounds.width > UIScreen.main.bounds.height
    } else {
        return UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight || UIDevice.current.orientation == .unknown
    }
}

But still not working probably on iPad. The case of unknown is called sometimes on portrait and sometimes on landscape.
Is there any other way, that could works flawlessly? I really need to have a prefect way to always show the the iPad and iPhone that they are in portrait and landscape? Those unknown, faceDown and faceUp are really confusing and make problems in our workflow.
Your help will be appreciated

A: if(UIApplication.shared.statusBarOrientation.isLandscape)
{
     print("[UI] Landscape")
}
else
{
     print("[UI] Portriat")
}

You will receive a warning saying that .statusBarOrientataion is deprecated, but I tested with Xcode 14 on an iPad Air 4th generation (iPadOS 15.7), and iPhone 12 (iOS 16), and it worked.


text:
Q: Sound not working when mounting on /home I have a Debian/Windows 10 dual boot system with a shared Data partition that I mount on /home. The problem is: if I mount anything on /home or on /home/$USERNAME, sound does not work anymore. (See below for how it does not work)
I tried the following things:

*

*When I mount /dev/sda5 ($DATA) on /home, sound breaks.

*When I mount $DATA on /media/$USERNAME/$DATA and then bind it to /home, it breaks.

*When I mount data as before and bind the $USERNAME subfolder only, still no sound

*When I bind a random folder on /home or /home/$USERNAME, silence.

*When I mount $DATA as before and then bind all the subfolders (Documents & co.) individually into /home/$USERNAME, everything works fine.

*I also added a new user and did the same there, the issue applies there too.

*I tried reproducing the issue on a Ubuntu USB stick, but I couldn't log in anymore because I messed up the permissions (everything was root and read-only).

*Same for mounting a smaller FAT32 partition on my drive instead of the NTFS DATA partition.

*Before Debian I had KUbuntu installed the same way and I don't remember sound ever worked.

I'm using that single working option as a workaround for now, but I'd like to know the root cause and to fix it. The content of the /home folder has no effect on the issue (I previously thought it was tied to some wrong config files). Can anyone reproduce the issue?
Original problem
When I have something mounted, the system does not recognize any sound cards, even if most of the commands (aplay -l and such) do, as before.
I tried getting rid of all old config files I could find, no result. I tried completely purging everything sound-related to re-install it (and almost uninstalled my whole system), but that didn't work either.
(Kind of) fun fact: on the login screen everything still works fine. Audacity  works out of the box too, but nothing else I tested (YouTube, Music, Factorio). On windows and Ubuntu live sound works perfectly fine too, so that's not the problem.
Some outputs:
$aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: Generic [HD-Audio Generic], device 3: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: Generic_1 [HD-Audio Generic], device 0: CX20585 Analog [CX20585 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

$aplay -L
null
    Discard all samples (playback) or generate zero samples (capture)
hdmi:CARD=Generic,DEV=0
    HD-Audio Generic, HDMI 0
    HDMI Audio Output
dmix:CARD=Generic,DEV=3
    HD-Audio Generic, HDMI 0
    Direct sample mixing device
dsnoop:CARD=Generic,DEV=3
    HD-Audio Generic, HDMI 0
    Direct sample snooping device
hw:CARD=Generic,DEV=3
    HD-Audio Generic, HDMI 0
    Direct hardware device without any conversions
plughw:CARD=Generic,DEV=3
    HD-Audio Generic, HDMI 0
    Hardware device with all software conversions
default:CARD=Generic_1
    HD-Audio Generic, CX20585 Analog
    Default Audio Device
sysdefault:CARD=Generic_1
    HD-Audio Generic, CX20585 Analog
    Default Audio Device
front:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    Front speakers
surround21:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    2.1 Surround output to Front and Subwoofer speakers
surround40:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    4.0 Surround output to Front and Rear speakers
surround41:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    4.1 Surround output to Front, Rear and Subwoofer speakers
surround50:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    5.0 Surround output to Front, Center and Rear speakers
surround51:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    5.1 Surround output to Front, Center, Rear and Subwoofer speakers
surround71:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    7.1 Surround output to Front, Center, Side, Rear and Woofer speakers
dmix:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    Direct sample mixing device
dsnoop:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    Direct sample snooping device
hw:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    Direct hardware device without any conversions
plughw:CARD=Generic_1,DEV=0
    HD-Audio Generic, CX20585 Analog
    Hardware device with all software conversions

$speaker-test
Playback device is default
Stream parameters are 48000Hz, S16_LE, 1 channels
Using 16 octaves of pink noise
ALSA lib pcm_dmix.c:1052:(snd_pcm_dmix_open) unable to open slave
Playback open error: -2,No such file or directory

$(ps axu | grep pulse)
Debian-+   692  0.0  0.1 889324 11152 ?        Ssl  12:47   0:00 /usr/bin/pulseaudio --daemonize=no
piegames  3742  0.0  0.0  12784   960 pts/0    S+   13:31   0:00 grep pulse

$aplay somefile.wav
ALSA lib pcm_dmix.c:1052:(snd_pcm_dmix_open) unable to open slave
aplay: main:788: audio open error: No such file or directory

$paplay somefile.wav
Connection failure: Connection refused
pa_context_connect() failed: Connection refused

pavucontrol says the connection to PulseAudio failed and suggests manually starting it. start-pulseaudio-x11 returns the same as paplay
Alsamixer works fine except that the default device has no useful settings, but switching the device outputs what it should.
The system settings just tell that the didn't find any devices; all options are grayed out.

A: Diagnosis:
You are running a Pulseaudio server under a different useraccount (Debian-+, likely truncated) than your main useraccount (piegames). Pulseaudio is meant to be run as the same user as the one that produces the sound. So on startup, the Pulseaudio server grabs all ALSA hw devices, and those devices are only meant to be open by one process, which is why you can't get sound via ALSA when you run aplay etc. On the other hand, Pulseaudio refuses connections from a different user, which is why you can't get sound via Pulseaudio.
Options:
One could try disabling Pulseaudio completely, but as you seem to want to use Gnome, that might cause consiberable headache.
The other option is to fix your desktop login process, and make sure Pulseaudio is started as the same user as the user that is logged in. I'm not familiar enough with the Debian/Gnome login process to give a step-by-step description. Look at your display manager (gdm?), the login process, and the configuration files involved, find out where it starts Pulseaudio, and fix what needs fixing. Very likely there are some configuration files in /home that screw things up, but it's impossible to guess which ones.
To make sure legacy ALSA applications work with Pulseaudio, you need
pcm.!default pulse
ctl.!default pulse

either in ~/.asoundrc or /etc/asound.conf, so sound gets routed to Pulseaudio via a compatibility layer. This should have been setup by the distro, I don't know what went wrong in your case.
As you will need to dig quite a bit into the bowels of the system, you'll have to know the difference between Pulseaudio and ALSA, and much more, so start reading up ...
Installing different distros over already existing home directories sometimes just doesn't work well.
Alternatively, do a complete Debian install from scratch, including making a new user with home directoy and everything, and copy over your old data only. That means copying configuration files only if you know what they are for.
All options are a bit annoying, but I guess it can't be helped ...


text:
Q: mongoose fulltext search not working i have a problem with index in mongoose
My model

var mongoose = require("mongoose");

var Schema = mongoose.Schema;

var commentSchema = new Schema({

    customer_id: String,
    motel_id: String,
    customer_name: String,
    content: String,
    created_at: Date

});
commentSchema.set('autoIndex', false);
commentSchema.index(
    {'$**': 'text'}
)

var comments  = mongoose.model("comments", commentSchema);

and my search function

function testIndex(req, res) {
    var searchString = "h";
    comment.find({$text: {$search: searchString}})
    .skip(20)
    .limit(10)
    .exec(function(err, docs) { res.send("docs:" + docs); });
}

but it don't return any value. How can i fix this problem?

A: Please refer this link
  [1]: Best way to perform a full text search in MongoDB and Mongooseenter code hereh-in-mongodb-and-mongoose


text:
Q: How can I listen to xhr response using chrome-extension? I want execute a function when some a chrome window gets a XHR response.
I don't know what exactly this request is like, because of a codified param of this request, for example: api.xxx.com/rest?random=123
So I don't think I could use
chrome.devtools.network.onRequestFinished.addListener(function callback)

or
chrome.webRequest.onCompleted.addListener(function callback)

which both need specify the request details.

A: The listeners for those events do not need you to specify the request details. On the contrary, they provide you with those details, when the get called.
Since you want to listen for any XHR request, you can define the special <all_urls> match pattern (or *://*/* to limit them to just http/https requests).
E.g.:
chrome.webRequest.onCompleted.addListener(function (details) {
  // Process the XHR response metadata. The request body is not available
  ...
}, {urls: ['<all_urls>']});

Don't forget to declare the appropriate permissions, according to your requirements.
E.g.:
// In `manifest.json`:
...
"permissions": {
  ...
  "webRequest",
  "<all_urls>"   // <-- add this to listen for XHR from all pages
]


text:
Q: UIView `readableContentGuide` in Interface Builder? The iOS 9 readableContentGuide is a UILayoutGuide (essentially, a thing you can pin constraints to) that all UIViews have. The idea is to keep subviews with text from being too wide on iPad in landscape.
It's easy to configure this in code (v1 is the subview, v is its superview):
NSLayoutConstraint.activateConstraints([
    v1.topAnchor.constraintEqualToAnchor(v.readableContentGuide.topAnchor),
    v1.bottomAnchor.constraintEqualToAnchor(v.readableContentGuide.bottomAnchor),
    v1.rightAnchor.constraintEqualToAnchor(v.readableContentGuide.rightAnchor),
    v1.leftAnchor.constraintEqualToAnchor(v.readableContentGuide.leftAnchor)
])

Now then. So far so good. However... In two different WWDC videos, it is claimed quite explicitly that you can configure pinning a subview to its superview's readableContentGuide in Interface Builder.
But they don't explain how you do that.
So my question is: How do you do it?

A: Pin the subview's edges to the superview's margins as usual.
Now, in the superview's Size inspector, check the Follow Readable Width checkbox:


text:
Q: Open an external URL from a struts sub-menu in menu-config.xml I am trying to open an external link from my menu-config.xml submenu..Is this possible to do ?
It is not working for me
<Menu name="MainMenu" title="MainMenu" description="MainMenu">

  <Item name="Google" title="Google" description="Google" link="http://www.google.com" ></Item>
  <Item name="Google" title="Google" description="Google" link="http://www.google.com" ></Item>

</Menu>

I tried using location and like this
menu name="google" link="javascript:window.open('http://www.google.com/');"
Thanks


text:
Q: Add Indent Lines similar to those in Sublime How do I add indent lines to my vscode? editor.renderIndentGuides: true doesn't work properly - at least on Mac. I think it used to be okay until some of the recent updates...
Here is an example image from Sublime. All indent lines are there and are displayed properly:
SUBLIME Proper version of Indent lines
and here a buggy version from vscode.
VSCODE Buggy and broken indent lines


text:
Q: list with deleted items does not bind correctly I have a view in which the user can edit all fields for a list of items and two buttons "Add" and "Delete" which should add a new item or delete all selected items, respectively.
Although the add functionality works properly, the delete option removes the correct number of items, but removes items from the end of the list regardless of which were selected.
Strangely, the correct items seem to be deleted in the controller and passed to the view, but the view renders with the last few items deleted instead of the selected ones. Here is the code:
Model:
public class TestClass
{
    public bool IsSelected { get; set; }
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

View:
@model List<TestMvcApp.Models.TestClass>

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    @using (Html.BeginForm()) {

            @Html.DisplayNameFor(model => model[0].IsSelected)

                @Html.DisplayNameFor(model => model[0].Prop1)

                @Html.DisplayNameFor(model => model[0].Prop2)

                @Html.DisplayNameFor(model => model[0].Prop3)

        @for (int i = 0; i < Model.Count(); ++i )
        {

                    @Html.EditorFor(model => model[i].IsSelected)

                    @Html.EditorFor(model => model[i].Prop1)

                    @Html.EditorFor(model => model[i].Prop2)

                    @Html.EditorFor(model => model[i].Prop3)

        }

    <input type="submit" name="buttonPressed" value="Add" />
    <input type="submit" name="buttonPressed" value="Remove" />
}

Controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        List<TestClass> testList = new List<TestClass>();
        testList.Add(new TestClass());
        return View(testList);
    }

    [HttpPost]
    public ActionResult Index(List<TestClass> list, string buttonPressed)
    {
        switch (buttonPressed)
        {
            case "Add":
                return Add(list);
            case "Remove":
                return Remove(list);
            default:
                return View(list);
        }
    }

    public ActionResult Add(List<TestClass> list)
    {
        list.Add(new TestClass());
        return View("Index", list);
    }

    public ActionResult Remove(List<TestClass> list)
    {
        for( int i = list.Count() - 1 ; i >= 0 ; --i)
        {
            if (list[i].IsSelected)
                list.RemoveAt(i);
        }
        if (list.Count <= 0)
            list.Add(new TestClass());
        return View("Index", list);
    }
}

When I break at the return statement, the list contains the correct items, but the view contains only the first items (e.g. if the list has 5 items and I remove items 2 and 3, the controller will show a list with items 1,4,5 but the view will render a list with items 1,2,3).
Any ideas why this does not work as expected?

A: I think ModelState is causing you these headaches. Try adding ModelState.Clear() in your post action before you return your View.


text:
Q: mosquitto cloudmqtt bridging I want to bridge local mosquitto broker and remote cloudmqtt broker. I want to make a bridge that connects two brokers so all the messages on all topics that are subscribed or published to one broker are visible to another broker, so both brokers can subscribe and publish on the same topics so I configured mosquitto.conf file like this:
#Place your local configuration in /etc/mosquitto/conf.d/
#
#A full description of the configuration file is at
#/usr/share/doc/mosquitto/examples/mosquitto.conf.example

connection cloudmqtt
address mnumber.cloudmqtt.com:port
topic # both 0
notifications false
start_type automatic
remote_usename username_of_the_user_on_cloudmqtt
remote_password password_of the_user_on_cloudmqtt

pid_file /var/run/mosquitto.pid

persistance true
persistance_location /var/lib/mosquitto/

When I use mosquitto_sub and mosquitto_pub in the terminal, local broker works fine but the messages are not coming to the cloudmqtt.com broker. And when I use these commands in terminal:
mosquitto_sub -h mnumber.cloudmqtt.com -p port -u remote_username -P remote_password -t topic
mosquitto_pub -h mnumber.cloudmqtt.com -p port -u remote_username -P remote_password -t topic -m message

messages are coming to cloudmqtt, but nothing comes to terminal in which I wrote mosquitto_sub - topic. So I can say that both brokers are working fine but there is no bridge between them, what may be wrong with this?
EDIT: after sudo /etc/init.d/mosquitto stop I get:

[ ok ] Stopping network daemon:: mosquitto

mosquitto is now stopped and when I try use local client I get:

Error: Connection refused

and then after starting mosquitto with mosquitto I get this log, in which I have this

Warning:Address family not supported by the protocol

is that problem that doesn't allow bridging?
@hardillb What do you mean by distro?
EDIT 2:
I've looked into log file (destination /var/log/mosquitto/mosquitto.log) and I've seen that there is a line that says:
mosquitto version 1.3.5 (build date 2014-10-18 21:06:44+0100) start$
Config loaded from /etc/mosquitto/mosquitto.conf.
.
.
.
Socket error on client mosqsub/3739-raspberryp, disconnecting.
.
.
.

and when I try mosquitto --version in terminal I get:

unknown option mosquitto --version mosquitto version 1.4.5 (build date
  Sun, 08 Nov 2015 21:43:12 +0000)

So i tried sudo apt-get install mosquitto and I got:

Reading package lists... Done Building dependecy tree Reading state
  information... Done mosquitto is already the newest version.
  0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded 0

How it is possible to have two versions of mosquitto (1.3.5 in log file and 1.4.5 when I try mosquitto --version) and when I try to upgrade I can't, could some of this cause the problem?
EDIT3: have installed raspibian jessie and mosquitto, but the problem is the same there is no bridging. Do I need to set up some port forwarding because local mosquitto is using port 1883, and cloudmqtt uses some other port?


text:
Q: problem with progress bar problem with NumUpDown box I am trying to use a progress bar as a life tracker for DND. I am using NumericUPDown boxes to control the life bar as one box is HP, a second is HP Max and the other is for the changes in HP.
I am having trouble with the HP NumericUpDown up clicker adding the Hp to be more than the Progress bar and it crashes the progream in debug. Can anyone help?
Code:

*

*HP is HP Numeric Up Down

*Health is Progress bar

*Max is Max HP Numeric Up Down

private void HP_MouseUp(object sender, MouseEventArgs e)
{
    if (HP.Value > Health.Maximum) ;
    Health.Maximum = (int)Max.Value;

A: I was overcomplicating it....
I was trying to do maths with the NumberUpDown stuff.
Didn't think for ages about just setting my maximum to be what I wanted the number to stop at.
            {
                HPNum.Maximum = MaxHPNUM.Value;

            }


text:
Q: Unable to build app after reanimated 2 installation in react native I just ran into issues with reanimated 2 (2.7.0) while trying to build react native for ios with the following errors:
 ERROR  TypeError: Cannot add new property '__reanimatedHostObjectRef'

This error is located at:

in AnimatedComponent(View) (at createAnimatedComponent.tsx:693)
in Unknown
in StyledNativeComponent (created by Styled(Component))
in Styled(Component) (at sheet.tsx:13)
in PanGestureHandler (at sheet.tsx:12)
in SheetContainer (at staff.tsx:59)
in StaffSheet (at App.tsx:45)
in RCTView (at View.js:32)
in View (at App.tsx:40)
in ApolloProvider (at App.tsx:39)
in App (at renderApplication.js:48)
in RCTView (at View.js:32)
in View (at AppContainer.js:106)
in RCTView (at View.js:32)
in View (at AppContainer.js:133)
in AppContainer (at renderApplication.js:41)
in mobile(RootComponent) (at renderApplication.js:57), js engine: hermes

Any idea on how to resolve this?

A: Related issue here:
https://github.com/software-mansion/react-native-reanimated/issues/1517
Did you try to deep copy the object/array of objects using JSON.parse(JSON.stringify(items)) as mentioned in the thread?


text:
Q: Creating dropdown menu on mouseover using css I'm trying to create a drop-down menu on mouseover using css.
But it seems to be incorrect.
I wanted to display the class .drop on mouseover on .menu.
Can someone help me to correct?
HTML-file:

Home

Time

Contact

CSS-file:
.menu{
  display:block;
  width:80px;
  height:80px;
  background-image:url(../images/menu.svg);
  background-size:cover;
  background-position:center;
}

.menu:hover{
  display:block;
  width:80px;
  height:80px;
  background-image:url(../images/menu2.svg);
  background-size:cover;
  background-position:center;
}

.drop{
  position:absolute;
  background:#000;
  margin:0;
  padding:10px;
  font-family: 'Exo 2', sans-serif;
  color:#FFF;
  visibility:hidden;
}

.menu:hover .drop{
  position:absolute;
  background:#000;
  margin:0;
  padding:10px;
  font-family: 'Exo 2', sans-serif;
  color:#FFF;
  visibility:visible;
}

A: Try this

dffdf

Home

Time

Contact

.menu{
display:block;
width:80px;
height:80px;
background-image:url(../images/menu.svg);
background-size:cover;
background-position:center;
}
 .menu:hover{
display:block;
width:80px;
height:80px;
background-image:url(../images/menu2.svg);
background-size:cover;
background-position:center;
  }

.drop{
position:absolute;
background:#000;
margin:0;
padding:10px;
font-family: 'Exo 2', sans-serif;
color:#FFF;
visibility:hidden;
}

.menu:hover+.drop,.drop:hover{
/*_________^_________^___________*/
position:absolute;
background:#000;
margin:0;
padding:10px;
font-family: 'Exo 2', sans-serif;
color:#FFF;
visibility:visible;
 }

FIDDLE


text:
Q: Youtybe player jetpack compose I wanted to implement Youtube Player in jetpack compose by
@Composable
fun YoutubeScreen() {
    val ctx = LocalContext.current
    AndroidView(factory = {
        val fm = (ctx as AppCompatActivity).supportFragmentManager
        val view = FragmentContainerView(it).apply {
            id = R.id.fragment_container_view_tag
        }
        val fragment = YouTubePlayerSupportFragmentXKt().apply {
            initialize("YoutubeApiKey",
                object : YouTubePlayer.OnInitializedListener {
                    override fun onInitializationFailure(
                        provider: YouTubePlayer.Provider,
                        result: YouTubeInitializationResult
                    ) {
                        Toast.makeText(
                            context,
                            "Error playing video",
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                    override fun onInitializationSuccess(
                        provider: YouTubePlayer.Provider,
                        player: YouTubePlayer,
                        wasRestored: Boolean
                    ) {
                        if (!wasRestored) {
                            player.cueVideo("YoutubeVideoId")
                        }
                    }
                })
        }
        fm.commit {
            setReorderingAllowed(true)
            add(R.id.fragment_container_view_tag, fragment)
        }
        view
    })
}

I use Hilt and my Activity inherit ComponentActivit but AppCompatActivity is required in the example above.
MainActivity : ComponentActivity()

Link to tutorial:
Looking for a Jetpack Compose YouTube Video Player wrapper dependency


text:
Q: ElasticSearch: how min_doc_count affects performance? Why is the time taken of this:
"aggs": {
            "Condition": {
                "terms": {
                    "field": "color",
                    "size": 10,
                    "min_doc_count": 1
                }
          }

is drastically faster than this:
    "aggs": {
            "Condition": {
                "terms": {
                    "field": "color",
                    "size": 10,
                    "min_doc_count": 0
                }
          }

Even though they both return the same aggregation result to me?

A: Extracted from the documentation:

Setting min_doc_count=0 will also return buckets for terms that didn't match any hit. However, some of the returned terms which have a document count of zero might only belong to deleted documents or documents from other types, so there is no warranty that a match_all query would find a positive document count for those terms.

So it seems that if you have lots of deleted documents the performance would be worse because the aggregation would process a bigger amount of documents. Try to optimize the index to see if the performance becomes similar.

A: To add on to  @moliware answer from the documentation excerpt

Setting min_doc_count=0 will also return buckets for terms that didn't
  match any hit. However, some of the returned terms which have a
  document count of zero might only belong to deleted documents or
  documents from other types, so there is no warranty that a match_all
  query would find a positive document count for those terms.

besides deleted documents with min_doc_count=0 another significant caveat is that aggregation is not restricted to documents that match the parent query or restricted to the types .
See the below example:
Example:
1) Create test index
PUT  test

2) Insert documents of type1 and type3
POST _bulk
{"index":{"_index":"test","_type":"type1","_id":"1"}}
{"condition":"good"}
{"index":{"_index":"test","_type":"type1","_id":"2"}}
{"condition":"bad"}
{"index":{"_index":"test","_type":"type1","_id":"3"}}
{"condition":"soso"}
{"index":{"_index":"test","_type":"type1","_id":"4"}}
{"condition":"excellent"}
{"index":{"_index":"test","_type":"type1","_id":"5"}}
{"condition":"bad"}
{"index":{"_index":"test","_type":"type1","_id":"6"}}
{"condition":"bad"}
{"index":{"_index":"test","_type":"type1","_id":"7"}}
{"condition":"excellent"}
{"index":{"_index":"test","_type":"type3","_id":"1"}}
{"condition":"unwell"}

3) Query all documents of type1 without term bad:
POST test/type1/_search
{
   "query": {
      "bool": {
         "must_not": {
            "term": {
               "condition": "bad"
            }
         }
      }
   },
    "aggs": {
            "condition_value": {
                "terms": {
                    "field": "condition",
                    "size": 10,
                    "min_doc_count": 0
                }
          }
    }

}

Response:
  "aggregations": {
      "condition_value": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "excellent",
               "doc_count": 2
            },
            {
               "key": "good",
               "doc_count": 1
            },
            {
               "key": "soso",
               "doc_count": 1
            },
            {
               "key": "bad",
               "doc_count": 0
            },
            {
               "key": "unwell",
               "doc_count": 0
            }
         ]
      }
   }

Note the documents of type:type3 and condition:bad in the results.
Since the term aggregations are by default orderd by doc_count and the OP has size:10 it may appear to not affect the overall result setting size:0 would give a better picture. In short the number of terms used for generating the aggregation would be significantly larger with min_doc_count:0.


text:
Q: Fair value of game involving obtaining Heads I don't know how to solve this question: You are playing a game with flipping a coin. You can play it as many times as you want until there is a head. At the nth time, when you get a head, they will pay the $2^n$ dollars. How much are you willing to play this game? What's the fair value?

A: This is the famous St. Petersburg's paradox.
If you have got a head in your first try, you will get $2$ dollars and the possibility for this case is $\frac{1}{2}$. Hence the first try has $1$ dollar expected income.
If you get a head in the second try, you will get $2^2=4$ dollars, but the possibility for this case will be $$\frac{1}{2} \text {(you get tail in first try)} \times \frac{1}{2} \text {(you get head in second try)} =1/4.$$
Hence the second try also has $1$ dollar expected income.
You can inductively prove that every try has equal $1$ dollar expected income. Since you may try it ad infinitum, the total expected income will be arbitrarily large, and this, theoretically, also should be what you would pay - that's why it is called as a paradox.
For further discussion trying to solve it, you can refer to the Wikipedia link I have given.


text:
Q: How should I configure elasticsearch mapping in order to get the MySQL "like" like behaviour? I have a field say "name" which can contain :

*

*Multiple words;

*both lower case and upper case;

*digits;

*special characters: !@#$%^&*();

*different languages like: english, french, danish and others.

The task is to define the settings of this field so that when I search I can get the desirable results as follows: no matter what I pass in as searched string(ex: '1', 'a', '#1' 'èæ qтчert1') I should get all documents that contain searched sequence.
Note: I use elasticsearch v 5.6;

A: I believe the TEXT type, should be OK. The best possible way is by testing it.
PUT /language_test/sample/1
{
  "sentence" :" 你吃饭了吗?",
  "lang" :"chinese"
}
PUT /language_test/sample/2
{
  "sentence" :"Var kan jag hitta någon som talar engelska?",
  "lang" :"swedish"
}
GET /language_test/_mapping


text:
Q: Hartl Rails Tutorial Chapter 8.46 NoMethodError one my my tests receiving the following error in Chapter 8 of Hartl's Rails Tutorial.
>  1) Error:
> UsersLoginTest#test_login_with_valid_information_followed_by_logout:
> NoMethodError: undefined method `forget' for #<Class:0x000000079be3b0>
>     app/helpers/sessions_helper.rb:30:in `forget'
>     app/helpers/sessions_helper.rb:37:in `log_out'
>     app/controllers/sessions_controller.rb:18:in `destroy'
>     test/integration/users_login_test.rb:40:in `block in <class:UsersLoginTest>'

I have tried copying and pasting code exactly as it is in the tutorial, but it doesn't seem to be solving the issue.
Here is my Sessions Helper
module SessionsHelper
  def log_in(user)
    session[:user_id] = user.id
  end

  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)

      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  def logged_in?
    !current_user.nil?
  end

  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # Logs out the current user.
  def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end
end

And my sessions controller is below
class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)

    if user && user.authenticate(params[:session][:password])
      log_in user
      remember user
      redirect_to user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
    log_out if logged_in?
    redirect_to root_url
    end
  end

Any suggestions would be very much appreciated!

A: Here we can see the importance of really looking closely at the error message. It says there is a "No Method Error". OK. So we're doing something with the Users and there's no method. A user is a modeled thing, so let's look at app/models/user.rb:
class User < ActiveRecord::Base
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
 def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

  # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end
end

we see that at the very end, there is a method being created called "forget"
def forget
  #something
end

That opens up the method to calls from other controllers and helpers, which you've already created in the Sessions section.