text:
Q: Grupo de imagens em gird do bootstrap ficando fora do loop Tenho uma lista de imagens onde estou usando em grid pra organiza-las ficando a quantidade exata que preciso por linhas.
Com isso eu fiz um loop para controlar os grids e tenho também o loop das imagens.
 Duvida: O que poderia esta fazendo para corrigir porque os grids e as imagens estão ficando separados, como podem ver em:  view-source google chrome
Caso queiram ver mais sobre o grid, eu peguei desse post: Grid bootstrap ficando desalinhado em painel com resultados trazidos do banco
 E como podem ver também na imagem abaixo, esse erro faz minhas imagens ficarem uma debaixo da outra.

php:

      <?php
      $i = 0;
      $row = 0;
      while($i < $count) :
        if($row == 6){
         echo '

 ';
         $row = 0;
       }
       ?>

          <?php
          $nofoto = '../../images/nofoto.jpg';
          while($rowDadosFoto = $queryDadosFoto->fetch()) {
            $foto = $rowDadosFoto['FOTO'];
            if($foto >= 1){
              echo"

";
            }else{
              echo"

";
            }
          }
          ?>

        <?php
        $row++;
        $i++;
      endwhile;
      ?>

view-source google chrome

A: Está faltando um fechamendo de div em baixo da

      <?php
      $i = 0;
      $row = 0;
      while($i < $count) :
        if($row == 6){
         echo '

 ';
         $row = 0;
       }
       ?>

          <?php
          $nofoto = '../../images/nofoto.jpg';
          while($rowDadosFoto = $queryDadosFoto->fetch()) {
            $foto = $rowDadosFoto['FOTO'];
            if($foto >= 1){
              echo"

";
            }else{
              echo"

";
            }
          }
          ?>

        <?php
        $row++;
        $i++;
      endwhile;
      ?>

A: Você está fazendo toda iteração dentro de um col-md-2, por isso as imagens ficam todas numa coluna e fica um monte de coluna sobrando como se vê no final:

Se for uma imagem por coluna, vc não precisa de uma ul. Não entendi como ficaria seu design mas tentei fazer algo parecido.

        <?php while($rowDadosFoto = $queryDadosFoto->fetch()) : ?>

                    <img src='../../images/<?= $rowDadosFoto['FOTO'] >= 1 ? 'produtos/'.$rowDadosFoto['FOTO'] : 'nofoto.jpg' ; ?>' class='img-responsive' style='vertical-align: middle;width:100px;height:100px;'>

        <?php endforeach; ?>


text:
Q: Does a factory automatically run a method in a model? I am trying to write a test for a model which is working perfectly - but for some reason the test is not returning the expected result.
My model contains this:
after_validation :set_conference

  def rand_conference
    r = rand.to_s[2..8]
    while conference == r
        r = rand.to_s[2..8]
    end
    r
  end

  def set_conference
    self.conference = rand_conference unless conference.presence
  end
end

And in my model test I am testing this (ideally I would be testing if 'conference' is a 6 digit number, but for now just a 'not nil' would suffice):
Factory:
FactoryGirl.define do
  factory :plan do
    name "Test"
    description "Lorem Ipsum"
    category "template"
  end
end

Model_spec:
  before (:each) do
    @plan = build(:plan)
  end

 it "has a conference number" do
   expect(@plan.conference).not_to be_empty
 end

As a result i get:
1) Plan has a conference number
     Failure/Error: expect(@plan.conference).not_to be_empty
     NoMethodError:
       undefined method `empty?' for nil:NilClass

Does factorygirl use the after_validation callback?

A:
I am trying to write a test for a model which is working perfectly - but for some reason the test is not returning the expected result.

The test is not returning the expected result because the after_validation callback is never called which is why conference attribute is nil. So @plan.conference is nil and you cannot call empty? on nil object. Hence, the error undefined method 'empty?' for nil:NilClass
@plan = build(:plan) would just create an instance of Plan model as per the attributes specified in factory :plan and assign it to instance variable @plan. It will definitely not run any validations and obviously no ActiveRecord callbacks.
Just change the before block as
before (:each) do
  @plan = create(:plan)  ## create record in database
end

With this your after_validation callback would be triggered as you actually create a record in database.
For reference:

Callbacks are methods that get called at certain moments of an
  object's life cycle. With callbacks it is possible to write code that
  will run whenever an Active Record object is created, saved, updated,
  deleted, validated, or loaded from the database.

A: Yes the callbacks are automatically run. However, you used FactoryGirl.build to build a plan, which only initializes the object but doesn't validate it.
You either need to make sure the validations are run:
before (:each) do
  @plan = build(:plan)
end

it "has a conference number" do
  @plan.valid?
  expect(@plan.conference).not_to be_empty
end

Or you need to call FactoryGirl.create to create your plan, but this would also create it in your test database:
before (:each) do
  @plan = create(:plan)
end

it "has a conference number" do
  expect(@plan.conference).not_to be_empty
end

A: I think the most abvious way is to be explicit like this :
it  "has a conference number" do
  @plan = build(:plan)
  @plan.set_conference
  expect(@plan.conference).not_to be_empty
end

Anyway, I don't recommend to use callbacks. I think it's preferable to use service objects.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Measuring 5G(New Radio) data List<CellInfo> cellInfoList = telephonyManager.getAllCellInfo();

First, I got total cellInfoList, and separated to CellInfo
cellRSRP = ((CellSignalStrengthNr) ((CellInfoNr) cellInfo).getCellSignalStrength()).getCsiRsrp();

I tried to get 5G RSRP rate for a few days, and this is the best I can approach and this doesn't work.
When It comes to LTE Cell Data,
cellRSRP = ((CellInfoLte) cellInfo).getCellSignalStrength().getRsrp();

It works like this, and It outputs the value well.
The Difference of these two Codes is:

*

*Change CellInfoLte -> CellInfoNr

*Additional CellSignalStrengthNr casting
(Because (CellInfoNr) cellInfo).getCellSignalStrength() returns CellSignalStrength,
Not CellSignalStrengthNr.)
(Deliberately casted.)
Is 5G Cell Signal Strength measurement isn't ready by now?
I've spent a lot of time in this problem, but didn't found a single solution.

A: I have a similar issue and the following casting seems to be working. Unfortunately, there is not possible to test it on real 5g radio in our country.
int mCsiRsrp = ((CellSignalStrengthNr) ((CellInfoNr) cellInfo).getCellSignalStrength()).getCsiRsrp();


text:
Q: Fitting images properly and zoom on hover I have two issues I'm dealing with at the moment. The first question is: I want to fit my images properly so that you can see the person in the picture while the images are still filling the entire screen. The second question is: how do I set up a transform function so that when you hover over the button, the text turns purple and the image behind it zooms in and out? Here is the current code that I have:
Code Snippet:
https://hover-example.diknight55.repl.co/
HTML:

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.98.0">
    <title>StudioPick</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">

    <link href="CSS/profileselect.css" rel="stylesheet">

              StudioPick
              <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

              </button>

                    Home

                    Log In

                    Sign Up

          <button class="profileselect">STUDIO</button>

            <button class="profileselect">ARTIST</button>

@Bekaedo
StudioPick 2022 ©

CSS:

body {
    font-family: Arial;
    color: white;
}
.navbar-light {
  background-color: transparent;
  z-index: 20;
}
.navbar-nav{
  justify-content: space-between;

}
.navbar-brand {
  font-size: 35px;
}
.nav-item{
  color: #686868 !important;
  font-size: 20px;
  padding-right: 15px;
}
.nav-item2{
  background-color: #9370DB !important;
  border-radius: 15px !important;
  width: 95px !important;
  text-align: center !important;
  font-size: 20px;
}
#navbarSupportedContent{
  position: relative;
  right: -1375px;
}

.split {
    height: 100%;
    width: 50%;
    position: fixed;
    z-index: 0;
    top: 0;
    overflow-x: hidden;
    padding-top: 20px;
    transition: all 0.3s ease-in-out;
}

.left {
    left: 0;
    background-image: url('../Images/kennybeats-stu.jpeg')
}

.right {
    right: 0;
    background-image: url('../Images/uzi-performing.jpeg')
}

.centered button {
    font-size: 50px !important;
    color: #ffffff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 5px;
    background-color: #000000 !important;
    text-align: center !important;
}

.left :hover {
    background-size: 150%;
}

Javascript:

$(document).ready(function() {

    $('.split').mouseover(function() {

        $(this).find('.profileselect').css('transform', 'scale(1.2)');
    });

    $('.split').mouseout(function() {

        $(this).find('.profileselect').css('transform', 'scale(1)');
    });
});

Thanks!

A: I fixed some styling and wrote the javascript. I also added the jQuery script and its working perfectly

$(".profileselect").on("mouseover", function () {
      $(this).parent().parent().addClass("hovered")
    })
    $(".profileselect").on("mouseout", function () {
      $(this).parent().parent().removeClass("hovered")
    })
body {
      font-family: Arial;
      color: white;
    }

    .navbar-light {
      background-color: transparent;
      z-index: 20;
    }

    .navbar-nav {
      justify-content: space-between;

    }

    .navbar-brand {
      font-size: 35px;
    }

    .nav-item {
      color: #686868 !important;
      font-size: 20px;
      padding-right: 15px;
    }

    .nav-item2 {
      background-color: #9370DB !important;
      border-radius: 15px !important;
      width: 95px !important;
      text-align: center !important;
      font-size: 20px;
    }

    #navbarSupportedContent {
      position: relative;
      right: -1375px;
    }

    .split {
      height: 100%;
      width: 50%;
      position: fixed;
      z-index: 0;
      top: 0;
      overflow: hidden;
      padding-top: 20px;
      isolation: isolate;
    }

    .split::after {
      content: "";
      position: absolute;
      inset: 0;
      transition: all 0.3s ease-in-out;
      background-size: cover;
      background-position: center;
      z-index: -1;
    }

    .left {
      left: 0;
    }

    .left::after {
      background-image: url('https://media.istockphoto.com/id/499718289/photo/faisal-mosque-islamabad-pakistan.webp?s=612x612&w=is&k=20&c=9K6B2okHbAfbN3uLdpLLgb_Nl6lRxtflRAp75WbAPVE=')
    }

    .right {
      right: 0;
    }

    .right::after {
      background-image: url('https://media.istockphoto.com/photos/pakistan-monument-islamabad-picture-id535695503?k=20&m=535695503&s=612x612&w=0&h=S16wHXc-b3AkL7YMrcFkR2pDGFJA1bRsPmAfQlfrwkc=')
    }

    .centered button {
      font-size: 50px !important;
      color: #ffffff;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: 5px;
      background-color: #000000 !important;
      text-align: center !important;
    }

    .left :hover {
      background-size: 150%;
    }

    .split.hovered::after {
      transform: scale(1.1);
    }

    .split.hovered button {
      color: purple;
    }
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">

          StudioPick
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
          aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Home

              Log In

              Sign Up

      <button class="profileselect">STUDIO</button>

      <button class="profileselect">ARTIST</button>

@Bekaedo
StudioPick 2022 ©

A: Check Images visiblity :
.right, .left {
      background-size: cover;
}

FYI, And also you have used navbar-expand-lg so its showing header improperly. try removing it and check.

A: try this
.right, .left {
      background-size: cover;
}


text:
Q: May a random access iterator to end be incremented by zero? The title says it all really. Given an iterator to end, may it be incremented by zero without invoking undefined behavior?
Case in point - does the following code work to return an iterator to the specified index - or to end if the index is out of range?
std::vector<Type>::iterator Class::fromIndex(size_t index) {
    return member_vector.begin() + std::min(index, member_vector.size());
}

If the behavior for std::advance or std::next are different that would be interesting to know as well, but here I am interested specifically in operator+.

A: It's a well-defined no-op, say I.

Given an iterator to end, may it be incremented by zero without invoking undefined behavior? [..] I am interested specifically in operator+.

For random access iterators, table 115 under [random.access.iterators] tells us (under "Operational Semantics", and after "expanding" the meaning of the while loop there given) that (r += 0) ≡ r, so (.end() += 0) ≡ .end().
The definition for r + 0 is given in terms of that.

If the behavior for std::advance or std::next are different that would be interesting to know as well.

For everything else, std::next is defined in terms of std::advance, which in [iterator.operations] doesn't explicitly say that this is well-defined but it seems pretty obvious from the wording, which defers to the English-language definition for "increment"/"decrement": "Increments (or decrements for negative n) iterator reference i by n".
We know that the English-language "increment"/"decrement" by zero is a no-op in all practical terms.


text:
Q: Creating tables with descriptive statistics in R I would like some help on creating formatted tables in R - whether it's just using the normal IDE or R Markdown. There are two main things that I'd like to do:

*

*Present the descriptive statistics (Mean, Median, Min, Max) by group based on different columns

*Present the descriptive statistic based on the total sample (ungrouped data)

Sample data:
   df <- data.frame(Gender = c("F", "M", "F", "M", "M", "M", "M", "F", "M", "M"),
                 Young = c("Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y", "N"),
                 Age = c("14", "25", "13", "24", "14", "25", "13", "24", "10", "26"),
                 Location = c("Suburb", "Rural", "Suburb", "Rural","Suburb", "Rural","Suburb", "Rural","Suburb", "Rural"))

Expected results

Variable
Mean
Median
Max
Min

Gender

Female

Male

Location

Suburb

Rural

TOTAL

Is there a way to do this in R?

A: You can get all the information that you need by getting the data in long format.
library(dplyr)
library(tidyr)

df <- type.convert(df, as.is = TRUE)

df %>%
  pivot_longer(cols = -Age) %>%
  group_by(name, value) %>%
  summarise(min_age = min(Age),
            max_age = max(Age),
            median_age = median(Age),
            mean_age = mean(Age))

#  name     value  min_age max_age median_age mean_age
#  <chr>    <chr>    <int>   <int>      <int>    <dbl>
#1 Gender   F           13      24         14     17
#2 Gender   M           10      26         24     19.6
#3 Location Rural       24      26         25     24.8
#4 Location Suburb      10      14         13     12.8
#5 Young    N           24      26         25     24.8
#6 Young    Y           10      14         13     12.8

A: Similar answer using data.table:
> library(data.table)
> df <- data.frame(Gender = c("F", "M", "F", "M", "M", "M", "M", "F", "M", "M"),
+                  Young = c("Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y", "N"),
+                  Age = c("14", "25", "13", "24", "14", "25", "13", "24",
+                          "10", "26"),
+                  Location = c("Suburb", "Rural", "Suburb",
+                               "Rural","Suburb", "Rural","Suburb",
+                               "Rural","Suburb", "Rural"))
> setDT(df)                        # make it a data.table
> df[,Age:=as.integer(Age)]        # correct age column
> df[,.(mean=mean(Age), median=median(Age), max=max(Age), min=min(Age)),
+     by=.(Gender,Location)]
   Gender Location    mean median max min
1:      F   Suburb 13.5000   13.5  14  13
2:      M    Rural 25.0000   25.0  26  24
3:      M   Suburb 12.3333   13.0  14  10
4:      F    Rural 24.0000   24.0  24  24
>

Or if we want to stratify by one variable at a time:
> df[,.(mean=mean(Age), median=median(Age), max=max(Age),min=min(Age)),
+    by=.(Gender)]
   Gender    mean median max min
1:      F 17.0000     14  24  13
2:      M 19.5714     24  26  10
> df[,.(mean=mean(Age), median=median(Age), max=max(Age), min=min(Age)),
+    by=.(Location)]
   Location mean median max min
1:   Suburb 12.8     13  14  10
2:    Rural 24.8     25  26  24
>

And inspired by Ronak's nice answer, the same as a data.table one-liner:
> melt(df, id.vars="Age")[, .(mean=mean(Age),
+                             median=median(Age),
+                             min=min(Age),
+                             max=max(Age)), by=.(variable,value)]
   variable  value    mean median min max
1:   Gender      F 17.0000     14  13  24
2:   Gender      M 19.5714     24  10  26
3:    Young      Y 12.8000     13  10  14
4:    Young      N 24.8000     25  24  26
5: Location Suburb 12.8000     13  10  14
6: Location  Rural 24.8000     25  24  26
>

A: Several packages have wrapped functions for this. I usually use describe from {psych} package.
library(tidyverse)

df <- data.frame(Gender = c("F", "M", "F", "M", "M", "M", "M", "F", "M", "M"),
                 Young = c("Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y", "N"),
                 Age = c("14", "25", "13", "24", "14", "25", "13", "24", "10", "26"),
                 Location = c("Suburb", "Rural", "Suburb", "Rural","Suburb", "Rural","Suburb", "Rural","Suburb", "Rural"))

df_summary <- psych::describe(df)

df_summary

         vars  n mean   sd median trimmed  mad min max range  skew kurtosis   se
Gender*      1 10  1.7 0.48    2.0    1.75 0.00   1   2     1 -0.75    -1.57 0.15
Young*       2 10  1.5 0.53    1.5    1.50 0.74   1   2     1  0.00    -2.19 0.17
Age*         3 10  3.5 1.58    3.5    3.50 2.22   1   6     5  0.00    -1.42 0.50
Location*    4 10  1.5 0.53    1.5    1.50 0.74   1   2     1  0.00    -2.19 0.17

You can then use dplyr to do whatever you want.
df_summary %>% select(mean, median, max, min)


text:
Q: Disable redirection script We have a redirect script on our site that detects mobile devices and redirects users to a subdomain which goes to the mobile site folder. But now we need a mechanism that gives the visitor a button on the page that then reloads the page and bypasses this check. The goal is if a smartphone user wants to see the full site, we need to give them a button to push to do so.  So, the question is: is it possible to disable this script when user clicks on that button?

A: I beleive cookies are a more better solution since they will not go away when the page is changed.
Just make a cookie when the user clicks the button and send him to the mainsite.
How to make the cookie:_
setcookie("fullsite", "SomeRandomThing", time()+60*60*24*30); // It will expire after a month

If the cookie is not set, then make it redirect.
if (!isset($_COOKIE['fullsite'])
{
  // redirect
}

Similarily make a button for the user to switch back and make that button delete the cookie.

A: yes you can. load script according to the button press.
if((!isset($_POST['button']) && mobiledevice==true))
{
         //put your redirection script here
}

use something like above

A: What I have done in the past is have a button on all the mobile specific pages that sets a cookie and then redirects the user back to the non mobile page, that cookie is read and if set adds a "back to mobile" banner and skips the mobile redirection code.
Also did a one time use version of this that does not show the "back to mobile" banner and automatically clears the cookie so the next page the suer visits they are back to mobile


text:
Q: In $L$, does there exist a definable non-principal ultrafilter on $\mathbb{N}$ The axiom of constructibility $V=L$ leads to some very interesting consequences, one of which is that it becomes possible to give explicit constructions of some of the "weird" results of AC. For instance, in $L$, there is a definable well-ordering of the real numbers (since there is a definable well-ordering of the universe).
Since AC holds true in $L$, the ultrafilter lemma must be true. Does this mean that a definable non-principal ultrafilter on $\mathbb{N}$ exists in $L$, given by an explicit formula?
If so, what is the formula?

A: Let me emphasize what Noah de-emphasized (by putting it in parentheses) in his answer: Instead of the "really cheap" idea of the first free ultrafilter in $L$-order, one can use the $L$-order of subsets of $\mathbb N$ to greedily construct an ultrafilter. The $L$-ordering of the subsets of $\mathbb N$ is a $\Delta^1_2$ relation with some additional properties (I believe Moschovakis uses the terminology $\Delta^1_2$-good well-ordering). One can then deduce that the greedily constructed ultrafilter is a $\Delta^1_2$ set of subsets of $\mathbb N$.
Since free ultrafilters on $\mathbb N$ never have the Baire property and are never Lebesgue measurable, this shows that the classical results, that analytic and coanalytic sets have the Baire property and are measurable, cannot be extended higher in the projective hierarchy in ZFC (without additional hypotheses like large cardinals or determinacy).
Similar greedy constructions based on the $L$-ordering of the reals produce $\Delta^1_2$ examples of lots of other sets of reals that, in the absence of $V=L$, would be obtained by applying the axiom of choice and thus might not be definable at all.  Examples include Hamel bases over $\mathbb Q$, Vitali sets, and Bernstein sets.

A: Generally formulas in set theory are not "very nice". There is very little structure to work with.
We can define when $U$ is a filter over $X$, simply by saying that every element of $U$ is a subset of $X$, and $U$ is closed under superset (below $X$), and under finite intersections (recall that in set theory we can say that within a first-order formula, simply by stating that the intersection over a finite subset of $U$ is in $U$).
Then we can define $U$ as an ultrafilter as a filter which is maximal with respect to inclusion. And $U$ is free if it doesn't contain finite sets, or a singleton, or its entire intersection is empty. Pick your pick.
Finally, from the axiom of choice we can prove that the set of ultrafilters over $\Bbb N$ is non-empty. Therefore using the canonical well-ordering of $L$ we can fully state "the least free ultrafilter over $\Bbb N$". It's just an insanely long formula (especially if you unwind all the recursive definitions everywhere and the abbreviations for subsets, finite, etc.) which is not very pretty.

A: Yes, but it's not particularly nice: since $L$ has a definable well-ordering of the sets of reals (in fact, of all of $L$) coming from the $L$-hierarchy itself, there is a formula defining the "least" (in that well-ordering) ultrafilter, $U$.
(This $U$ isn't the only naturally definable ultrafilter in $L$; we could also consider the ultrafilter gotten by going through the infinite sets of natural numbers, in the $L$-order, and throwing in each set that we can - a sort of "greedy algorithm" for building an ultrafilter. This ultrafilter $U'$ would also be definable, and there's no reason for $U'$ to equal $U$. Other tricks exist.)
Note that, while of course there are only countably many definable ultrafilters, we can use the $L$-ordering to produce a definable ultrafilter with any given definable property ("the least ultrafilter with property X") - so there's basically nothing that can be said about the definable ultrafilters.


text:
Q: Change the value of xforms element via javascript? I was wondering if it's possible to change the value of an xforms element via javascript and then submit the form with that value?
what i have tried is change the text of an xforms:input when an <input type="file"> is triggered and it works, the thing is that when i submit the form, the xforms:input doesn't seem to apply the value
<div id="ubi" class="controls">
     <xf:input ref="ubicacion"/>
     <input class="input-file" id="fileadjunto" type="file" onchange="uploadfile()"/>
</div>

<script>
        function uploadfile()
        {{
            var inp = document.getElementById('fileadjunto');
            var name = inp.files.item(0).name;
            var span1 = document.getElementById('ubi').getElementsByTagName('span')[0].getElementsByTagName('span')[0].getElementsByTagName('input')[0];
            span1.value = name;
        }};
</script>

why am i getting the spans and inputs? if you check the xforms:input element in the console you'll see that it's converted to
<span .....>
    <span.....>
         <input..../>
    </span>
</span>


text:
Q: WordPress Customizer checkbox default not working I am having a problem with the WordPress Customizer checkbox default value.
No matter what I put in the default value, but the checkbox is always checked in the theme customizer.
$wp_customize->add_setting( 'swastika_social_youtube', array(
    'capability' => 'edit_theme_options',
    'default'    =>  'false',
    'sanitize_callback' => 'swastika_sanitize_checkbox',
    )
);

$wp_customize->add_control( 'swastika_social_youtube', array(
    'type' => 'checkbox',
    'section' => 'social_settings_section',
    'label'      => __( 'Show Youtube Icon', 'swastika' ),
    )
);

And here is how I am showing icon
<?php if ( true == get_theme_mod( 'swastika_social_youtube', false ) ) { ?>

    <?php } ?>

Please Help Me

A: Your default of 'false' is actually a string, which evaluates to true because it's not empty.
Use plain false, without the quotes.


text:
Q: WinAPI c++ multithread computation I have a task to compute Pi with following formula:

(i is in range from 0 to N, N = 10^8)
Computation should be completed in multiple threads with following requirement: each thread receives only a small fixed amount of computations to complete (in my case - 40 sum members at a time), and there should be a "Task pool" which gives new set of computations into a thread when it reports completion of previous set of operations given to it. Before a thread receives new task, it should wait. All of this should be done with WinAPI.
My solution is this class:
#include "ThreadManager.h"
#include <string>

HANDLE ThreadManager::mutex = (CreateMutexA(nullptr, true, "m"));

ThreadManager::ThreadManager(size_t threadCount)
{
    threads.reserve(threadCount);
    for (int i = 0; i < threadCount; i++)
    {
        threadInfo.push_back(new ThreadStruct(i * OP_COUNT));
        HANDLE event = CreateEventA(nullptr, false, true, std::to_string(i).c_str());

        if (event)
        {
            threadEvents.push_back(event);
            DuplicateHandle(GetCurrentProcess(), event, GetCurrentProcess(),
                            &(threadInfo[i]->threadEvent), 0, false, DUPLICATE_SAME_ACCESS);
        }
        else std::cout << "Unknown error: " << GetLastError() << std::endl;
        HANDLE thread = CreateThread(nullptr, 0,
                                     reinterpret_cast<LPTHREAD_START_ROUTINE>(&ThreadManager::threadFunc),
                                     threadInfo[i],
                                     CREATE_SUSPENDED, nullptr);
        if (thread) threads.push_back(thread);
        else std::cout << "Unknown error: " << GetLastError() << std::endl;
    }
}

double ThreadManager::run()
{
    size_t operations_done = threads.size() * OP_COUNT;
    for (HANDLE t : threads) ResumeThread(t);
    DWORD index;
    Sleep(10);
    while (operations_done < ThreadManager::N)
    {
        ReleaseMutex(ThreadManager::mutex);
        index = WaitForMultipleObjects(this->threadEvents.size(), this->threadEvents.data(), false, 10000);
        WaitForSingleObject(ThreadManager::mutex, 1000);
        threadInfo[index] -> operationIndex = operations_done + OP_COUNT;
        SetEvent(threadEvents[index]);
        //std::cout << "Operations completed: " << operations_done << "/1000" << std::endl;
        operations_done += OP_COUNT;
    }
    long double res_pi = 0;
    for (auto&& ts: this->threadInfo)
    {
        res_pi += ts->pi;
        ts->operationIndex = N;
    }
    res_pi /= N;
    WaitForMultipleObjects(this->threads.size(), this->threads.data(), true, 10000);
    std::cout.precision(10);
    std::cout << "Pi value for " << threads.size() << " threads: " << res_pi;
    threads.clear();
    return 0;
}

ThreadManager::~ThreadManager()
{
    if (!threads.empty())
        for (HANDLE t: threads)
        {
            TerminateThread(t, -1);
            CloseHandle(t);
        }
    std::destroy(threadInfo.begin(), threadInfo.end());
}

long double ThreadManager::calc(size_t startIndex)
{
    long double xi = 0;
    long double pi = 0;
    for (size_t i = startIndex; i < startIndex + OP_COUNT; i++)
    {
        const long double ld_i = i;
        const long double half = 0.5f;
        xi = (ld_i + half) * (1.0 / N);
        pi += ((4.0 / (1.0 + xi * xi)));
    }
    return pi;
}

DWORD WINAPI ThreadManager::threadFunc(ThreadStruct *ts)
{
    while (ts->operationIndex < N)
    {
        WaitForSingleObject(ts->threadEvent, 1000);
        ts->pi += calc(ts->operationIndex);
        WaitForSingleObject(ThreadManager::mutex, 1000);
        SetEvent(ts->threadEvent);
        ReleaseMutex(ThreadManager::mutex);
    }
    return 0;
}

ThreadStruct::ThreadStruct(size_t opIndex)
{
    this -> pi = 0;
    this -> operationIndex = opIndex;
}

My Idea was that there will be an auto-reset event for each thread, which is set to signaled when a thread finishes it's computation. Main thread is waiting on one of thread Events to signal, and after modifying some values in a shared ThreadStruct (to enable thread start another portion of computations) it sets that same event to signaled, which is received by the exact same thread and the process received. But this doesn't work for even one thread: as a result i see values which are pretty random and not close to Pi (like 0.0001776328265).
Though my GDB debugger was working poorly (not displaying some variables and sometimes even crashing), I noticed that  there were too much computations happening (I scaled down N to 1000. Therefore, I should have seen threads printing out "computing" 1000/40 = 25 times, but actually it happened hundreds of times)
Then I tried adding a mutex so threads wait until main thread is not busy before signaling the event. That made computation much slower, and still inaccurate and random (example: 50.26492171 in case of 16 threads).
What can be the problem? Or, if it's completely wrong, how do I organize multithread calculation then? Was creating a class a bad idea?
If you want to reproduce the problem, here is header file content (I am using c++20, MinGW 6.0):
#ifndef MULTITHREADPI_THREADMANAGER_H
#define MULTITHREADPI_THREADMANAGER_H
#include <iostream>
#include <vector>
#include <list>
#include <windows.h>
#include <memory>

struct ThreadStruct
{
    size_t operationIndex;
    long double pi;
    HANDLE threadEvent = nullptr;
    explicit ThreadStruct(size_t opIndex);
};

class ThreadManager
{
public:
    explicit ThreadManager(size_t threadCount);
    double run();
    ~ThreadManager();

private:
    std::vector<ThreadStruct*> threadInfo;
    std::vector<HANDLE> threads;
    std::vector<HANDLE> threadEvents;
    static HANDLE mutex;
    static long double calc(size_t startIndex);
    static const int OP_COUNT = 40;
    static const int N = 100000000;
    static DWORD WINAPI threadFunc(ThreadStruct* ts);
};

#endif //MULTITHREADPI_THREADMANAGER_H

To execute code, just construct ThreadManager with desired number of threads as argument and call run() on it.

A: Even with all below changed, it doesn't give consistent values close to PI. There must be more stuff to fix. I think it has to do with the events. If I understand it correctly, there are two different things the mutex protects. And the event is also used for 2 different things. So both change their meaning during execution. This makes it very hard to think it through.
1. Timeouts
WaitForMultipleObjects may run into a timeout. In that case it returns WAIT_TIMEOUT, which is defined as 0x102 or 258. You access the threadInfo vector with that value without bounds checking. You can use at(n) for a bounds-checked version of [n].
You can easily run into a 10 second timeout when debugging or when setting OP_COUNT to high numbers. So, maybe you want to set it to INFINITE instead.
This leads to all sorts of misbehavior:

*

*the threads information (operationIndex) is updated while the thread might work on it.

*operations_done is updated although those operations may not be done

*The mutex is probably overreleased

2. Limit the number of threads
The thread manager  should also check the number of threads, since you can't set it to a number higher than MAXIMUM_WAIT_OBJECTS, otherwise WaitForMultipleObjects() won't work reliably.
3. Off by 1 error
Should be
size_t operations_done = (threads.size()-1) * OP_COUNT;
or
threadInfo[index] -> operationIndex = operations_done; // was + OP_COUNT
otherwise it'll skip one batch
4. Ending the threads
Ending the threads relies on the timeouts.
When you replace all timeouts by INFINITE, you'll notice that your threads never end. You need another ReleaseMutex(mutex); before
res_pi /= N;

A: struct CommonData;

struct ThreadData
{
    CommonData* pData;
    ULONG i, k;

    ThreadData(CommonData* pData, ULONG i, ULONG k) : pData(pData), i(i), k(k) {}

    static ULONG CALLBACK Work(void* p);
};

struct CommonData
{
    HANDLE hEvent = 0;
    LONG dwActiveThreadCount = 1;
    ULONG N;
    union {
        double res = 0;
        __int64 i64;
    };

    CommonData(ULONG N) : N(N) {}

    ~CommonData()
    {
        if (HANDLE h = hEvent)
        {
            CloseHandle(h);
        }
    }

    void DecThread()
    {
        if (!InterlockedDecrement(&dwActiveThreadCount))
        {
            if (!SetEvent(hEvent)) __debugbreak();
        }
    }

    BOOL AddThread(ULONG i, ULONG k)
    {
        InterlockedIncrementNoFence(&dwActiveThreadCount);

        if (ThreadData* ptd = new ThreadData(this, i, k))
        {
            if (HANDLE hThread = CreateThread(0, 0, ThreadData::Work, ptd, 0, 0))
            {
                CloseHandle(hThread);

                return TRUE;
            }

            delete ptd;
        }

        DecThread();

        return FALSE;
    }

    BOOL Init()
    {
        return 0 != (hEvent = CreateEvent(0, 0, 0, 0));
    }

    void Wait()
    {
        DecThread();
        if (WaitForSingleObject(hEvent, INFINITE) != WAIT_OBJECT_0) __debugbreak();
    }
};

ULONG CALLBACK ThreadData::Work(void* p)
{
    CommonData* pData = reinterpret_cast<ThreadData*>(p)->pData;
    ULONG i = reinterpret_cast<ThreadData*>(p)->i;
    ULONG k = reinterpret_cast<ThreadData*>(p)->k;
    delete p;

    ULONG N = pData->N;
    double pi = 0;
    do
    {
        double xi = (i++ + 0.5) / N;
        pi += 4 / (1 + xi * xi);
    } while (--k);

    union {
        double d;
        __int64 i64;
    };

    i64 = pData->i64;

    for (;;)
    {
        union {
            double d_compare;
            __int64 i64_compare;
        };

        i64_compare = i64;

        d += pi;

        if (i64_compare == (i64 = InterlockedCompareExchange64(
                           &pData->i64, i64, i64_compare)))
        {
            break;
        }
    }

    pData->DecThread();

    return 0;
}

double calc_pi(ULONG N)
{
    SYSTEM_INFO si;
    GetSystemInfo(&si);
    if (si.dwNumberOfProcessors)
    {
        CommonData cd(N);
        if (cd.Init())
        {
            ULONG k = (N + si.dwNumberOfProcessors - 1) / si.dwNumberOfProcessors, i = 0;
            do
            {
                if (!cd.AddThread(i, k))
                {
                    break;
                }
            } while (i += k, --si.dwNumberOfProcessors);

            cd.Wait();

            if (!si.dwNumberOfProcessors)
            {
                return cd.res/ N;
            }
        }
    }

    return 0;
}

when i call calc_pi(100000000) on 8 core i got 3.1415926535898153


text:
Q: Two-column text layout with irregular inset One picture worth a thousand words:

How to implement this layout? I want text to flow freely from Column-1 to Column-2.
Note that inset width is greater than column width, so it "pushes" text in Column-1 a bit. Below inset Column-1 returns to normal width.
I want compatibility with latest releases of modern browsers (Chrome, FF). No IE is OK. Safari, Mobile Safari, Opera are desirable.
JS is OK, but I'd prefer a solution without it.

Update about known dimensions:

*

*I know width and height of whole "page".

*I know width and height of image.

*I know width of inset, but not its height (since there is additional caption text there).

Update:
Below is my test code. If I move inset out of columns div, it is displayed as "third column".
If inset is in front of the text, it is displayed in the left column at the top, clipped from the left side to the column width.
If inset is in end of the text, it is displayed in the right column at the bottom, clipped from the left side to the column width in Chrome, and overflowing to the left column in FF (without pushing its text).
I must be missing something... :-(
<!DOCTYPE html>

<meta charset="utf-8">

<title>Column test</title>

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc neque elit, mollis a vulputate ac, mollis vitae augue. Sed augue enim, congue ac laoreet hendrerit, ultricies a sem. Integer dignissim molestie erat quis lacinia.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc neque elit, mollis a vulputate ac, mollis vitae augue. Sed augue enim, congue ac laoreet hendrerit, ultricies a sem. Integer dignissim molestie erat quis lacinia. Nulla pellentesque sodales dolor, et egestas tortor ultricies et. In hac habitasse platea dictumst. Nunc semper dui sit amet sem condimentum vitae molestie arcu cursus. Morbi rhoncus posuere gravida. Sed bibendum ullamcorper lectus, id mollis nulla pulvinar hendrerit. Mauris id est nulla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam tempor venenatis vehicula. Nam a enim justo, nec viverra sem. Vivamus faucibus ullamcorper lobortis.

Cras nulla ante, tincidunt non accumsan nec, adipiscing eget odio. Nam gravida ligula at elit interdum lacinia. Mauris condimentum justo venenatis mauris condimentum eu fringilla augue hendrerit. Duis eget enim et erat faucibus blandit et lobortis ligula. Integer felis justo, feugiat et scelerisque non, vehicula in urna. Aliquam dignissim tristique ornare. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam volutpat ullamcorper purus, ut auctor magna consectetur at. Aliquam vitae odio in lectus lobortis fermentum. Nunc tortor quam, luctus et consequat vel, fringilla at lorem. Cras ut molestie diam. In aliquet purus sed massa sagittis id dapibus est ultricies. Mauris sed laoreet est.

In hac habitasse platea dictumst. Integer mollis dapibus tellus, at venenatis mi euismod quis. Donec quis ullamcorper nulla. Maecenas semper porttitor nibh, et porttitor ipsum convallis eget. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Donec est turpis, faucibus id venenatis ac, mollis ut risus. Nam tincidunt scelerisque lectus.

Donec euismod neque id est accumsan eu egestas tortor adipiscing. Curabitur tortor ante, mattis at ultrices vel, facilisis eu sapien. Nullam congue ipsum vel nisi condimentum quis condimentum turpis pretium. In aliquet imperdiet ligula, ut dictum lorem ultrices at. Quisque ac nunc arcu. Pellentesque egestas venenatis urna, in blandit purus ullamcorper at. Ut lobortis, nisi at pharetra consequat, est nibh interdum est, vitae tempor felis magna sed erat. In hac habitasse platea dictumst.

Sed ligula felis, volutpat ac pulvinar a, porta sed felis. Aenean eu turpis nec magna mollis tincidunt quis vitae massa. Praesent faucibus nisl in leo rutrum gravida. Donec aliquet interdum vestibulum. Aenean faucibus posuere ornare. Donec sed velit id sem pulvinar faucibus ut tempor tellus. Donec ante justo, egestas eget venenatis vitae, tempor et nulla. Suspendisse dapibus pellentesque nulla sit amet tempor. Curabitur auctor, sem id ullamcorper ultricies, nisl tortor rhoncus lorem, eleifend ornare tortor ante vel lectus. Nunc lectus sem, ullamcorper vitae aliquam sed, volutpat eu justo. Nam et nisl est, dictum vestibulum dolor. Cras ipsum orci, vestibulum ac convallis a, laoreet in lorem. Aliquam at adipiscing lacus. Donec quis dui sed felis sollicitudin ultricies in vel libero. Donec tincidunt felis et metus mollis at congue elit molestie.

Ut posuere lobortis est, sit amet adipiscing neque vehicula eu. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam id fermentum felis. Aenean nunc neque, faucibus vel consectetur eget, ullamcorper ac est. Nulla sit amet metus sed erat fringilla lacinia. In at pulvinar sapien. Mauris volutpat scelerisque elit, quis lobortis orci imperdiet pretium. Ut facilisis interdum dapibus. Sed luctus dignissim blandit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum sollicitudin ultricies tortor nec rutrum.

Quisque sed sollicitudin lacus. Quisque egestas interdum dui, eget gravida sem convallis in. Sed auctor justo et urna gravida tincidunt. Proin erat nibh, euismod et varius at, aliquam in diam. Nullam condimentum libero id libero pretium ac ullamcorper arcu luctus. Sed gravida mattis tortor sit amet accumsan. Etiam vitae consequat dolor.

A: How about making the image with its caption in a separate CSS layer and "pinning" it into the right position, coupled with some DIV's underneath which take care of pushing the content out from under it?  Something like this:
In CSS:
#column1 {
    color: white;
    width: 200px;
    background: #444;
    height: 300px;
    float: left;
    margin-right: 5px;
}
#column1-spacer {
    float: right;
    width: 45px;
    height: 170px;
}
#column2 {
    color: white;
    width: 200px;
    height: 300px;
    background: #444;
    float: left;
    margin-left: 5px;
}
#column2-spacer {
    height: 175px;
}
#imageWrapper {
    background: white;
    position: absolute;
    left: 170px;
    width: 250px;
    height: 170px;
}
#image {
    margin-left: 10px;
    width: 240px;
    height: 125px;
    background: #888;
}
#caption {
    font-size: 0.85em;
    margin-left: 10px;
}

And in HTML:

    Column 1

    Column 2

Image

        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
        Maecenas vel vulputate justo.

In my Firefox, it produces this:

A: curtisdf has answered the issue of the image placement but as far as flowing text freely from column 1 to column 2 the easiest way would be to use CSS 3 columns. You can make CSS 3 columns work in browsers that don't support CSS 3 by adding modernizer to your site.
Modernizer: http://www.modernizr.com/
CSS 3 Columns: http://www.w3.org/TR/css3-multicol/


text:
Q: FFMpeg working in command line but not in PHP script I am using FFMpeg to convert videos and it is working fine from the command line. I am using the following command:
ffmpeg -i input.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv output.flv

However, when I run the command using PHP script, the output video is not encoded.
exec("ffmpeg -i input.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv output.flv",$output, $returnvalue);

$returnvalue = 127;

FFMPEG installed path :
[root@localhost ~]# which ffmpeg

/root/bin/ffmpeg

My Script Path :
www.domainname.com/core/foldername/ffmpeg.php
Please provide me solution for the same ASAP.
Thank you.

A: The natural way to run ffmpeg from PHP scripts is something like:
<?php
    echo "Starting ffmpeg...\n\n";
    echo shell_exec("ffmpeg -i input.avi output.avi &");
    echo "Done.\n";
?>

There are several issues that need to be pointed out here. The first one is that, although we specified we want ffmpeg to be executed in the background (using the ampersand operator "&"), PHP script will not continue it's execution until ffmpeg has finished its execution. This is due to the fact, mentioned in one of the notes for the PHP's exec() function that says:

If a program is started with this function, in order for it to
  continue running in the background, the output of the program must be
  redirected to a file or another output stream. Failing to do so will
  cause PHP to hang until the execution of the program ends.

Don't be confused about the example showing shell_exec() call instead of exec(). All of the PHP's Program execution functions share the similar code base and limitations.
So, to work around this issue, we need to do something like this:
<?php
    echo "Starting ffmpeg...\n\n";
    echo shell_exec("ffmpeg -i input.avi output.avi >/dev/null 2>/dev/null &");
    echo "Done.\n";
?>

The part that says ">/dev/null" will redirect the standard OUTPUT (stdout) of the ffmpeg instance to /dev/null (effectively ignoring the output) and "2>/dev/null" will redirect the standard ERROR (stderr) to /dev/null (effectively ignoring any error log messages). These two can be combined into a shorter representation: ">/dev/null 2>&1". If you like, you can read more about I/O Redirection.
An important note should be mentioned here. The ffmpeg command-line tool uses stderr for output of error log messages and stdout is reserved for possible use of pipes (to redirect the output media stream generated from ffmpeg to some other command line tool). That being said, if you run your ffmpeg in the background, you'll most probably want to redirect the stderr to a log file, to be able to check it later.
One more thing to take care about is the standard INPUT (stdin). Command-line ffmpeg tool is designed as an interactive utility that accepts user's input (usually from keyboard) and reports the error log on the user's current screen/terminal. When we run ffmpeg in the background, we want to tell ffmpeg that no input should be accepted (nor waited for) from the stdin. We can tell this to ffmpeg, using I/O redirection again ** "ffmpeg command-line tool in the background would be similar to this:
<?php
    echo "Starting ffmpeg...\n\n";
    echo shell_exec("ffmpeg -y -i input.avi output.avi </dev/null >/dev/null 2>/var/log/ffmpeg.log &");
    echo "Done.\n";
?>

The "-y" option is used to auto-overwrite the output file (output.avi) without asking for yes/no confirmation. If you need the opposite scenario, to auto-cancel the entire process if the output file already exists, then use "-n" option instead.
Wrapper Libraries
Some PHP libraries allow wrapping ffmpeg calls into PHP objects, and give you a nice syntax to work with if you don't like to use the command line. One of these is the actively maintained PHP-FFMpeg. It only requires you to download a recent ffmpeg and ffprobe build apart from installing the PHP components. Then you can run PHP code like this:
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open('video.mpg');
$video
    ->filters()
    ->resize(new FFMpeg\Coordinate\Dimension(320, 240))
    ->synchronize();
$video
    ->save(new FFMpeg\Format\Video\X264(), 'export-x264.mp4')

Of course you need to take care of running such a task in the background. Libraries such as GearmanClient facilitate this.
Note: ffmpeg-php is an extension that is not developed since 2007 (and requires "ffmpeg-0.4.9_pre1 or higher"), which means that you are restricted to use a very old version of ffmpeg, without possibility to update it to the latest version. Since a lot of changes/improvements are being made, inside ffmpeg's code, every day, it makes ffmpeg-php incompatible with the latest ffmpeg.
Read the official documentation for more info.

A: I covered the solution that helps most people that I spoke to about this in another thread.
https://stackoverflow.com/a/38626752/2074077
Essentially, your user needs access to the public directories.
<?php
   exec('whoami'); // Gives you the running user; often it's www-data
?>

Then change your public ownership to the whoami user.
sudo chown -R www-data:root /var/www

A: This happened to me, I found this on another forum; the trick inside of PHP is to give the absolute path to FFMPEG. Try running it like this..
exec("/root/bin/ffmpeg -i input.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv output.flv",$output, $returnvalue);

Something about the fact that php is a different user than you are when typing straight into the command line. I guess it doesn't have the same shortcut list or whatever it is.
Not sure exactly why but it worked for me!
Good luck.


text:
Q: How to save gravity forms total pricing value in database I am working on gravity forms add-on. I am saving all the values of gform fields in my database successfully after form submission using this hook gform_after_submission. Now I want to save the total pricing value but I don't get it I also see that the total pricing value coming from span.
So i search a lot but nothing found except some java script code:
<script type="text/javascript">

     gform.addFilter( 'gform_product_total', function(total, formId) {
        return total;
     } );

</script>

But i don't get that how can i get this value in gform_after_submission hook
So please give me some suggestions

A: check bellow code . it's meet your requirement  .
 function saiful_gf_remove_money_symbol( $s ) {
    return GFCommon::to_number( $s );
}
add_filter( 'saiful_gf_remove_money_symbol', 'saiful_gf_remove_money_symbol' );
add_filter( 'gform_product_info', 'add_fee', 10, 3 );
function add_fee( $product_info, $form, $lead ) {
    $loop_price = 0;
    if( isset( $product_info['products'] ) && count( $product_info['products'] ) > 0 ){
        foreach ( $product_info['products'] as $data ){
            if( isset( $data['options'] ) && count( $data['options'] ) > 0 ){
            foreach ( $data['options'] as $key => $option ) {
                $loop_price += floatval( $option['price'] );
            }
            }
            // Save From Here total amount
            $new_price = apply_filters( 'saiful_gf_remove_money_symbol',$data['price']) + $loop_price ;
        }
    }
    return $product_info;
}


text:
Q: Nav-views in html for ionic and angular I've got this piece of code here that doesn't seem to be displaying quite as I'd like. It seems to be displaying view item2 but not item1 for some reason. Is there any reason in particular for this overlap?

        <ion-nav-bar></ion-nav-bar>
        <ion-nav-view name="item1" animation="slide-left-right"></ion-nav-view>
        <ion-nav-view name="item2" animation="slide-left-right"></ion-nav-view>
    </div


text:
Q: How to display a percific table from sqlserver into a datagridview using combobox in winform so i got a small homework from my teacher during this whole corona thing
First: create a database in SQL with 6 table , lets call it A, B, C, D, E and F
Then: Using VisualStudio to
-Create an MDI form and 3 childs (also call childform into MDI form w/o duplicate) (done)
-In the 1st childform: Display table A into a datagridview and sort the data in that table using a combobox (done)
and the next one is where im stuck at
-In the 2nd childform: create a combobox and a datagridview. Combobox will display (and let you choose) the table in the SQL, and the datagridview will display that percific table.
that is to say: if i select A from the combobox, then the content of table A will be display into the datagridview, B then content of B will be display into the datagridview, and so on.
and if something doesnt make sense to you ... it might be cause english isnt my first language.
and thanks for your help in advance
edit
what i have done so far:
so the combobox, i manually inserted the table name
then in the -lets call it childform2- childform2_load section.i tried the following (multiple times with diff idea in mind) (also just picked up c# a while back so expect dumb idea)
-using dataadapter to "select * from" + combobox.text > doesnt work
-using if to make independant case of childform2_load (each with diff "select * from correspondingtable*) > doesnt seem to work .... (if combobox.text = "A" then ........ *select * from A)
and .. thats all i've manage to do so far.The problem im encountering is:
so the select part .... how would one select the table acording to the combobox's selection ... like ..... if i select A from the combobox then the select command in the "select * from x" . that X would register as A, and register B if i select B. I tried "select * from " + combobox.text and that obviously wouldnt work since the whole select thing must be put in " ". and making diff case of formload using if doesnt work and i think i know why it will never work so ... yeah .....im stuck


text:
Q: Java Script. Add new value to end of an array and shift the rest I would like to know what is the best way to add a new value to an end of an array and let the rest of values to shift with the first element of an array to be deleted.
Example. I got an array:
 int []a = {1, 2, 3, 4, 5, 6};

and after adding 7 i want to have this:
 int []a = {2, 3, 4, 5, 6, 7};

A:

    var a = [ 1, 2, 3, 4, 5, 6];
    console.log('a before:- ', a)
    a.push(7);
    var removed = a.shift(); // Save removed item if you need it

    console.log('a after:- ',a);

A: You can use splice method for remove element

    var arr = [ 1, 2, 3, 4, 5, 6];
    arr.push(7);
    arr.splice(0, 1);
    console.log(arr)

Output
[2,3,4,5,6,7]

for more information read this splice


text:
Q: Excel Graph - Cell with Formula to act as Empty Cell in Graph I'm using a set of monthly data to create a graph (i.e. one number for each month) - the cell I'm using for the graph has a formula so there are not any truly empty cells in the dataset.
I would like for the graph to appear as if the cells that are null due to the formula are actually treated as empty cells so there are no points at zero and no lines connecting the points (similar to Example 1 in the image). The only options I have found thus far are the other 2 examples in the image.
Example 2: using an if statement with ,"" at the end and the chart referring to "Null" fields as zero and the lines connecting to each point
Example 3" using an if statement with ,NA() at the end and the chart referring to these fields as #N/A but the graph is still connecting all of the points and skipping over the fields with #N/A
My goal is for the graph to look like Example 1 but still be able to incorporate the if statement in the table.
Excel Graph Examples

A: Did you consider using another chart type? Since the data is not continuous, maybe you could use Column chart or Scatter chart.
See examples:


text:
Q: Angular - How to access iframe content inside a external domain I'm trying to access an external iframe content inside the parent html, is it possible?
I already trying multiple ways to access those content, take a look at my code below:
Trying to access with ViewChild inside onLoad function of the iframe

Result:

At this moment looks like a good information, but I need to access the data inside #document tag, so I tried the following code at the ngOnInit function.

So in this case, I can't access the body content tag, how can I do this?
And, my final tried, was with this code

With this code I get cross origin error.
My final question is, is it possible access an iframe content in a external domain?
Thanks!


text:
Q: 3 TToolBar's on a TCoolbar band I have TCoolBar with two bands. On the first band I want to put 3 separate TToolBar's in it. I take TToolBar in TCoolBar and set align to alNone but cannot adjust the size of TCoolBar.
I look at my Delphi 5 and it uses TControlBar that the sites tell me to avoid.
I'm installing Speed buttons on my Toolbar with spaces and separators to get flat button effects.
has any one got a good solution to this problem
Thanks in advance.

A: I can't replicate your problem. Here's what I did (exactly):

*

*Started Delphi 7, which gave me a new blank VCL forms application

*Dropped a TCoolBar on the form, and then dropped three TToolBars on the CoolBar.

*Hit Escape to change the designer's focus from the last dropped ToolBar.

*Used Shift+DownArrow to increase the height of the CoolBar so that all the ToolBars were visible.

EDIT: After posting this, I also tried setting the TCoolBar.AutoSize property to True instead of manually resizing as the last step above describes. This also worked properly.
I don't know what

I look at my Delphi 5 and it uses TControlBar that the sites tell me to avoid.

means. What "sites", and why "avoid"? If you're telling us that the Delphi 5 IDE uses TControlBar, IIRC D5's IDE worked just fine.
Also, don't use SpeedButtons on a TToolBar. A TToolBar is designed to hold TToolButtons, which you can put on the TToolBar by right-clicking it and choosing either "New Button" or "New Separator" from the context menu.


text:
Q: Redhat Ansible Tower and Gitlab deployment I am trying to deploy RH Ansible tower and GitLab on the RHEL8.3 server. I am able to deploy GitLab successfully and access it through the browser. But when I am trying to deploy Ansible Tower on the same machine, it is throwing below error. Since both the services are using the same port 80, Ansible Tower installation is failing. How to run both the Gitlab and Ansible Tower on the same machine. I am trying to run Gitlab at https://xx.xx.xx.xx:9443/ and Ansible tower at https://xx.xx.xx.xx:8443/** . Could you please help me?
Aug 13 11:23:46 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:47 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:47 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:48 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:48 tower_centos nginx[893591]: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in us>
Aug 13 11:23:49 tower_centos nginx[893591]: nginx: [emerg] still could not bind() ```

A: After long googling and research, found the below answer and it worked. You need to send the port in the ansible tower deployment
First I deployed Gitlab and then ansible tower. and then run the made

SELinux as permissive

and ran below command

./setup.sh -e nginx_https_port=8443 -e nginx_http_port=85


text:
Q: Snap GPS coordinates to closest line, get line ID, generate and execute URL I have a web map in Portal that has a sidewalk line layer.
Using Portal, I plan to collect sidewalk deficiencies using GPS (on a Microsoft Surface/Windows 10 device).

I would like to add the following functionality to the web map:

*

*Using the device's current GPS coordinates, snap the coordinates to the closest sidewalk line.

*Get the ID of the sidewalk line.

*Generate a URL from the ID and the snapped coordinates.

*Execute the URL.

*

*The URL will open a work order management system form that is pre-populated with the sidewalk ID and the snapped coordinates.

How can I do this in Portal?


text:
Q: NativeScript ListView items disappear after routing back to BottomNavigation component In my NativeScript app, there is a BottomNavigation tab:
const routes: Routes = [
    {
        path: 'tabs',
        component: TabsComponent,
        children: [
            {
                path: 'feed',
                loadChildren: '~/app/pages/feed/feed.module#FeedModule',
                component: NSEmptyOutletComponent,
                outlet: 'feedTab'
            },
            {
                path: 'notification',
                loadChildren: '~/app/pages/notification/notification.module#NotificationModule',
                component: NSEmptyOutletComponent,
                outlet: 'notificationTab'
            },
            {
                path: 'create',
                loadChildren: '~/app/pages/create/create.module#CreateModule',
                component: NSEmptyOutletComponent,
                outlet: 'createTab'
            },
            {
                path: 'profile',
                loadChildren: '~/app/pages/profile/profile.module#ProfileModule',
                component: NSEmptyOutletComponent,
                outlet: 'profileTab'
            }
        ]
    }
];

and within one of those child tabs, there is a RadListView of items:
<ActionBar id="profile-action-bar" title="Notifications"></ActionBar>
<GridLayout>
  <RadListView separatorColor="transparent" class="notification-list" [items]="notificationList"
    (loadMoreDataRequested)="onLoadMoreItemsRequested($event)" loadOnDemandMode="Auto"
    (itemTap)="onNotificationTap($event)">
    <!-- (itemTap)="onGoalTap($event)" -->

    <ng-template let-item="item" let-i="index">
      <ns-notification-item [item]=item [position]=i></ns-notification-item>
    </ng-template>

  </RadListView>
</GridLayout>

The list populates as expected when navigating to that tab, but if you navigate to a child component of another tab and then directly back to the BottomNavigation:
child-component:
this.router.navigate([
     '../tabs'
  ]);

all of the items in the ListView that previously loaded have disappeared...items that had not loaded previously will then begin to populate the list however

A: There is a major difference Router Outlet and Page Router Outlet. On web, when you navigate all components on current route is destroyed and new component for the navigated route is rendered.
With mobile apps, you retain your navigation stack, go back to previous page right where you left. For this purpose you use Page Router Outlet, and to handle Page Router Outlet you need RouterExtensions
When you want to go back to previous page in history, you should call back() method on RouterExtensions.
Updated Playground


text:
Q: How to return all types except a certain type in MongoDB? Let's say that there is a column called colours and it can have values red, blue, and green. I want to retrieve all rows except the ones where the colour is green. How to do this in MongoDB?

A: Hey you can use $ne operator in mongoDB
for reference look here : https://www.educative.io/edpresso/what-is-the-ne-operator-in-mongodb


text:
Q: Regex How to remove last ; from a string? I have this (/\;$/, ""); to remove last ; from a string. but the result is same as input.

A: The following regex should work for you:
\;(?=[^;]*$)

So your replacement code would become:
(\;(?=[^;]*$), "");

Here is an example of the regex working on RegExr.


text:
Q: In bitcoin, how do I calculate the probability for the latest n block/s to be wrong? I learned from here that it takes 6 blocks over a block for its contents to be confirmed.
If so, what is the chance that the latest block's contents are illegitimate? What is the chance for the second to the latest?

A:
...it takes 6 blocks over a block for its contents to be confirmed.

The number of confirmations is directly correlated to the amount of security and finality you require on the transaction. The more confirmations, the more secure it will be. 6 is not a magic number, though it is commonly used.

If so, what is the chance that the latest block's contents are illegitimate? What is the chance for the second to the latest? . . .

The chance that a recent block's contents are invalid are basically zero if you are using the latest Bitcoin software and it has not been tampered with (and there are no bugs). A node will reject an invalid block.
Now, the block could become invalid for a few reasons.

*

*If a longer chain is presented, which can be validated. For example, if another miner has mined 2 blocks which replace the latest block, the node will accept them since there is more proof of work (each block has to be mined with a proof of work). This requires a majority of the network hashpower (computing power) and is also known as a 51% attack. The more blocks have been mined since the transaction occurred (aka number of confirmations), the more secure it will be from being reversed (or removed) in a reorganization or 51% attack. This is very very unlikely for Bitcoin because of how high the network hashrate is. It is much more likely for other coins which have a much lower network hashrate.

*A miner mines another block at nearly the same time (within seconds or less), Chain Reorganization. This could happen because of latency issues, for example. This is also unlikely because a block on average is mined every 10 minutes, and the network propagation is very fast, but probably much more likely than #1. It depends on your node's connection latency relative to the rest of the network.


text:
Q: Winform .net6 Start process without waiting for it to finish Sorry it's my fault. Read my answer below first pls.
It's a winform program (.net6). At the beginning, or when a button on mainform is clicked, a bat file should be run in the background. The bat runs for 10~120 minutes so I do not want to wait for it's completion. So the winform should continue normally, waiting for users' operations.
But it didn't. The black window of the shell stays in front, and the winform starts to response only after the process is finished.
Here are the codes:
public void SomeButtonClicked()
{
    Task task = Task.Run((Action)RunStaticCodeCheck); //Does not work.
}

private static void RunStaticCodeCheck()
{
    _currentCmdFileName = GenerateCmdFile(); //CmdFile is a bat with program-able parameters in it.
    RunCmdAsync(); //Warning from ide: "because this call is not awaited, execution of current method continues before the call is completed." No, the current method does NOT continue.
}

private static string? _currentCmdFileName; //A bat file name generated programmatically.
private static async Task RunCmdAsync()
{
    if (string.IsNullOrEmpty(_currentCmdFileName))
        return;

    var cmdFileName = _currentCmdFileName;
    _currentCmdFileName = null;

    //Run bat.
    var cmdline = new ProcessStartInfo("CMD.exe", $"/C \"{cmdFileName}\"") // The "" does not work.
    {
        UseShellExecute = true //Does not work.
    };

    //Solution 1.
    // await Task.Run(() => { Process.Start(cmdline); }); //Does not work.

    //Solution 2.
    Task.Run(() => { Process.Start(cmdline); }); //Does not work.

    // Solution 3.
    // Process.Start(cmdline); //Does not work.

    // Solution 4.
    // var process = Process.Start(cmdline);
    // if (process != null)
    //     process.WaitForExitAsync(); //Does not work.
}

Solutions tried:
Start process and allow caller to end without waiting for process to finish says that UseShellExecute = true should make the Process.Start() running in background. But it did not.
C# Threading/Async: Running a task in the background while UI is interactable says Task.Run((Action) MyFunction); without waiting will make it continue, but not.
How to start an application without waiting in a batch file? says blank in path might make the bat file wait or something like that. I tried using "" to wrap the cmd file name, and it did not help.
Ironically, I found many questions asked how to wait for a process/cmdline until finished. I deleted everything from those answers, but my program is still waiting!
I think there might be 2 solutions: Run a method async-ly without waiting; let the Shell start a bat file without waiting.
Any help? Thanks~

A: As you have used async on async Task RunCmdAsync()you should use await inside the function at least once.

A: You can try to run the Bat File in another Thread, It will prevent the form from freezing.
using System;
using System.Diagnostics;
using System.Threading;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press any Key to Start the Thread ...");
            Console.ReadKey();

            // Creating the new thread
            Thread batStart = new Thread(new ThreadStart(RunBat));
            batStart.Start(); // Starting it

            Console.WriteLine("Bat File Started! ....");
            Console.ReadKey();
        }

        static void RunBat()
        {
            // make new process info with bat file
            ProcessStartInfo bat = new ProcessStartInfo(@"E:\test.bat");
            // to hide the window
            bat.WindowStyle = ProcessWindowStyle.Hidden;
            Process.Start(bat); // starting the prcoess
        }
    }
}

A: After more work, I realized that it was already working( going on without waiting). But the task it started has 10 threads (totally 12 in my laptop), so it occupied most of the CPU and the main thread was very slow as if it's waiting.
To make it work better I made a mechanism:

*

*Instead of to start the task immediately, leave a "todo" flag.

*Go on until everything is ok (for me, when the winform is idle).

*Check if there is a "todo" flag.

*If yes, start the task now and leave a "doing" flag.

*Keep checking if the task is finished, until we get the result.

*Clear all flag when you want.

The name in the following code is an identity to distinguish different tasks.
        public static class SimpleFlow
        {
            public enum Steps
            {
                Todo, Doing, Done
            }
            public static void CreateTag(Steps step, string name)
            {
                var tagFileName = TagFileName(step, name);
                if (!File.Exists(tagFileName))
                    File.Create(tagFileName);
            }

            public static bool ExistsTag(Steps step, string name)
            {
                var tagFileName = TagFileName(step, name);
                return File.Exists(tagFileName);
            }

            public static void DeleteTag(Steps step, string name)
            {
                var tagFileName = TagFileName(step, name);
                if (File.Exists(tagFileName))
                    File.Delete(tagFileName);
            }

            public static void ClearTags(string name)
            {
                foreach (var step in Enum.GetValues<Steps>())
                {
                    DeleteTag(step, name);
                }
            }

            private static string TagFileName(Steps step, string name)
            {
                var tagFileName = $@"{Directory.GetCurrentDirectory()}\_{step}_{name}.tag";
                return tagFileName;
            }
        }


text:
Q: Configure virtual host in Wildly 12 I want to configure virtual host on Wildly 12. I tried to configure this:
standalone.xml
<subsystem xmlns="urn:jboss:domain:undertow:5.0">
            <buffer-cache name="default"/>
            <server name="default-server">
                <http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true"/>
                <https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" enable-http2="true"/>

                <host name="mypackage" alias="mydomain.biz,www. mydomain.biz" default-web-module="My_site.war">
                    <location name="/" handler="welcome-content"/>
                    <filter-ref name="server-header"/>
                    <filter-ref name="x-powered-by-header"/>
                    <http-invoker security-realm="ApplicationRealm"/>
                </host>

                <host name="default-host" alias="localhost">
                    <location name="/" handler="welcome-content"/>
                    <filter-ref name="server-header"/>
                    <filter-ref name="x-powered-by-header"/>
                    <http-invoker security-realm="ApplicationRealm"/>
                </host>

            </server>
            <servlet-container name="default">
                <jsp-config/>
                <websockets/>
            </servlet-container>
            <handlers>
                <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
            </handlers>
            <filters>
                <response-header name="server-header" header-name="Server" header-value="WildFly/11"/>
                <response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow/1"/>
            </filters>
        </subsystem>

jboss-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
    <context-root>/</context-root>
    <virtual-host>mypackage</virtual-host>
</jboss-web>

Bu when I open the domain nothing happens. Can you give me some advice how I can configure it?


text:
Q: Is there any algorithm pattern to protect any content in the web to ensure I am the first one who created it? A few years ago there was this hacker (don't remember who he was) that full disclosed a vulnerability in a given system, but to make sure nobody took credit for that, he created some kind of PGP key.
What I understood at the time is that he created a key to ensure he was the one who discovered it, but didn't disclosed who he was actually, just created some mechanism to be able to prove that he was the one who created the disclosure.
Ok. I get how algorithms and cryptography works. But I still don't understand how you can create a key to protect a given content disclosed in the web to prove you are the one who created it first! It is just words!
Is it really possible? What should be the process to ensure you can empirically prove it? Did I understood it correctly or I probably missed something regarding this case?
I hope this question is specific enough, basically it is just how to protect a content that you created in the web (a paragraph, a code, a word, etc.) and make sure you are the one who created it first, inside a given context.
With my knowledge I don't see how that is possible, but I am intrigued if there is a practical way to do it. Is there?

A: In days of old, scientists would publish anagrams of their work to be able to say "I thought of this idea." (look at the 'history' and 'establishment of priority' sections)  The thing is, they wanted to be able to take credit for it, but also give other scientists to publish their results if they had other ideas without building on the original idea.
For example Gallileo published SMAISMRMILMEPOETALEVMIBVNENVGTTAVIRAS which was an anagram of altissimvm planetam tergeminvm obseravi which translated from Latin reads "I observed the highest planet in threefold shape".  He got it wrong - Saturn (the 'highest' planet known at the time) isn't built of three parts.  Fifty years later, Christiaan Huygens published AAAAAAA CCCCC D EEEEE H IIIIIII LLLL MM NNNNNNNNN OOOO PP Q RR S TTTTT UUUUU which in Latin is Annulo cingitur, tenui, plano, nusquam cohaerente, ad eclipticam inclinato which translates to "It is surrounded by a thin flat ring that does not touch it and is inclined against the ecliptic."
While those are historical bits now of interest, they show an important concept back then - providing a 'hash' that is easy to say "this hash encodes this text."  It is easy to go from the known text to the anagram or the hash, but hard to figure out what it is if you don't know what it is in the first place.
With the modern mechanisims, we have other ways of doing hashes.  Many of them are very closely related to cryptography.  There is the cryptographic hash function.  The idea being, still, it is easy to go from the text you know to the hash, but hard to go from the hash to the text you don't know.
And so, if you have a program you could publish a hash of the program that does something and then when you are ready to disclose it (possibly after the company fixes it or a period of time later), you can publish the actual code and everyone can see that, yes, this code matches that hash.

A: You can do that quite easy. If you have a plaintext text, secret key S and public key P you do S(text) and get the cipher.
Now you can publish cipher and P but not S. Therefore, everyone can decrypt the cipher with P by doing P(cipher). If you now want to prove, that you are the one who created the cipher (and therefore the original text), you can either publish S, or - if you don't want anyone to know S - you can create another S("I was really the one who found the text first") and publish it. Because there is no way to create a cipher that is decrypted with P(cipher) that results in some meaningful text.
That is how you can prove it.

A: It's possible to hash the data you wish to timestamp and turn it into a Bitcoin address.  This is known as trusted timestamping.  By making a small payment (a satoshi, or 0.00000001 BTC) to it, the payment is stored on the blockchain along with the address you paid to.
Since only the hash is stored on the Bitcoin blockchain, no one can tell what data you stored, but given the pre-hashed data you can prove the data was created prior to the block that contains the payment made to that address.

A: A very simple way to establish that you are the first one to publish something, without revealing who you are immediately but having the option to do this later:

*

*Publish it on a well known public source (there everyone can see that you published it)

*In this publication, add a line: Originally published on dd/mm/yyyy by the owner of xxx@gmail.com

No need to encrypt anything.
Of course there is the chance that you don't want to publish your results yet. In that case you need to encrypt everything except the line with the email address. However, now it may be harder to get this published on a renowned site.

A:
I probably missed something regarding this case?

I think the bit you are missing is a trusted entity.
When you hash the file with the content you want to certify, you can show to the world that you are the owner of this document, without disclosing this document. This is all very well, but how can you prove you had this document at some specific time in the past ?
This is what Trusted Timestamping is about. Here is an extract from wikipedia:

The technique is based on digital signatures and hash functions. First
  a hash is calculated from the data. A hash is a sort of digital
  fingerprint of the original data: a string of bits that is different
  for each set of data. If the original data is changed then this will
  result in a completely different hash. This hash is sent to the TSA*.
  The TSA concatenates a timestamp to the hash and calculates the hash
  of this concatenation. This hash is in turn digitally signed with the
  private key of the TSA. This signed hash + the timestamp is sent back
  to the requester of the timestamp who stores these with the original
  data (see diagram).
(*) Time Stamping Authority

I have been using Universign's Timestamping Service, which has a nice set of tools to make the whole operation easy to perform. There are plenty of companies offering similar services.
It is interesting to note that, as @JoelFan mentioned, that bitcoin provides a way to get a trusted entity that is not centralized (why should I trust anyone ?). The bitcoin chain provides a timeline (you can prove one document incrusted in the bitcoin chain was created before another further down in the chain). To my understanding, however, you would still miss the effective date and time of the event.
Also, Trusted Timestamping is a valid reference in litigation.

A: This is a different take on valenterry's answer.
Here's how you would do it using PGP:
Generate a public/private key pair.

*

*You keep the private key and you make sure it stays secret.

*You encrypt your idea with your public key: P(idea)

*You put P(idea) somewhere that is trusted(not by you, but in general) and will log the time.

*When you need to prove you made the idea first, you get the timestamp from when you stored the data, and you decrypt your data with your secret key.  S(P(idea)) => idea

This method doesn't require releasing your secret key, which in general is a bad idea.  Granted, you can always make a new PGP key pair - it doesn't cost anything, but you shouldn't be recklessly handing out secret keys if you want to be credible.
The hardest part is proving the time, but in terms of documenting a vulnerability, we don't need a 100% bullet-proof-and-verifiable-in-court solution, we just need something that's 'good enough'.  The logs of a cloud storage provider(dropbox, rackspace, google, etc) is probably good enough, assuming they implement a secure service.
It's also worth noting that being the first one with an idea and timestamping it has never meant that you were the first person to think of the idea. If someone thought of it before you but never registered the idea with a timestamping mechanism, then they can't prove they made it before you.  So, if we're trying to figure out who made it first, and all we know is the time you came up with it, then we have to assume you came up with it first(the other person could be spewing lies).

A: Ugh, so many of these answers are missing the point.
1) What the hacker did had nothing to do with encryption.
2) What the hacker did had nothing to do with time (the time stamp, etc).
What the hacker did was Publicly Sign the release document. When you PGP sign something (an e-mail, a word document, etc), you create a hash which is the sum of the hash of the document being signed, and your own private key. Now, to prove that you are the creator of the document, you just need to "show" the private key, as presumably only the author knows it. Cryptographically speaking, you can "show" that you are in possession of the private key without actually showing the key itself.
So, in effect, he digitally signed the document. The only person who can copy that signature, is someone with his private key.
There is nothing to say that the document was made today, or yesterday, or was the first instance of it to exist ever. No amount of hashing timestamps or whatever will change that.
The only way to digitally sign something IN TIME, is to use the blockchain a la bitcoin. There could be no digital currency without time verification - the fact that person A sent money to person B is irrelevant unless we know when.
You cannot go into a shop with a piece of paper and say "my mum sent me $100 once. I would like to buy some bread", because a receipt of a transaction doesn't mean the money still belongs to you. You might have given it to someone else in the interim.
The blockchain solves this issue by getting a large number of people (bitcoin miners) to all agree on the fact that the transaction happened at a certain time (and then by recording that time in the blockchain forever).


text:
Q: What's the difference between fdisk -l and df -h? In my ubuntu system, I want to have a look about my system disk info. When I use fdisk -l without sudo, I get nothing. But with sudo fdisk -l, I only get a device /dev/sda1, but when I use df -h, I get so many devices, like /dev/sda2, /dev/sda4 and so on. What is the difference between such disk operations?
# fdisk -l
WARNING: GPT (GUID Partition Table) detected on '/dev/sda'! The util fdisk doesn't support GPT. Use

Disk /dev/sda: 6000.1 GB, 60000069312512 bytes
255 heads, 63 sectors/track, 729466 cylinders, tatal 11718885376 sectars
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
   Device Boot     Start          End      Blocks   Id  System
/dev/sda1              1   4294967295  2147483647+  ee  GPT

# df -h
Filesystem     Size  Used Avail Use% Mounted on
/dev/sda2      457G  2.0G  432G   1% /
udev            16G  4.0K   16G   1% /dev
tmpfs          6.3G  236K  6.3G   1% /run
none           5.0M     0  5.0M   0% /run/lock
none            16G     0   16G   0% /run/shm
/dev/sda4      5.0T  604G  4.2T  13% /var

A: It says it right there:

WARNING: GPT (GUID Partition Table) detected on '/dev/sda'! The util fdisk doesn't support GPT.

Your /dev/sda is using a GUID Partition Table.  Your version of fdisk doesn't support GPT, so all it can see is the fake MBR partition that takes up your entire disk.  Try using gdisk or another program that supports GPT.

A: df -h displays all of the mounted partitions.

fdisk -l displays all of the partitions that exist on your system. The partitions are displayed by their device's names. For example: /dev/sda, /dev/sdb or /dev/sdc

A: fdisk checks the MBR on the disk device. df lists filesystems present in the OS.


text:
Q: for loop returning a number between 0 and 3 every cycle I have this piece of code that runs a simple for loop:
const InvType = ["Hat", "Face", "FaceAccessory", "HairAccessory", "BackAccessory", "NeckAccessory", "FrontAccessory", "WaistAccessory", "Gear"]

var Prom = new Promise((resolve, reject) => {
        var Inv = []

        for (let i = 0; i < InvType.length; i++) {
            https.get('https://inventory.roblox.com/v1/users/111138402/assets/collectibles?assetType=' + InvType[i] + '&sortOrder=Asc&limit=100', (resp) => {
                let data = '';

                // A chunk of data has been received.
                resp.on('data', (chunk) => {
                    data += chunk;
                });

                // The whole response has been received. Print out the result.
                resp.on('end', () => {
                    var arrayLength = JSON.parse(data).data.length;
                    for (var v = 0; v < arrayLength; v++) {
                        Inv.concat(JSON.parse(data).data[v])
                        console.log(i)
                    }
                    if (i >= 9) {
                        resolve(Inv)
                    }
                });

            }).on("error", (err) => {
                console.log("Error: " + err.message);
            });
        }
    })

I would like for this to resolve the promise once the Inv table has been filled, that way I do not move onto the next step of the code before the required data has been gathered.
for some reason the "i" variable in this loop always prints out as either 0, 1, or 3, and so the promise is never resolved. I am not the best at node, and do not know why this would be happening.

^example of output

A: You're creating a new binding for i every iteration of the loop here:
for (let i = 0; i < InvType.length; i++) {

When the code runs, there are a bunch of different is, not just one.
Since i never gets reassigned (except in the loop declaration), i is always 0 through 8, and never 9 inside the loop; once the declaration's i is 9, iteration stops. The loop body will always see an i between 0 and 8.
You could declare i outside the loop, or with var, but that wouldn't fix things because then i would be at its final value the first time the if (i >= 9) line is encountered.
Instead of messing with indicies, promisify https.get and use Promise.all, and flatten the response arrays with .flat()
const get = (url) => new Promise((resolve, reject) => {
    https
        .get(url, (resp) => {
            let data = '';
            resp.on('data', (chunk) => {
                data += chunk;
            });
            resp.on('end', () => {
                resolve(data);
            });
        })
        .on('error', reject);
});

const allProm = Promise.all(
    InvType.map(str => get('https://inventory.roblox.com/v1/users/111138402/assets/collectibles?assetType=' + str + '&sortOrder=Asc&limit=100'))
)
    .then(allResults =>
        allResults.map(resText => JSON.parse(resText).data).flat()
    )
    // .catch(handleErrors);


text:
Q: PHP - get random image from multiple folders I am trying to figure out the best way, using PHP, to pull a random image from multiple sub-folders on my site. I would use the RecursiveDirectoryIterator to iterate through the subfolders and extract images, but am wondering how to handle the randomisation and how to do it efficiently. Any advice on how to go about this?

A: Create a random number for the iteration endpoint (while $i < 10). Before this you can create another random session to choose the directory.

Read all images into an array then pick a random index.

A: function get_images($root) {

    $r = array();
    foreach(glob("$root/*") as $n) {
        if (is_dir($n)) {
            $r = array_merge($r, get_images($n));
        } else {
           $r[] = $n;
        }
    }

    return $r;
}

$files = get_images('foo');
shuffle($files);
echo $files[0];

A: Load all the full $paths into an $array and select mt_rand(0, count($array)-1).
You might want to cache your list as long as it does not change, to avoid re-iterating over your directories.


text:
Q: Finitely presented group in which every element is conjugate to its square Does there exist a nontrivial finitely presented group in which every element is conjugate to its square? Is this an open problem?
Motivation: Jahren proved in [Geom Dedicata (2010)] that if $M$ is a closed manifold of dimension $\ge 5$ such that $\pi_1(M)$ has an element not conjugate to its square, then the smooth pseudoisotopy space for $M$ is not connected.
Finitely generated examples exist: Osin  constructed a f.g. infinite torsion free group in which all nontrivial elements are conjugate.

A: One is naturally led to consider the simple case, and I wonder if Graham Higman's 1951 examples might suffice.  In J. Lond. Math. Soc. 26 (1951), 61-64, Higman gives examples of groups presented using 4 generators with 4 relations.  (One can replace 4 by a larger integer.)  According to these relations, each of the four generators is conjugate to its square.  Of course, this is no guarantee that every group element has this property.  Maybe someone can add why Higman's examples do or do not answer the question.


text:
Q: Multiple vimeo pattern for magnific popup question to those who customized magnific popup - how do I combine multiple vimeo patterns for iframe type in Magnific Popup plugin?
Here is the video urls I need to play and their patterns:

https://player.vimeo.com/external/xxxxx.hd.mp4

patterns: {
    ...
    vimeo: {
       index: '//vimeo.com/',
       id: '/',
       src: '//player.vimeo.com/external/%id%'
    },
    ...
}

https://vimeo.com/xxxx

patterns: {
    ...
    vimeo: {
       index: 'vimeo.com/',
       id: '/',
       src: '//player.vimeo.com/video/%id%?autoplay=1'
    },
    ...
}

Each pattern works individually, but the question is how to use them together?
Thanks

A: The solution was to use id as a function:
patterns: {
      vimeo: {
        index: 'vimeo.com/',
        id: function(src){
           if (src.indexOf('external') > -1) {
              return 'external/' + src.substr(src.lastIndexOf('/')+1, src.length);
           } else {
              return 'video/' + src.substr(src.lastIndexOf('/')+1, src.length);
           }
        },
        src: '//player.vimeo.com/%id%?autoplay=1'
      },
    },


text:
Q: Transmission-daemon - dangling symlink and dpkg error After some attempts to install Transmission I couldnt get the webUI working. This made me want to make a fresh start by removing all my transmission files. I encounter the following on my Ubuntu 14.10 Server.
chris@homeserver:~$ sudo apt-get remove transmission-daemon
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
  libnatpmp1
Use 'apt-get autoremove' to remove it.
The following packages will be REMOVED:
  transmission-daemon
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 606 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 142422 files and directories currently installed.)
Removing transmission-daemon (2.84-0ubuntu0.14.10.1) ...
invoke-rc.d: dangling symlink: /etc/rc2.d/S01transmission-daemon
dpkg: error processing package transmission-daemon (--remove):
 subprocess installed pre-removal script returned error exit status 102
invoke-rc.d: dangling symlink: /etc/rc2.d/S01transmission-daemon
dpkg: error while cleaning up:
 subprocess installed post-installation script returned error exit status 102
Errors were encountered while processing:
 transmission-daemon
E: Sub-process /usr/bin/dpkg returned an error code (1)

The same error keeps popping up even if I want to reinstall of force install transmission-daemon.
My knowledge of Ubuntu and Linux is very limited I am a beginner. Can someone explain what is going on and how to fix this?

A: probably some previous version of the package was broken. I'd suggest deleting the file...
sudo rm /etc/rc2.d/S01transmission-daemon


text:
Q: Amazon S3 CORS PUT fails I'm trying to upload a large file (1.5GB) to Amazon S3 by using the REST Api and HTML5 file slicing. Here's how the upload code looks like (code stripped down for readability):
File.prototype.slice = File.prototype.webkitSlice || File.prototype.mozSlice || File.prototype.slice;

var length = u.settings.chunk_size; // 6MB
var start = chunk * length;
var end = Math.min(start + length, u.file.size);

var xhr = new XMLHttpRequest();
var path = "/" + u.settings.key;

path += "?partNumber=" + chunk + "&uploadId=" + u.upload_id;

var method = "PUT";
var authorization = "AWS " + u.settings.access_key + ":" + signature;
var blob = u.file.slice(start, end);

xhr.upload.addEventListener("progress", progress_handler, true);
xhr.addEventListener("readystatechange", handler, true);
xhr.addEventListener("error", error_handler, true);
xhr.addEventListener("timeout", error_handler, true);

xhr.open(method, u.settings.host + path, true);

xhr.setRequestHeader("x-amz-date", date);
xhr.setRequestHeader("Authorization", authorization);
xhr.setRequestHeader("Content-Type", u.settings.content_type);
xhr.setRequestHeader("Content-Disposition", "attachment; filename=" + u.file.name);

xhr.send(blob);

chunk_size is 6MB. After a chunk finishes uploading, the next one follows, and so on. But sometimes (every 80 chunks or so), the PUT request fails, with e.type == "error", e.target.status == 0 (which surprises me), and e.target.responseText == "". After a chunk fails, the code re-attempts to upload it, and gets the exact same error. When I refresh the page and continue the upload (the same chunk!), it works like a charm (for 80 chunks or so, when it gets stuck again). Here's how the request looks in chrome dev tools:

Any ideas why this might happen, or how to debug something like this?
EDIT: Here is the OPTIONS response:

A: I finally found the issue by sniffing packets: there are two issues:

*

*for PUT requests that get a 4xx (didn't test for other non-2xx responses), the xhr request returns as aborted (status = 0); still haven't found an explanation for that, check out Why does a PUT 403 show up as Aborted?

*Amazon S3 responded with a 403 that said RequestTimeTooSkewed, because my signatures are generated when the upload starts, and after 15 minutes (the timeout that triggers the RequestTimeTooSkewed error), it fails, and the signatures have to be regenerated. That 403 error is never seen in the dev tools console or by the js code, because of the first problem..
After regenerating the signatures, everything works like a charm.

A: Did you verify whether browser is making any 'OPTIONS' request. If yes what is the response headers.


text:
Q: For someone to + verb
8 minutes for this guy to fall down to earth yet it takes one hour for my Uber eats to be delivered

I saw this comment on a video on YouTube and I'd like to know if when I use 'for someone to + verb', whether I'd have to use 'to + verb' after the subject or not?


text:
Q: pigeonhole principle problem 3 Prove: For every group of 1009 positive integers, there exist 2 integers of that group, that their sum or difference divide with 2014 without residue.
where do I start?

A: The remainders when $2014$ divides a number is given by the set
$$S = \{0\} \bigcup \{1007\}\displaystyle\bigcup_{r=1}^{1006}\{r,2014-r\} = \bigcup_{k=0}^{1007} S_k$$
where $S$ is written as a union of $1008$ mutually disjoint sets, where $S_0=\{0\}$, $S_{1007} = \{1007\}$ and $S_k = \{k,2014-k\}$. Since there are $1009$ numbers there exists two numbers say $a_1,a_2$ whose remainders fall in the same of the $1008$ sets say some $S_k$. If the remainders of $a_1,a_2$ are the same, then their difference is divisible by $2014$. Else if the remainders are different, then their sum is divisible by $2014$.

A: Hint: Think about the possible residues when dividing the integers by 2014 (i.e. 0 to 2013). When do two of these residues sum to 0? When do two of these residues lead to a difference of 0? How many different residues could you have?

 Let $N$ be the set of the residues of the 1009 positive integers modulo 2014. Suppose there are two integers with equal residues, i.e., $n_1 \equiv n_2$ mod $2014$. Then $n_1-n_2\equiv0$ mod $2014$. Then assume no two numbers have equal residues (or any number has residue 0). Assume that for any $n_1, n_2\in N$, it is not the case that $n_1+n_2\equiv 0$ mod $2014$. Then for each $n\in N$, its unique inverse mod 2014 is not in $N$. Since there are 1009 unique residues in $N$, there must be 1009 residues not included. However $1009 + 1009 = 2018 > 2014$. This implies that the number of residues of 2014 is greater than 2014, which is a contradiction.