text:
Q: Directly adding text into innerHTML without using innerText Is it possible to add string inside innerHTML without having to use innerText?
like this:

var sentence="hello there";

document.querySelector(".container").innerHTML='';
document.querySelector(".thing").innerText=sentence;
<!DOCTYPE html>

but without having to use innerText,
Maybe the code would look something like this:
var sentence="hello there";

document.querySelector(".container").innerHTML=''+raw(sentence)+'';

A: I don't see anything seriously wrong with your current approach. If you want to avoid the repetition of creating an element with a particular class and then have to select it again right after you append it, you can consider creating an element instead of an HTML string:

var sentence="hello there";

document.querySelector(".container")
  .appendChild(document.createElement('span'))
  .textContent = sentence;


text:
Q: Passing a value for an optional fortran parameter that will return false for present() I would like to find a way to get a fortran method to take some value for an optional parameter that will make the argument not appear to be present in the method that has been called.
Here is a reduced test case which distills the problem in the fortran code:
MODULE FortranOptional
  USE ISO_C_BINDING

CONTAINS
  SUBROUTINE optionaltest(scalar)
    REAL(8), OPTIONAL, INTENT(IN) :: scalar

    IF (PRESENT(scalar)) THEN
      print *, "scalar is present: ", scalar
    ELSE
      print *, "scalar is NOT present"
    END IF

  END SUBROUTINE optionaltest

  SUBROUTINE optionaltest_c(scalarC) BIND(C, NAME="optionaltest_c")
    REAL(C_DOUBLE), OPTIONAL, INTENT(IN) :: scalarC
    REAL(8) :: scalar

    IF (PRESENT(scalarC)) THEN
      print *, "scalarC is present: ", scalarC
      scalar = scalarC
    ELSE
      print *, "scalarC is NOT present"
      ! Can I do something here to make scalar appear not present in optionaltest()?
    END IF

    CALL optionaltest(scalar)
  END SUBROUTINE optionaltest_c
END MODULE FortranOptional

And the associated C++ test code:
extern "C"
{
void optionaltest_c(double*);
}

void testMethod()
{
    double v = 5.3;
    optionaltest_c(0);

    std::cout << "\n";

    optionaltest_c(&v);
}

Which produces:
scalarC is NOT present
scalar is present:    6.9118029901527309E-310

scalarC is present:    5.2999999999999998
scalar is present:    5.2999999999999998

Is there any way I can set the scalar variable based on the presence of scalarC that will make it appear to not be present when scalarC is not present?
Some constraints:

*

*I'd prefer to avoid if statements involving different calls to optionaltest, as the real version of the subroutine has several optional parameters that may be specified or not on an individual basis, resulting in a combinatorial explosion.

*I cannot bind the optionaltest subroutine directly as a C function, as the real version of the subroutine has assumed shape optional arguments, which are not C-compatible in the version of Fortran I am using.

*I cannot modify the signature of optionaltest.

A: In the subroutine optionaltest_c the variable scalar is a local one.  As you note, a local variable has no concept of optional-ness.
For completeness, if it's just a matter of passing the optional dummy argument down from optionaltest_c to optionaltest, then
call optionaltest(scalarC)

would suffice.  That is, an optional dummy argument may be an actual argument for a procedure where the corresponding dummy argument is also optional, regardless of its presence.
So, if instead you need to do some form of manipulation, what to do?1  I note that you have intrinsic assignment between the dummy argument and local variable.
Under Fortran 2008 there is a sensible option: have the local variable allocatable.  If a variable is not allocated and is an actual argument for an optional non-allocatable dummy then it is treated as not present:
  subroutine optionaltest_c(scalarC) bind(C)
    type(type1), optional, intent(in) :: scalarC
    type(type2), allocatable :: scalar  ! Local, conformable with scalarC

    if (PRESENT(scalarC)) scalar=scalarC
    ...

    call optionaltest(scalar)
  end subroutine optionaltest_c

[You may need to provide alternative ways of allocating scalar and setting its value, depending on your compiler support.]
With scalarC present, scalar becomes allocated and has its value. Then on the call, the dummy argument is present.  With scalarC not present, scalar is left not allocated and on the call the dummy argument is absent.
This works just as well for arrays as for scalars.
Now, I see that you mention gfortran 4.4.7, so it's possible this approach won't work.  I'll let someone else answer with a specific way in that case, but this is perhaps still worth documenting for the benefit of others/after upgrade.

1 That may not be the case in this question if c_double has value 8, but we'll consider anyway.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Расположить элементы "listview" в строку Задача в следующем:
в listview сделать список запущенных процессов как в диспетчере задач, в общем должно быть так: иконка процесса, затем его название, на следующей строке тоже самое только следующий просцесс, я использую такой тестовый код:
imgList->Images->Add(System::Drawing::Icon::ExtractAssociatedIcon(System::Diagnostics::Process::GetCurrentProcess()->MainModule->FileName));

listView1->LargeImageList = imgList;
listView1->SmallImageList = imgList;

listView1->Items->Add("myProcess", 0);

Вывожу для примера название моего процесса и его иконку, выводится вот что: иконка, а под ней названием процесса, что мне нужно изменить - нужно чтобы была иконка, а текст с названием процесса правее и чтобы следующий элемент располагался на следующей строке, а не правее.

A: Кому интересно - делается так:
listView1->View = View::Details;


text:
Q: Prove some member of the sequence $7, 77, 777, 7777, \dots$ is divisible by $2019$.
Prove that some member of the sequence $7, 77, 777, 7777, \dots$ is divisible by $2019$.

So far I have figured that as $2019$ is divisible by $3$, then if one of the terms of the sequence
$$
a_{n} = 7\left(\frac{10^{n}-1}{9}\right)
$$
is divisible by $2019$ it is also divisible by $3$. Hence the number of digits in the solution will be a multiple of $3$, i.e. $777, 777777, 777777777, \dots$
I'm not too sure where to go from here any help would be appreciated.

A: Consider $2020$ terms of the sequence $\{7, 77, 777, \ldots, \underbrace{777...777}_{2020} \}$.
Due to pigeonhole principle, at least two of terms have same value by $\mod 2019$:
$$
\underbrace{777...777}_a \equiv \underbrace{777...777}_b \equiv x (\bmod 2019).
$$
Then (for $a<b$):
$$
\underbrace{777...777}_b - \underbrace{777...777}_a = \underbrace{777...777}_{b-a}\underbrace{000...000}_a \equiv 0 (\bmod 2019),
$$
hence
$$
\underbrace{777...777}_{b-a} \equiv 0 (\bmod 2019),
$$
since $GCD(10,2019)=1$.

A: It suffices to find a positive integer $n$ such that $7(\frac{10^{n}-1}{9})$ is divisible by $2019$. So
$$7(\frac{10^{n}-1}{9})\equiv 0\pmod{2019}$$
$$10^{n}\equiv1\pmod{2019}$$
By Euler's theorem we have $10^{\phi(2019)}=10^{1344}\equiv 1\pmod{2019}$, so $n=1344$ will do.
You can also have $n\equiv 0 \pmod{224}$.

A: Inspired by a book titled "A walk through combinatorics" by Miklos Bona on page 2 and page 3.
I prove that an even stronger statement is true, in fact, one of the first 2019 elements of the sequence is divisible by 2019.

*

*I start my proof by assuming that its contrary is true. It means that none of the first 2019 elements is divisible by 2019. When being divided by 2019, their remainders must be in a closed set of $[1,2018]$.

*As there are 2018 possible remainders for 2019 elements, there are at least two elements with the same remainder.

*Let $A_x$ and $A_y$ (with $x<y$) be the $x$-th and $y$-th elements with the same remainder.

*For certain integers $\kappa_x$, $\kappa_y$, and $r$,  I can represent $A_x$, $A_y$, and $A_y-A_x$ as follows.
\begin{align}
    A_x &= 2019\kappa_x +r\\
    A_y &= 2019\kappa_y +r\\
    A_y-A_x&= 2019 (\kappa_y-\kappa_x)  \\
   \end{align}
It means that $A_y-A_x$ is divisible by 2019.  It is not the end of proof.

*The first $(y-x)$ digits of $A_y-A_x$ are all 7. They are followed by $x$ zeros. Therefore, $A_y-A_x$ can be written as $A_y-A_x=\underbrace{777\cdots777}_{(y-x) \,\text{digits}}\times 10^x$.

*As $10^x$ is not divisible by 2019 then  $\underbrace{777\cdots777}_{(y-x) \,\text{digits}}$, which is the $(y-x)$-th element of the given sequence, must be divisible by 2019. It is contradictory to my assumption in the beginning.

*The proof by contradiction is complete. Some elements of the given sequence are divisible by 2019.


text:
Q: color picker doesn't show in my code I need to use a color picker so I use this:
http://www.eyecon.ro/colorpicker/#about
In my page html I create this:
<input id="colore_sfondo_generale" type="text" class="form-control" value="">

and my jquery code is:
$('body').on('click','#colore_sfondo_generale',function(){
            $('#colore_sfondo_generale').ColorPicker({
                    onSubmit: function(hsb, hex, rgb, el) {
                        $(el).val(hex);
                        $(el).ColorPickerHide();
                    },
                    onBeforeShow: function() {
                        $('#colore_sfondo_generale').ColorPickerSetColor(this.value);
                    }
                })
                .bind('keyup', function() {
                    $('#colore_sfondo_generale').ColorPickerSetColor(this.value);
                });

        });

In my code this is not work and I don't know why. Anyone can help me?

A: This should not come inside a click event handler.
Just attach it directly and it should work as expected:
$(document).ready(function() {
    $('#colore_sfondo_generale').ColorPicker({
        //options here...
    });
});

The .click() event is handled by the picker itself, and when you attach it in every click, you're disrupting its events.

A: I think you're making things hard for yourself
Would it not be easier to do it like this
http://jsbin.com/lucetuqucu/edit?html,js,output

$('#colorSelector').ColorPicker({
 color: '#0000ff',
 onShow: function (colpkr) {
  $(colpkr).fadeIn(500);
  return false;
 },
 onHide: function (colpkr) {
  $(colpkr).fadeOut(500);
  return false;
 },
 onChange: function (hsb, hex, rgb) {
  $('#colorSelector div').css('backgroundColor', '#' + hex);
 }
});
<!DOCTYPE html>

<link rel="stylesheet" href="http://www.rachelgallen.com/css/colorpicker.css" type="text/css" />
    <link rel="stylesheet" media="screen" type="text/css" href="http://www.rachelgallen.com/css/layout.css" />
    <title>ColorPicker - jQuery plugin</title>


text:
Q: Database good practice: how to make users, which belong to dynamic groups I'd like to ask you about good design practice:
I want to design database which will have that kind of functionality:
There will be and users table with login and passwd
Groups table with id, name and description columns
And privilages table with privilages (admin, bigboss, user category A, user category B, user category C, ...)
I want to have possiblity to have one user belong to one groups: how to make it, as a column "group_id" in table users or rather a table users_groups with colums user_login and group_id?
I want to have possibility to give every user from every to none privilage, probably in table groups_privilages
How to make it, so it will be easly implemented using java, java ee, java server faces, mysql, glassfish and jdbc realm? How to make good relation between users and privilages? Are my tables even good to be used?
Admin can create, edit, delete groups at runtime, admin is not mutable.

A: As it is strictly a one to one relationship put the permission on the user table, as it pertains strictly to the user. If you ever think that it may become a one to many relationship, put it in its own table with userId and groupId. Have the groupId and description in a lookup table.


text:
Q: Adding screenshot to TestNG I am running some tests using testNG and Selenium. The test data comes from a CSV file. In each step it is possible to take a screenshot of the page. I am trying to add this screenshot to the testNG HTML report (emailable report).
I am using this to add the img element;
Reporter.log("
");

Now this works partially, because it is in fact adding this to the report as you can see in the screenshot below. But the HTML code does not seem to work.

Is the path to the image file wrong? I think so, but I am not sure how I can fix this.
UPDATE:
This is from the source code of the HTML report. Apparently its not even parsing it as HTML???

<img src="file://C:\Users\myUSername\Desktop/screenshots/step 1_enter username_baseline.png" alt=""/></img>

A: To have the screenshot embedded in the index.html report I used relative paths as:
System.setProperty("org.uncommons.reportng.escape-output", "false");

Reporter.log(
"" +
    "
");

In this case, the Screenshot is displayed in the OutputReport not in the main index page with the stacktrace of the fails which is a bit anoying. But at least images and links are working.
I edit myself to add the complete solution, setting the property "org.uncommons.reportng.escape-output" as false we are passing the html code instead of the text.
I recommend to use ReportNG where the screenshots are attached correctly to the test failure with the complete stack trace:

A: Ok apparantly I was looking at the wrong file. I was looking at the emailable-report.html while reporter.log sends everything to index.html. In the index.html file everything is working fine using the code in my first post.

A: if you want to save your image both as file(jpg/png etc ..)  and base64 format try below complete code .
Base64 format is recommended for emailable reports .
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

//Saving image to current working directory , you can ignore this step if dont want to save file
FileUtils.copyFile(src, new File("./demotest.png"));
String fileName = System.getProperty("user.dir") + "/demotest.png";
Reporter.setEscapeHtml(false); //This need to be set as false

byte[] fileContent = FileUtils.readFileToByteArray(new File(fileName));
String encodedString = Base64.getEncoder().encodeToString(fileContent);

String path = "";

Reporter.log(path);

or if you want only Base64 file format then ..
String src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);

String path = "";

Reporter.log(path);

See Output:


text:
Q: convert custom loss function output y test and y pred to numpy arrays Hi i am compiling using custom loss function in keras , but it is throwing error
If Y_test and Y_pred is  a binary categorical variable
than i have to create dummy variables for Y_test and Y_pred.
here need to convert tensor object to Numpy array.
Below is the custom function
def keras_custom_loss_function(Y_true, Y_pred):
    #convert Y_test and Y_pred into Numpy arrays
    Y_pred  = np.array(Y_pred)
    Y_test  = np.array(Y_test)

    #create Dummy variable for Y_test and Y_pred
    en_Y_test = pd.get_dummies(Y_test)
    en_Y_pred = pd.get_dummies(Y_pred)
     ...
     # DO further operations

#during compiling it is throwing below error
model.compile(loss=keras_custom_loss_function, optimizer=opt, metrics=['accuracy'])

TypeError: Cannot iterate over a tensor with unknown first dimension.
Please help how to create numpy arrays from tensor objects(Y_test,Y_pred) generating from compile function
thanks in advance
Edit:1
We are trying to compute below logic in Loss function
Below is the example
suppose Y_test and Y_pred  values are from keras compile function are
Y_true = pd.Series([2,1,2,2,1,2,2,2,2,1,2,2,2,2,2,2,2,2,2,1]
Y_pred = pd.Series([2,2,2,1,1,2,2,2,1,1,2,2,2,2,2,2,2,2,2,2]

than  custom loss function  having parameters Y_test,Y_Pred
def keras_custom_loss_function(Y_true, Y_pred):
        #convert Y_test and Y_pred into Numpy arrays
        Y_pred  = np.array(Y_pred)
        Y_test  = np.array(Y_test)

        #create Dummy variable for Y_test and Y_pred
        en_Y_test = pd.get_dummies(Y_test)
        en_Y_pred = pd.get_dummies(Y_pred)
         # DO further operations

        #Change the column names
        en_Y_true.columns = ["D1","D2"]
        en_Y_pred.columns = ["Y1","Y2"]

        #Create dataframe and append
        Custm_df = pd.concat([en_Y_true, en_Y_pred], axis=1)

        #convert datatypes
        Custm_df['D1'] = Custm_df['D1'].astype('int32')
        Custm_df['D2'] = Custm_df['D2'].astype('int32')
        Custm_df['Y1'] = Custm_df['Y1'].astype('int32')
        Custm_df['Y2'] = Custm_df['Y2'].astype('int32')

        Custm_df['D1-Y1']  = Custm_df['D1'] -Custm_df['Y1']
        Custm_df['D2-Y2']  = Custm_df['D2'] -Custm_df['Y2']

        loss = Formula based on (D1,D2,Y1,Y2)

        return loss

Iam  getting below error while compiling complete
TypeError                                 Traceback (most recent call last)
<ipython-input-22-22841b8add1e> in <module>
     26
     27 #model.compile(loss=custom_loss, optimizer=opt, metrics=['accuracy']) # loss 'adam' ,y_predicted
---> 28 model.compile(loss=keras_custom_loss_function, optimizer=opt, metrics=['accuracy']) # loss 'adam' ,y_predicted

~\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\engine\training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    227         #                   loss_weight_2 * output_2_loss_fn(...) +
    228         #                   layer losses.
--> 229         self.total_loss = self._prepare_total_loss(masks)
    230
    231         # Functions for train, test and predict will

~\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\engine\training.py in _prepare_total_loss(self, masks)
    690
    691                     output_loss = loss_fn(
--> 692                         y_true, y_pred, sample_weight=sample_weight)
    693
    694                 if len(self.outputs) > 1:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\losses.py in __call__(self, y_true, y_pred, sample_weight)
     69         scope_name = 'lambda' if self.name == '<lambda>' else self.name
     70         with K.name_scope(scope_name):
---> 71             losses = self.call(y_true, y_pred)
     72             return losses_utils.compute_weighted_loss(
     73                 losses, sample_weight, reduction=self.reduction)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\losses.py in call(self, y_true, y_pred)
    130             Loss values per sample.
    131         """
--> 132         return self.fn(y_true, y_pred, **self._fn_kwargs)
    133
    134     def get_config(self):

<ipython-input-21-e80cbe1c715d> in keras_custom_loss_function(Y_true, Y_pred)
     39
     40     #label_numpy = Y_pred.eval()
---> 41     en_Y_pred = pd.get_dummies(Y_pred)
     42     print("second after")
     43     en_Y_true.columns = ["D1","D2"]

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\reshape\reshape.py in get_dummies(data, prefix, prefix_sep, dummy_na, columns, sparse, drop_first, dtype)
    864                                  sparse=sparse,
    865                                  drop_first=drop_first,
--> 866                                  dtype=dtype)
    867     return result
    868

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\reshape\reshape.py in _get_dummies_1d(data, prefix, prefix_sep, dummy_na, sparse, drop_first, dtype)
    872     from pandas.core.reshape.concat import concat
    873     # Series avoids inconsistent NaN handling
--> 874     codes, levels = _factorize_from_iterable(Series(data))
    875
    876     if dtype is None:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in __init__(self, data, index, dtype, name, copy, fastpath)
    227             elif (isinstance(data, compat.Iterable)
    228                   and not isinstance(data, compat.Sized)):
--> 229                 data = list(data)
    230             else:
    231

~\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in __iter__(self)
    484     if shape[0] is None:
    485       raise TypeError(
--> 486           "Cannot iterate over a tensor with unknown first dimension.")
    487     for i in xrange(shape[0]):
    488       yield self[i]

TypeError: Cannot iterate over a tensor with unknown first dimension.


text:
Q: Can air plasma be used as a fuel source in ion propulsion? After doing some calculations (using conservation of energy, $F=qE$, $E_k = \frac{1}{2} mv^2$ etc), I came up with the formula for the exit velocity, $v$, of a mass, $m$, with charge, $q$, being accelerated through a potential difference, $U$, to be
$v = \sqrt{\frac{2qU}{m}}$.
Assuming air is 78% $N_2$ and 22% $O_2$, and each molecule of $N_2$ and $O_2$ gains a single positive charge (e.g. By bombarding the molecules with high energy electrons, or by energizing them with UV or Xray radiation so that they loose an electron) , the charge of 1 gram of air can be calculated,
$q=\frac{0.78}{28}\times6.022\times10^{23}\times e + \frac{0.22}{32}\times6.022\times10^{23}\times e \approx 3346.5 C$
Using the velocity formula where $U=10V$,
$v=\sqrt{\frac{2\times3346.5\times10}{0.001}}\approx8181ms^{-1}$
Thrust, $T$ is given by
$T = \frac{dm}{dt}v$
$\frac{dm}{dt}=0.001kgms^{-1}$ and $v=8181ms^{-1}$, thus $T=0.001\times8181=8.181N$
My question is whether there are any ways in which air could be ionised so as to produce a meaningful amount of thrust force, while also using a realistic amount of energy.


text:
Q: Compute an approximation of some cubic polynomial over an extension of the $3$-adics Let $K = \mathbb{Q}_3(\sqrt[4]{-3},i)$ and $L = K(\alpha)$
where $$
\alpha = \frac{(1-\zeta_3)(1-\sqrt{-7})}{6}
$$
and $\zeta_3 \in K$ is a primitive 3rd root of unity.
Furthermore, let $v$ be the valuation on $L$ with $v(3)=1$.

Question: Is there a unit $\epsilon \in L^\times$ satisfying the equation $\epsilon^3 \equiv \frac{1}{4}$ modulo an element of valuation $\frac{9}{4}$?

Ideas and Approaches:

*

*I tried to use Hensel's Lemma on the polynomial $f(X)= 4X^3-1$. However, since $f'(X) = 12X^2$ vanishes modulo $3$, it cannot be applied.

*By using Magma, my colleague found out that $\alpha^3 \in K$, i.e. the minimal polynomial of $\alpha$ over $K$ is $x^3-\alpha^3$.

*It is $v(\alpha) = -\frac{1}{2}$, so $\tilde{\alpha} = (1-\zeta_3) \alpha$ is a unit in $L$ since $v(1-\zeta_3)=\frac{1}{2}$. Maybe this can be used for constructing an appropriate $\epsilon$.

Now I ran out of ideas. Could you please help me with this problem? Thanks in advance!
Edit: After skimming through the answers, I noticed that I took the wrong element $\alpha$. In this post, I changed it to the one I intended to use. I will check the answer here more thoroughly though.

A: *

*The uniformizer of $L$ is $(-3)^{1/4}$

*If $\epsilon^3 = \frac{1}{4}\bmod (-3)^{9/4}$ for some $\epsilon\in L$ then $\epsilon-1$ is a root of $$(x+1)^3-1/4 =x^3+3 x^2+3x+3-9\bmod (-3)^{9/4}$$

This implies that $v(\epsilon-1)=1/3$ which is a contradiction  since $L/\Bbb{Q}_3$ is tamely ramified with ramification degree $4$, no element of $L$ has valuation $1/3$

Also note that $$v{1/3\choose n}= v(\prod_{k=0}^{n-1} (1/3-k))-v(n!) = -n-\sum_{k\ge 1} \lfloor n/3^k  \rfloor\le -n-n\frac{3^{-1}}{1-3^{-1}}$$ thus $(1+x)^{1/3}=\sum_n {1/3\choose n}x^n$ converges for $v(x)>1+\frac1{3-1}$ and hence $\epsilon^3=1/4\bmod 3^2$ gives that $(4\epsilon^3)^{1/3}\in L, 4^{1/3}\in L$ which is a contradiction since no element of $L$ has valuation $1/3$. The convergence of the binomial series can be stated in term of Hensel lift, when $f'(a)=0\bmod \pi$  we need to use the higher derivatives.

A: First, notice that $\sqrt{-7}$ is already in $\Bbb Q_3(i)$, since $X^2+7\equiv X^2+1\pmod3$: the latter factors in $\Bbb Q_3(i)$, so the former must as well. Thus $L=K$. This field has ramification index $e=4$ over $\Bbb Q_3$, and the residue-field extension degree is $f=2$. For a prime element, we can take $\pi=\sqrt[4]{-3}$.
Second, since you're talking about units, and $2$ is one such, finding an $\epsilon$ of the type you want is equivalent to finding a unit $\delta$ with such that $v(\delta^3-2)\ge\frac94$: just take $\epsilon=\delta/2$.
We may assume that such a $\delta$ will be $\equiv-1\pmod\pi$: otherwise multiply by a cube root of unity. Thus we write $\delta=-1+\rho$ with $v(\rho)>0$, and expand $\delta^3-2=-1+3\rho-3\rho^2+\rho^3-2$. Let's look carefully:
$$
\delta^3-2=-3+3\rho-3\rho^2+\rho^3
$$
In case $v(\rho)<\frac13$, the $v$-value of the whole sum is $3v(\rho)<1$, while if $v(\rho)>\frac13$, the $v$-value of the whole is $1$, the minimum valuation being taken on at the first term in the sum. Of course these two are the only possible cases, since there are no elements of $v$-value $1/3$. In other words, it's not possible for $v(\delta^3-2)$ to take on the value $9/4$, similarly for $v(\epsilon^3-\frac14)$.


text:
Q: No module named 'setuptools' I want to install xlwings, but it can't find setuptools.
I install the setuptools already.
the path seems has no problem.
how can I do?

C:\>pip install setuptools
Collecting setuptools
  Using cached https://files.pythonhosted.org/packages/db/3c/1065553af43e5f388cb5ae96f44867470063a2d04c02551104dcb12794bd/setuptools-41.5.1-py2.py3-none-any.whl
Installing collected packages: setuptools
  WARNING: The scripts easy_install-3.7.exe and easy_install.exe are installed in 'c:Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed setuptools-41.5.1

C:\>pip install xlwings
Collecting xlwings
  Using cached https://files.pythonhosted.org/packages/bb/08/9719e055e57d4475e00e6a5a8c96a808433fe12f534ae818e90ed856b607/xlwings-0.16.0.tar.gz
    ERROR: Command errored out with exit status 1:
     command: 'c:\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\temp\\pip-install-fmk5dya0\\xlwings\\setup.py'"'"'; __file__='"'"'C:\\temp\\pip-install-fmk5dya0\\xlwings\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\temp\pip-install-fmk5dya0\xlwings\pip-egg-info'
         cwd: C:\temp\pip-install-fmk5dya0\xlwings\
    Complete output (3 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    ModuleNotFoundError: No module named 'setuptools'
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

C:\>path
PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Scripts\;C:\;C:\Users\AppData\Local\Programs\Python\Launcher\;C:\Users\AppData\Local\Microsoft\WindowsApps;C:\Lib;C:\Windows\SysWOW64\Lib

A: Eventually I turned to use Anaconda to solve the problem.


text:
Q: Matlab: Split string into multiple strings at the points where '_' exists I have a string which is this:
a = 'Sound_impro_Act'

I want to divide this into multiple strings which are the words that are seperated by '_' and assign these to different variables.
The end result will be like this:
b = 'Sound'

c = 'impro'

d = 'act'

Thanks.

A: You may also use regexp which is faster than strsplit
a = 'Sound_impro_Act';
parts = regexp(a,'_','split');
[b,c,d] = deal(parts{:});

The last line comes from @Divakar's answer. Lots of thanks!

A: Use strsplit and then deal to put them into different variables -
split_strings = strsplit(a,'_')
[b,c,d] = deal(split_strings{:})

A: strsplit function can do it for you:
An example:
a = 'Sound_impro_Act';
b= strsplit(a, '_');

now you can access all splited values using b(1), b(2), b(3)


text:
Q: Activerecord map to array I'm trying to take everything out of my Users table and send it to mail chimp for subscription.
I need to go from User.all to
[{:email => {:email => "example@domain.org"},
  :merge_vars => {:FNAME => "First name", :LNAME => "Last name"}
}]

I'm trying to do this with map but I'm struggling, any ideas of the cleanest way of doing this?

A: subscription_array = User.all.collect do |user|
 {
  :email => {:email => user.email},
  :merge_vars => {:FNAME => user.first_name, :LNAME => user.last_name}
 }
end

A: users_array = []
User.all.find_each {|u| users_array << {:email => u.email, :merge_vars => {:FNAME => u.first_name, :LNAME => u.last_name} }

I chose to use find_each is it's a more efficient way of loading your collection.
http://api.rubyonrails.org/classes/ActiveRecord/Batches.html


text:
Q: Java - throw and catch in same method I have problem with understand existing code. I would like to know how Java manage throw exception and catch it in same method. I can't find it in other question so I preapare example. What will be output of run below code in Java?
public static void main(String [ ] args) {
     try{
         System.out.println("1");
         method();
     }
     catch(IOException e) {
         System.out.println("4");
     }
}

public static void method() throws IOException {
     try {
         System.out.println("2");
         throw new IOException();
     }
     catch(IOException e) {
         System.out.println("3");
     }
 }

It will be 1 2 3 or 1 2 4?

A: Well, let's check:
    public static void main(String [ ] args) {
         try{
             System.out.println("1"); //<--When your code runs it first prints 1
             method();  //<--Then it will call your method here
         }
         catch(IOException e) { //<---Won't catch anything because you caught it already
             System.out.println("4");
         }
    }

public static void method() throws IOException { //<--Your Signature contains a throws IOException (it could throw it or not)
     try {
         System.out.println("2");  //<--It will print 2 and thow an IOException
         throw new IOException(); //<--now it throws it but as you're using a try catch it will catch it in this method
     }
     catch(IOException e) {//the exception is caught here and it so it will print 3
         System.out.println("3"); //<--Prints 3
     }
 }

Now, if you remove your catch clause in the method() method for something like this, now it will catch it for you:
    public static void main(String [ ] args) {
         try{
             System.out.println("1"); //<--When your code runs it first prints 1
             method();  //<--Then it will call your method here
         }
         catch(IOException e) { //<---It will catch the Exception and print 4
             System.out.println("4");
         }
    }

public static void method() throws IOException { //<--Your Signature contains a trows IOException (it could trhow it or not)
         System.out.println("2");  //<--It will print 2 and thows an IOException
         throw new IOException();
 }

Remember, a try-catch means: CATCH IT OR THROW IT (someone else will catch it, and if not it will go to the main and stop your process).

A: 1 2 3 will be the output.
not 4 because the exception is caught in the method's try-catch block


text:
Q: Understanding Forwarding unit I am new to this subject and am having trouble understanding this topic.
Suppose I have the following circuit to control the forwarding of a MIPS pipeline processor:

So the forwarding control will be in the EX stage because the ALU forwarding multiplexors are found in that stage.
These are the control values for the forwarding multiplexors :

The goal here is to deal with the data hazards and to pass proper values early from the pipeline registers to ALU rather than writing for the WB stage to write the register file.
This is the truth table that I have for this circuit :

[
How exactly are the output signals ForwardA and ForwardB selected when EX/MEM and MEM/WB are 1 and WBHazardRt is 1 ?


text:
Q: Components dont rerender when redux store is updated I have a connected top level component :
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import store from './store/store';
import { Provider } from 'react-redux';
import LifePlanner from './lifePlanner';
import { getContainer, setContainer } from './store/plannerSlice'

class App extends React.Component {

  componentDidMount() {
    fetch("/lp/top-layer", { mode: 'cors' }).then((response) => {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }
      response.json().then((data) => {
        store.dispatch(setContainer({ name: "Root Container", children: data.data.containers }));
        this.setState({ container: getContainer(store.getState()) })
      });
    }
    ).catch(function (err) {
      console.log('Fetch Error :-S', err);
    });
  }

  render() {
    let c = this.state.container;
    if (c.name) {
      return <LifePlanner container={c} />
    }
    return
Loading
;
  }
}

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>
  ,
  document.getElementById('root')
);

LifePLanner then calls an ExpandedCard component, psasing the container down and then again to a ImageCard component where I put an onClick, which changes the openContainer item in the store
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import {  setContainer } from '../store/plannerSlice'
import store from '../store/store';

const useStyles = makeStyles({
  media: { height: 250 },
});

export default function SectionCard({ id, name, image, description, children }) {
  const classes = useStyles();
  const handleClick = () => {
    fetch(`/lp?${id}`, { mode: 'cors' }).then((response) => {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }
      response.json().then((data) => {
        store.dispatch(setContainer({ name , children: data.data.containers }));
      });
    }
    ).catch(function (err) {
      console.log('Fetch Error :-S', err);
    });
  }
  return (
    <Card className={classes.root} onClick={()=>handleClick()}>
      <CardActionArea>
        {image &&
          <CardMedia
            className={classes.media}
            image={image}
            title="Contemplative Reptile"
          />}
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2">
            {name}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {description}
          </Typography>
        </CardContent>
      </CardActionArea>
      {(children && children.length > 0) &&
        <CardActions>
          <Button size="small" color="primary">
            Expand (Contains {children.length} items)
          </Button>
        </CardActions>
      }
    </Card>
  );
}

Heres my reducer too:
import { createSlice } from '@reduxjs/toolkit';

export const slice = createSlice({
  name: 'containers',
  initialState: {
    openContainer: {}
  },
  reducers: {
    setContainer: (state, action) => {
      let payload = action.payload;
      state.openContainer  = {...payload}
    },
  },
});

export const getContainer = state => {
  return state.containers.openContainer
};

export const { setContainer } = slice.actions;

export default slice.reducer;

None of the components get their componentWilLReceiveProps triggered or get notified of the change, but the store does get the change from the click

A: Yes, there's several issues here.  The primary problems are:

*

*You're interacting with the store directly in our components.  Instead, you should be using the React-Redux APIs like connect and useSelector/useDispatch to read data from the store and dispatch actions in your components.  That way they'll update properly when the store state gets updated.

*You shouldn't be copying data from props to state just to render with it.  Copying data from props to state is almost always the wrong approach.

A few other notes:

*

*Conceptually, think of actions as "events that happened", not "setters".  Instead of calling that reducer/action setContainer, call it something like containerDataLoaded.

*You don't need to spread {...payload} in that reducer, since the object was constructed when you dispatched the action.  You can simplify that line to state.openContainer = action.payload.

*You might want to consider using async/await syntax instead of promise chaining.


text:
Q: How to turn off update for Wireless card I'am a new Linux Ubuntu user my version is 12.10. After updating the OS my wireless turned off, becouse I use Linux for 10 days I dont know how to fix it. Then I reinstalled Linux and want to ask you is there a way to use the updater but Without installing new drivers for wlan or other hardware.

A: I'm not sure if 12.10 has synaptic, if it doesn't, you can sudo apt-get install synaptic. Here are some alternatives I can think of:

*

*Go to the synaptic package manager. Settings > Repositories > Updates, check Only notify me about updates. Then, when you see the Updates available icon, click it and only check the updates you want to install -- don't check the drivers update. This works in Debian, it should work on Ubuntu too, although I'm not sure what process manages updates.

*On synaptic, find the driver's packages, check them, Edit > Lock Version. Apparently this won't prevent aptitude and apt-get of installing new versions, so check this answer.
I only noticed after I answered it, but I think your question is a duplicate of this one.


text:
Q: Objective-C and C interoperability We're going to have to write a C library and this library has to be accessible from Objective-C. Now I don't know anything about Objective-C so I wonder how simple Objective-C <-> C interoperability is. Is that as simple as including the C header in the Objective-C code and linking to the library? Is there anything special I'm supposed to do (like the extern "C" bit with C++)?

A: Objective-C is a strict superset of GNU C (note, this is not the same as ISO C90).

A: Objective-C is a strict superset of C. You don't need to use extern "C" or anything like that.


text:
Q: Fix broken firefox window.innerheight/width within p5 I am currently trying to make a image out of numbers. The code is the following:
let grid = [];
const gridSize = 8;
let img;

function preload() {
    img = loadImage('CR-Logo.jpg');
}

function setup() {
    const myCanvas = createCanvas(windowWidth, windowHeight/2);
    myCanvas.parent('canvasDiv');
    background(0);
    textSize(gridSize);
    noStroke();
    textFont("Courier");

    img.resize(min(width, height), 0);
    imageMode(CENTER);
    image(img, width/2, height/2);

    loadPixels();

    for(let i = 0; i < width/gridSize; i+=1) {
        for(let j = 0; j < height/gridSize; j+=1) {
            if(pixels[(i * gridSize + j * gridSize * width)*4] > 20 && Math.random() > 0.1) {
                grid.push([i*gridSize, j*gridSize]);
            }
        }
    }

    background('#41413f'); //for gray screen
    //background(255); //for white screen
}

function draw() {
    for(let i = 0; i < 4; i+=1) {
        //fill(0,255,65); //matrix color
        //fill(0); //black
        fill(255); //white
        if(grid.length <= 0) {
            noLoop();
            break;
        } else {
            let pos = grid.splice(grid.length * Math.random(),1)[0];
            text(Math.round(Math.random()), pos[0], pos[1]);
        }
    }
}

This should load an image, resize it to the smaller value of width and height and then paint numbers, where the image was not black ... it works fine in every browser, except for Firefox, where the following "bug" was encountered not only by me:

*

*https://github.com/processing/p5.js/pull/1494/commits/f641dcdb3650a4b09782a59a9223921894a48a2a

*Wrong value for window.innerWidth during onload event in Firefox for Android?

*etc.

I am not a Javascript or p5 professional, and would like to know, what a quick and dirty way might be, to fix this and not have the wrong values there, as this just breaks my code and the image is basically painted outside of the canvas.
Thank you!


text:
Q: vb.net check the value of each column for only the 1st row datatable I want to check the first row only of a data table.  I want to verify that the right name is in the right column.  The first row has header name and they have to be in the right order. for example I want to check the first row and the first column to check that it has "First Name"
If I do the following it give me the right column data but it gives me the 2nd row not the first.  I don't get it since I am asking for row 0 and col 0.
Dim ExcelData As DataTable

field = ExcelData.Rows(0)(0).ToString()

(actually I will  want to do a IF to check this column.   first wanted to see what value is there before I code it all )


text:
Q: Sort objects in List by String (dd/mm/yyyy)? Can someone help me with this? I can't find any example..
I've created a Java Class called Subtaks with multiple fields. And i'm trying to sort a list of Subtasks. Firt I'm sorting the list alphabetically with one field called status; but if this field is the same i'm trying to sort it by another String field that containt a date with this format:
String resolutionDate = "18/09/2014"

I've implemented this method to sort it:
@Override
public int compareTo(Subtask o) {
    if (this.status.equals(o.status))
        return o.resolutiondate.compareTo(this.resolutiondate);
    else
        return this.status.compareTo(o.status);
}

A: I assume you want to sort by date so you'd either have to manually extract year, day and month and compare them or parse the date and compare the parsed dates.

For the first approach, you could use something like this:
String  resolutionDateReordered = resolutionDate.replaceAll("(\\d+)/(\\d+)/(\\d+)","$3$2$1");

And then compare resolutionDateReordered. This assumes that the parts of the date have equal length, i.e. 2-digit day and month and 4 digit year and would reorder the string "18/09/2014" to "20140918", which then would be sortable by date.
This could be optimized by creating the pattern once and reusing it, e.g.
Pattern p = Pattern.compile( "(\d{2})/(\d{2})/(\d{4})" ); //pattern slightly changed to expect 2-digit day and month and 4-digit year.
and in your compare() method:
String resolutionDateReordered = p.matcher( resolutionDate ).replaceAll(  "$3$2$1" );

As for the second approach you do something like this:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date resolutionDateParsed = df.parse( resolutionDate );

And then compare resolutionDateParsed using Date's compareTo() method.
Depending on the size of the list, the first or second approach might be faster, but YMMV. For example, on my machine sorting a list of date strings having your format using the optimized version of the string reordering is approx. twice as fast as parsing first and comapring the dates, with 3.5 seconds vs. 7.4 seconds for 100k entries.

A: First you convert your String value of date("dd/mm/yyyy") to type of Date(java.util)
public class YourClassName implements Comparable<YourClassName> {

    ....

    //return -1 for less than, 0 for equals, and 1 for more than
    public compareTo(Subtask subTask) {
        int result = 0;
        result = getResolutionDate().compareTo(subTask.getResolutionDate());
        if (result != 0)
        {
            return result;
        }
        result = getStatus().compareTo(subTask.getStatus());
        if (result != 0)
        {
            return result;
        }
        ...
    }
}

A: Here is the SubTask class:
package com.test.main;

import java.util.Date;

public class Subtask implements Comparable<Subtask> {

    private String status;
    private Date resolutionDate;

    public Subtask(String status, Date resolutionDate) {
        super();
        this.status = status;
        this.resolutionDate = resolutionDate;
    }

    public String getStatus() {
        return status;
    }

    public Date getResolutionDate() {
        return resolutionDate;
    }

    @Override
    public int compareTo(Subtask o) {
        int compareToIgnoreCase = status.compareToIgnoreCase(o.getStatus());
        return compareToIgnoreCase==0?resolutionDate.compareTo(o.getResolutionDate()):compareToIgnoreCase;
    }

}

Main method:
public static void main(String args[]){
        List<Subtask> arrayList = new ArrayList<>();
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        arrayList.add(new Subtask("test1", instance.getTime()));
        instance.set(Calendar.MONTH, 11);
        arrayList.add(new Subtask("test1", instance.getTime()));
        instance.set(Calendar.MONTH, 5);
        arrayList.add(new Subtask("test1", instance.getTime()));
        Collections.sort(arrayList);

        for (Subtask subtask : arrayList) {
            System.out.println(subtask.getResolutionDate());
        }
    }


text:
Q: Java - Returning Multiple Integers to an Array I am trying to return multiple integers to an array through a void. Something like this:
public class abc {
    public static void main(String[] args) {

        int[] evenNumbers = { findEvenNumbers(0, 10); };

    }

    public static void findEvenNumbers(int min, int max) {

        for(int i = min; i <= max; i++) {

            if((i % 2) == 0) {

                return i;

            }

        }

    }

 }

I know that will produce quite a few errors, but is there a way I can return multiple integers to an array (sort of like the program above)? Thanks!

A: This will do the trick, I think:
import java.util.Arrays;

public class Abc {
    public static void main(String[] args) {

        int[] evenNumbers = findEvenNumbers(0, 10);
        // should really do something with the result:
        System.out.println(Arrays.toString(evenNumbers));
    }

    public static int[] findEvenNumbers(int min, int max) {
        int[] result = new int[max - min + 1];
        int n = 0;
        for(int i = min; i <= max; i++) {
            if((i % 2) == 0) {
                result[n++] = i;
            }
        }
        if (n < result.length) {
             result = Arrays.copyOf(result, n);
        }
       return result;
    }

}

Changes from your original code:

*

*Changed class name to start with upper case (Java coding convention; does not affect behavior).

*Changed findEvenNumbers to return an int[] instead of void.

*Changed initialization expression for evenNumbers to account for findEvenNumbers returning an array instead of an int value.

*Changed the body to store even numbers in array results and return results (after adjusting length).

A: Change:
public static void findEvenNumbers(int min, int max)

to
public static int[] findEvenNumbers(int min, int max)

this means you are intending to return something from the function (void means nothing will be returned). In this case, an array of ints will be returned.
create and return an array from the method like this:
int[] arr = new int[numberOfElements];
//put stuff in array like this:
arr[0] = 1;
arr[1] = 2;

return arr;

A: Noete: You cannot return anything from a function with void return type
   public static Integer[] findEvenNumbers(int min, int max)
    {
       List<Integer> lists = new ArrayList<Integer>();

      for(int i = min; i <= max; i++) {

        if((i % 2) == 0) {

            lists.add(i);

        }

    }
 return (Integer[])(lists.toArray());
}

A: You can try this :
    private static ArrayList <Integer> evenNumbers = new ArrayList<Integer>();

    public static void findEvenNumbers(int min, int max) {

        for(int i = min; i <= max; i++) {

            if((i % 2) == 0) {

                evenNumbers.add(i);
            }

        }
   }

   public static void main (String [] args){

       findEvenNumbers(0, 10);

       Iterator iterator = evenNumbers.iterator();

       while(iterator.hasNext()){

          System.out.println(iterator.next());
       }

   }

I recommend you to make classes which will make what you want instead of putting everything in the main class, where you have the main method :)


text:
Q: Flutter : problem with dropdown_formfield 0.1.1 plugin when put data to second menu Hello I am working with flutter drop down menu. First menu is for location and second is for sublocation. It is working when clicking on first location but when changed to second and clicking on second location this error appears:

my variable
//location
  String _myLocation ;
  List data = List();
  //sublocation
  String _mySublocation  ;
  List data2 = List();

function for location
 getLocation() async {
   try{
      var res = await http
        .get(Uri.encodeFull("http://iraqdoctors.com/api/locations"), headers: {"Accept": "application/json"});
    setState(() {
    var resBody = json.decode(res.body);
      data = resBody;
    });
    return "Sucess";
   }catch(e){

   }
  }//get location

function for sublocation
getSublocation() async {
    try{
      var res2 = await http
        .post(Uri.encodeFull("http://iraqdoctors.com/api/getlocationflutter"),
         headers: {"Accept": "application/json"},
         body: {
            "cityname":"$_myLocation",
          }
         );
    setState(() {
      var resBody2 = json.decode(res2.body);
      data2 = resBody2;
    });
    return "Sucess";
    }catch(e){

    }
  }//get sublocatio

Location dropdown
DropDownFormField(
                   hintText: 'اختر المدينة',
                    titleText: null,
                  value: _myLocation,
                  dataSource: data,
                  onChanged: (value) {
                    setState(() {
                      _myLocation = value;
                      getSublocation();
                    });
                  },
                  textField: 'city',
                  valueField: 'city',
                ),

Sublocation dropdown
 DropDownFormField(
                  hintText: 'اختر المنطقة',
                  titleText: null,
                  value:  _mySublocation,
                  dataSource: data2,
                  onChanged: (value) {
                    setState(() {
                      _mySublocation = value;
                     });
                  },
                  textField: 'state',
                  valueField: 'state',
                ),

A: Replace your _myLocation Dropdown with following code and it will work for you:
DropDownFormField(
    hintText: 'اختر المدينة',
    titleText: null,
  value: _myLocation,
  dataSource: data,
  onChanged: (value) async { // <-- added async.
      _myLocation = value; // <-- updated value outside of setState((){})
      await getSublocation();  // <-- Fetched data outside of setState((){})
    setState(() {  // <-- When every thing is ready setState is called
    });
  },
  textField: 'city',
  valueField: 'city',
),

I hope this helps, in case of any doubt please comment. If this answer helps you then please accept and up-vote the answer.


text:
Q: Using google s2 library - find all s2 cells of a certain level within the circle, given lat/lng and radius in miles/km What S2Region should i use and how should i use it to get all cells within a circle given a latitude, longitude and a radius in miles/km using google's s2 library?
S2Region region = ?
S2RegionCoverer coverer = new S2RegionCoverer();
coverer.setMinLevel(17);
coverer.setMaxCells(17);
S2CellUnion covering = coverer.getCovering(region_cap);

Thanks

A: Here's a C++ example from the npm package s2geometry-node. The code was copied from viewfinder/viewfinder.cc
const double kEarthCircumferenceMeters = 1000 * 40075.017;

double EarthMetersToRadians(double meters) {
  return (2 * M_PI) * (meters / kEarthCircumferenceMeters);
}

string CellToString(const S2CellId& id) {
  return StringPrintf("%d:%s", id.level(), id.ToToken().c_str());
}

// Generates a list of cells at the target s2 cell levels which cover
// a cap of radius 'radius_meters' with center at lat & lng.
vector<string> SearchCells(double lat, double lng, double radius_meters,
                           int min_level, int max_level) {
  const double radius_radians = EarthMetersToRadians(radius_meters);
  const S2Cap region = S2Cap::FromAxisHeight(
      S2LatLng::FromDegrees(lat, lng).Normalized().ToPoint(),
      (radius_radians * radius_radians) / 2);
  S2RegionCoverer coverer;
  coverer.set_min_level(min_level);
  coverer.set_max_level(max_level);

  vector<S2CellId> covering;
  coverer.GetCovering(region, &covering);
  vector<string> v(covering.size());
  for (size_t i = 0; i < covering.size(); ++i) {
    v[i] = CellToString(covering[i]);
  }
  return v;
}

A: I had encountered the same task and solved it with the usage of S2RegionCoverer.getCovering(S2Region region, ArrayList<S2CellId> covering) method.
The problem why you were getting cells of a different levels is described in S2RegionCoverer.getCovering(S2Region region) documentation:
/**
   * Return a normalized cell union that covers the given region and satisfies
   * the restrictions *EXCEPT* for min_level() and level_mod(). These criteria
   * cannot be satisfied using a cell union because cell unions are
   * automatically normalized by replacing four child cells with their parent
   * whenever possible. (Note that the list of cell ids passed to the cell union
   * constructor does in fact satisfy all the given restrictions.)
   */


text:
Q: Конвертировать строку в массив чисел в с# using System;

public class Program
{
    public static void Main()
    {
        int number = 233411;
        string Number = Convert.ToString(number);
        Console.WriteLine(Number);
        int[] Array = new int[Number.Length];
        int i;

        for(i = 0; i < Number.Length; i++)
        {
            Array[i] = Convert.ToInt32(Number[i]);
            Console.Write(Array[i] + " ");
        }

    }
}

Output:
233411
50 51 51 52 49 49
Почему на выходе другие числа?

A: Как можно заметить, это коды символов. Дело в том, что вы передаете в ToInt32 символ, а он переводится в код Юникода.
Надо передавать строку
Array[i] = Convert.ToInt32(Number[i].ToString());

A: Доброго времени суток.
Для преобразования char в числовые типы на MSDN рекомендуют использовать метод GetNumericValue.
Array[i] = (int)char.GetNumericValue(Number[i]);

Проблема появления "других" чисел в строчке
Array[i] = Convert.ToInt32(Number[i]);

Документация гласит:

The ToInt32(Char) method returns a 32-bit signed integer that
  represents the UTF-16 encoded code unit of the value argument. If
  value is not a low surrogate or a high surrogate, this return value
  also represents the Unicode code point of value.

A: Строка - это последовательная коллекция символов, используемая для представления текста. Предложу вариант конвертации строки в массив чисел через LINQ:
var str = "233411";
int[] array = str
    .Select(number => Convert.ToInt32(Char.GetNumericValue(number)))
    .ToArray(); // создаст массив из IEnumerable (результат `Select` - IEnumerable)

foreach (var number in array)
{
    Console.WriteLine(number);
}

На выходе получим:

2  3 3 4 1 1

Другие числа - потому что при конвертации символа (char) в число (Int32) - получаем код символа в кодировке Unicode. Convert char to int in C#. Метод Char.GetNumericValue отлично подходит для преобразования указанного числового символа Unicode в число двойной точности с плавающей запятой (то есть double), поэтому дополнительно применяется метод Convert.ToInt32 - который преобразует заданное значение в 32-битовое целое число со знаком (то есть в int, он же Int32).
Полезные ссылки:

*

*Enumerable.Select

*Enumerable.ToArray

*Convert.ToInt32

*Char.GetNumericValue

*String

*Объекты char и символы Юникода


text:
Q: Adding custom field in General setting TAB in wordpress I want to add a custom field in General setting TAB in wordpress.
This are the present fields that wordpress has it by default.

*

*Site Title

*Tag line

*Wordpress Address URL
...etc

I want to add a custom field like, I want to have an image upload field.
For that I had to edit
options-general.php ,
options.php,
general-template.php,
I had to insert an entry in wp-options table in my database
Now when I tested it with a simple input type as text it worked well.
But when I set the input type as file for my logo upload it doesn't work this is my code below.
options-general.php

<?php _e('Logo') ?>
<input name="file" type="file"/>

As you can see I have placed my image field right under my blog description field, and the action of this form takes me to options.php.
this is my option.php
if ( is_multisite() && !is_super_admin() && 'update' != $action )
    wp_die(__('Cheatin’ uh?'));
/* image upload function goes here */

if($_POST['submit']){

$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "
";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "
";
    echo "Type: " . $_FILES["file"]["type"] . "
";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB
";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";

    if (file_exists("images/logo/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],"images/logo/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
}
    /* image upload function ends here */

Above I have added the simple image upload script, some how it doesn't work, nor the file is uploaded to the directory.
Does core PHP code works in WP environment  Or I'm missing on something, Kindly suggest.

A: Stop the machines!
You're _doing_it_wrong(), although this function does not detect what you're doing :)
We don't touch core file, we do plugins. Please, restore your WP to a fresh state.

Answering to the Question title

Adding custom field in General setting TAB in wordpress

Follows an example from WordPress Answers. The key function is add_settings_field, right now it adds a full WP Editor, but it can be adjusted to show any kind of field. A nice article that explains the Settings API.
<?php
/**
 * Plugin Name: My Custom General Setting
 */

add_action( 'admin_init', 'wpse_57647_register_settings' );

/*
 * Register settings
 */
function wpse_57647_register_settings()
{
    register_setting(
        'general',
        'html_guidelines_message',
        'esc_html' // <--- Customize this if there are multiple fields
    );
    add_settings_section(
        'site-guide',
        'Publishing Guidelines',
        '__return_false',
        'general'
    );
    add_settings_field(
        'html_guidelines_message',
        'Enter custom message',
        'wpse_57647_print_text_editor',
        'general',
        'site-guide'
    );
}

/*
 * Print settings field content
 */
function wpse_57647_print_text_editor()
{
    $the_guides = html_entity_decode( get_option( 'html_guidelines_message' ) );
    echo wp_editor(
        $the_guides,
        'sitepublishingguidelines',
        array( 'textarea_name' => 'html_guidelines_message' )
    );
}

A: If you need to add an option to a site, but it doesn't really need to be on its own page. You can probably add it to one of the existing settings pages. Here's how to add an option to the General Settings page.
In this case, I'm adding a 'favorite color' field, probably not the best example, so go ahead and change that.
$new_general_setting = new new_general_setting();

class new_general_setting {
    function new_general_setting( ) {
        add_filter( 'admin_init' , array( &$this , 'register_fields' ) );
    }
    function register_fields() {
        register_setting( 'general', 'favorite_color', 'esc_attr' );
        add_settings_field('fav_color', ''.__('Favorite Color?' , 'favorite_color' ).'' , array(&$this, 'fields_html') , 'general' );
    }
    function fields_html() {
        $value = get_option( 'favorite_color', '' );
        echo '<input type="text" id="favorite_color" name="favorite_color" value="' . $value . '" />';
    }
}

The third argument of the register_setting() function is the name of the function that should be used to validate the input data, so customize that as needed.


text:
Q: What are the spawn times for world bosses? What are the server spawn times for Elder dragons and other world bosses such as the Fire Elemental in the Asura starter zone?
Is there a wiki for this type of information?

A: Yes, there is a wiki for Guild Wars 2.
What you really want, though, are the timers, which will tell you when the bonus chest events are expected to start. Keep in mind that these timers rely on players to reset the timers after the event is completed, so they are not 100% reliable (and may be far less reliable if your server doesn't use them much).
It's important to remember, however, that almost all of the events have windows rather than set spawn times. For example, when Tequatl the Sunless, the undead dragon in Sparkfly Fen, is defeated a 2 hours and 30 minutes timer is started. When that timer ends Tequatl's 30 minute window starts, and he may spawn at any time during that 30 minute window. Thus there's a certain amount of randomness in the spawn times. Tequatl will spawn again somewhere between 2 hours and 30 minutes and 3 hours after being defeated. It should also be pointed out that Tequatl has one of the shorter windows. The Maw (in Wayfarer Foothills) has a 1 hour window, and the Claw of Jormag (in Frostgorge Sound) has a 1 hour 30 minutes window.


text:
Q: what's distinction of HTTP proxy, tunnel, gateway? all,
I see the terms from RFC 2616.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html#sec1
But I can't understand the distinction of the proxy, tunnel and gateway?
Can anyone give me a simple explanation of them?
Thanks.

A: The answer below is explained based on the definition found in RFC 2616
Proxy and server have definitions which use the word program. Whereas, for a gateway it does not. That is one of the distinctions you should notice.
Try to compare a proxy and a gateway by their handling of a request. For a proxy:

"Requests are serviced internally or by passing them on, with
  possible translation, to other servers."

It essentially may alter the request or response that get passed through it.
The gateway definition specifies that it:

"acts as an intermediary for some other server. Unlike a proxy, a
  gateway receives requests as if it were the origin server for the
  requested resource; the requesting client may not be aware that it is
  communicating with a gateway."

So, gateway in this context pretty much receives and delivers whatever goes through it.
A tunnel is like a tube with a point at each end. The intermediate program or server is not aware of this connection. This tunnel can be initiated by an HTTP request. The tunnel will be removed when either endpoint decides to drop the tunnel.


text:
Q: Should port 25 be open on localhost (Ubuntu 18.04) Port 25 is open on localhost and also on my internal 192.168.1.xxx number. The nmap scan shows:
25/tcp open  smtp Postfix smtpd

Should this be the case? I am not trying to run an SMTP server. However, for all I know, this is standard for Linux. I am using Ubuntu 18.04.
I hope someone can let me know, thanks.


text:
Q: Error in parsing the query I am getting error , whats the problem here?
SqlCeCommand com5 = new SqlCeCommand("SELECT MAX(OrderID) AS Expr1 FROM Order_Details)", con);
SqlCeDataReader dr5 = com5.ExecuteReader(); // Catches Ex here
while (dr5.Read())
{
     orderID = Convert.ToInt32(dr[0]);
}

I am using SQLCe with VS2012, WPF, C#.
The Exception is

$exception {"There was an error parsing the query.[ Token line number = 1,Token line offset = 62,Token in error = ) ]"}
       System.Exception {System.Data.SqlServerCe.SqlCeException}`

Got the query correct, but these query does not update my database, can you look into it.
SqlCeCommand com3 = new SqlCeCommand("INSERT INTO Order_Details(Discount, TotalPrice, TotalTax) VALUES(@Discount, @TotalPrice, @TotalTax)", con);
                com3.Parameters.AddWithValue("@Discount", discount);
                com3.Parameters.AddWithValue("@TotalPrice", gTotal);
                com3.Parameters.AddWithValue("@TotalTax", totalIndividualTax);

A: Remove the ) at the end
SELECT MAX(OrderID) AS Expr1 FROM Order_Details)
                                               ^--here

A: You have an extra bracket) after the FROM Order_Details part. Just remove it.
Change it to;
SqlCeCommand com5 = new SqlCeCommand("SELECT MAX(OrderID) AS Expr1 FROM Order_Details", con);
SqlCeDataReader dr5 = com5.ExecuteReader(); // Catches Ex here
while (dr5.Read())
{
     orderID = Convert.ToInt32(dr[0]);
}

By the way, I don't understand why you use ExecuteReader here. Since you just return one row with one column, using ExecuteScalar would be better.
For example;
SqlCeCommand com5 = new SqlCeCommand("SELECT MAX(OrderID) AS Expr1 FROM Order_Details", con);
orderID = (int)com5.ExecuteScalar();

A: Remove parenthesis here:
SqlCeCommand com5 = new SqlCeCommand("SELECT... Order_Details)", con);
                                                             ^


text:
Q: qt QML tabviewstyle tab rectangle add x I need to move the tab buttons in tabview to shift or padding right. When I add x position to the tabviewstyle rectangle, it moves to the right but the end tabs are getting cut off. How could I move the tabs without the cut off, Any idea how to fix this?
TabView {
    id: frame
    //anchors.fill: parent
    y: 250
    width: 400
    anchors.margins: 4
    Tab { title: "Tab 1" }
    Tab { title: "Tab 2" }
    Tab { title: "Tab 3" }

    style: TabViewStyle {

        frameOverlap: 1
        tab: Rectangle {
            x: 50
            color: styleData.selected ? "steelblue" :"lightsteelblue"
            border.color:  "steelblue"
            implicitWidth: Math.max(text.width + 4, 100)
            implicitHeight: 20
            radius: 2
            Text {
                id: text
                anchors.centerIn: parent
                text: styleData.title
                color: styleData.selected ? "white" : "black"
            }
        }
        frame: Rectangle { color: "steelblue" }
    }
}

A: It's not completely clear from your description, but if you just want the buttons in the tab bar aligned right, this should do the trick for you:
https://doc.qt.io/qt-5/qml-qtquick-controls-styles-tabviewstyle.html#tabsAlignment-prop
TabViewStyle {
    tabsAlignment: Qt.AlignRight
    [...]
}

If that's not what you are looking for, can you clarify the question a little more?
EDIT: based on OP's comment below, here's another approach.
Source code for the TabView component is here: https://github.com/qt/qtquickcontrols/blob/dev/src/controls/TabView.qml
You can see it uses a private TabBar component to place the tab buttons at the top of the Tabs stack and supports left, center and right alignment for them.
Perhaps you can achieve the effect you want by setting the anchors.leftMargin on the TabBar? Without it being an aliased property, you'll need to loop on the TabView's children to find it by objectName and then set the anchor margin on it.


text:
Q: How to show all of minibuffer commands history in Emacs? I see I can go back history of command by using "M-p" in minibuffer. But I want to see all of command I used in minibuffer.
Thanks.

A: The variable is command-history, not minibuffer-history.
You can use M-x list-command-history.  Just customize option list-command-history-max, if you want to see the whole history.
Or look directly at variable command-history using C-h v.  But see option history-length, which controls how many commands to keep in command-history.

A: It's held in minibuffer-history variable.
For a graphical view, use helm-minibuffer-history from helm package.

A: This explains how to repeat the n-th previous command and how to view history:

M-x list-command-history
Display the entire command history, showing all the commands C-x <ESC> <ESC> can repeat, most recent first.

And according to this you can set the maximum length of the minibuffer history:

The variable history-length specifies the maximum length of a minibuffer history list; adding a new element deletes the oldest element if the list gets too long. If the value is t, there is no maximum length.

A: If you use Helm, then it would be:
(define-key minibuffer-local-map (kbd "C-c C-l") 'helm-minibuffer-history)

The equvalent version of selectrum + consult:
(define-key minibuffer-local-map (kbd "C-c C-l") 'consult-history)


text:
Q: How to pull customer email on Magento Checkout Success.phtml 1.7 I've tried various solutions online to no avail.  I think it should be something like:
<?php
$order->getBillingAddress()->getEmail();
?>

An email confirmation was sent to: <?php echo $order->getEmail ?>

I am able to display order ID with:
<?php echo $this->getOrderId() ?>

If you have a suggestion, please be as specific as you can because I am definitely a novice.

A: Try adding this to Success.phtml
<?php
   $order = Mage::getModel('sales/order')->loadByIncrementId($this->getOrderId());
   echo $order->getCustomerEmail();
?>

Read more: Get Order Increment ID in Magento

A: Try with this code
$_customerId = Mage::getSingleton('customer/session')->getCustomerId();

$lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();

$order = Mage::getSingleton('sales/order');

$order->load($lastOrderId);

Then do
foreach($order as $_order){
    echo $_order->getCustomerEmail();
}

Hope this helps


text:
Q: Dns protocol header I want to encode DNS protocol header using C and create a UDP datagram.
Lets say I have a query www.google.com.
Can anyone suggest how to go about it?
You can find the header format here -
http://www.nersc.gov/~scottc/software/snort/dns_head.html

A: RFC 1035 explains the DNS packet format in full detail. Note that the format is designed to be as compact as possible, so there are a lot of bit- and byte-level optimisations that you will have to pay attention to. A proper, robust DNS encoder and decoder is not for the faint of heart.

A: +1 to RFC 1035.
You can take a look on Wireshark: http://www.wireshark.org/
It shows packets in both - binary and decoded view + contains source code in C so you can check how decoding is implemented.


text:
Q: Code signing error in Xcode 8 I want to run my app on my device instead of on the simulator, but every time I try to run it, I get a code signing error:

*

*'AppName' requires a provisioning profile. Select a provisioning profile for the "Debug" build configuration in the project editor.

*Code signing is required for product type 'Application' in SDK 'iOS 10.0'

I added a provisioning profile to the build settings under 'Code signing' but I still keep getting this error. Is there something wrong with my provisioning profile or am I looking in the wrong place? By the way, I used this provisioning profile on the previous version of Xcode and never ran into any problems.

A: I had a similar problem and it was because my iPhone Developer certificate had expired. You can check this with the Keychain Access app in Utilities.

A: To fix it, I set  > TARGETS  > General tab > Signing > Automatically manage signing = CHECK MARK


text:
Q: How to remove default button style in android
Above is my button and i want to remove default shadow also, I have successfully removed background but shadow is still there below is my xml code
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/create_account"
    android:id="@+id/buttonCreateAccount"
    android:layout_gravity="center_horizontal"
    android:background="@null"
    style=""
    android:shadowRadius="@null"
    android:drawableBottom="@null"
/>

A: use following style
style="?android:attr/borderlessButtonStyle"


text:
Q: Macro with ## in @interface, what does it mean? What does it do, especially the ## ?
#define CUSTOM_ARRAY_INTERFACE(classname) \
@interface classname ## Array : ConcreteMutableArray \
- (void) add:(classname*)obj;\
- (classname*) get:(int)index;\
@end\

What does CUSTOM_ARRAY_INTERFACE(NSString) generate then, this idea of mine doesn't even work
@interface NSString ## Array : ConcreteMutableArray
- (void) add:(classname*)obj;
- (classname*) get:(int)index;
@end

?
Is a way to show to what code a macro would get expanded, without looking into assembler code?

A: The ## is a macro concatenation operator, so that
CUSTOM_ARRAY_INTERFACE(Foo)

would concatenate Foo with Array and result in
@interface FooArray : ConcreteMutableArray
- (void) add:(Foo*)obj;
- (Foo*) get:(int)index;
@end

Or
CUSTOM_ARRAY_INTERFACE(NSString)

would result in
@interface NSStringArray : ConcreteMutableArray
- (void) add:(NSString*)obj;
- (NSString*) get:(int)index;
@end

It's worth noting that Objective-C now supports lightweight generics, eliminating the need for the above pattern. For example, NSArray lets you specify the type of objects for the individual elements in the array, e.g.
NSArray <NSString *> *array = ...

Now the compiler knows that array is an array of strings without needing to declare a specific type for this. The compiler will know that the following is valid:
NSString *string = array[0];

But if you attempted to do something like:
NSNumber *number = array[0];

It would resulting in the following compile-time warning:

Incompatible pointer types initializing 'NSNumber *' with an expression of type 'NSString *'.

Note, this is a "lightweight" generic. E.g. it merely results in compile-time warnings, but doesn't strictly enforce this at runtime like true generics in other languages (such as Swift).

A: You can see preprocessor output for your file  the following way from Xcode menu:

*

*in Xcode 4.6: go to "Product" -> "Generate output" -> "Preprocessed File".

*in Xcode 5: go to "Product" -> "Perform Action" -> "Preprocess File".
For your macro example it produces the following code:
@interface NSStringArray : ConcreteMutableArray
- (void) add:(NSString*)obj;
- (NSString*) get:(int)index;
@end


text:
Q: How can I compare two rows in R data frame by different columns and perform an operation on them? I have some data with a similar structure.
test_data <- data.frame(start = c(1,15,17,35),
                         time = c(87, 1, 35, 3),
                         end = c(88,16,52,38))
test_data
  start   time end
1     1     88  87
2    15      1  16
3    17     35  52
4    35      3  38

I want to compare the "start" variable with the "end" variable of the previous row. If the difference is less then 2 I want to sum them by time, leaving the start from the first row and end of the second row.
So in this test data start in the third observation is 17 and end in the second is 16. The difference is 1 and thus I want to sum them.
I expect such an output
    start time end
1     1     88  87
2    15     36  52
3    35      3  38

Is there a neat way to do this in R? I tried writing a for loop, but it seems that I am overcomplicating it a lot.

A: You could use data.table with a combination of shift and cumsum:
library(data.table)
test_data <- data.frame(start = c(1,15,17,35),
                        time = c(87, 1, 35, 3),
                        end = c(88,16,52,38))

setDT(test_data)
test_data[, gid:=ifelse(.I>1 & shift(end) - start < 2, FALSE, TRUE)]
test_data[,.(start=head(start,1), time=sum(time), end=tail(end,1)), by=cumsum(gid)][,-"cumsum"]
#>    start time end
#> 1:     1   87  88
#> 2:    15   36  52
#> 3:    35    3  38

Created on 2021-01-31 by the reprex package (v1.0.0)
Note that this would also merge multiple consecutive rows (not just 2) with <2 distance between previous end and current start values.


text:
Q: How to know allowed methods for one route in Symfony2? I'm currently in a listener, and I want to return some headers in my response. $this->router->match($this->request->getPathInfo()); I don't have any information about this. I have however specified the methods :
api_v2_spokespeople_collection:
  path: /spokespeople
  defaults: { _controller: "APIBundle:v2/Spokesperson:getCollection" }
  methods:  [GET, OPTIONS]

Is it finally possible without having to "manually" parse the routing files?

A: If you have a route name:
/** @var string $routeName */
/** @var Symfony\Component\HttpFoundation\Request $request */
$routeName = $request->attributes->get('_route');

and you have the @router service (It seems this service was injected into your listener):
// from the controller action.
/** @var Symfony\Bundle\FrameworkBundle\Routing\Router $router */
$router = $this->get('router');

//in your sample should be $this->router directly.

then we can get the route instance and its information through route collection:
/** @var Symfony\Component\Routing\Route $route */
$route = $router->getRouteCollection()->get($routeName);

finally, you need to call to getMethods() to know the defined methods:
/** @var string[] $methods */
$methods = $route->getMethods(); // e.g. array('GET', 'POST')

In one line:
$methods = $this->router->getRouteCollection()->get($request->get('_route'))->getMethods();

A: As I understood you are going to get allowed methods for current route. If so then:
$route = $this->request->get('_route');
$methods = $route->getMethods();


text:
Q: android application i am a beginner in android.now i am familiar with layout concept.i can add different layer in android.Now i want to know how can i divide the emulator into two or more parts.just like < frameset > in html.i want to perform edit or refresh one part, without disturbing other part.Somebody told me that it is done by multilayer concept.But i didn't see any multilayer concept in anywhere .when i am trying to search " multilayer concept in android", it always lead to layout concept. So somebody told me how can i perform this.

A: I too haven't found any multi-layer concept yet LoL
Its about a god mix of Layouts only

A: I agree with Sheikh Aman's answer.
But if you look at the Android 3.0 Honeycomb features then there are some interesting features. Like contacts application has a two pane user interface.
Also you can breaks your application Activities into the subcomponents (fragments). And by combining them you can create a rich UI with the multiple panes.
Like this one:

However sounds like it's only for the Tablets but hope it's what you want to know like as Frameset's in HTML.
See more here:
http://developer.android.com/sdk/android-3.0-highlights.html#ui


text:
Q: Prime and Maximal Ideals of $\mathbb{Z}[x]$ containing $(30,x^3+1)$ What I've worked out so far is that $(30, x^3+1)$ is contained in $(2, x^3+1)$, $(3, x^3+1)$, and $(5, x^3+1)$.
For $(2, x^3+1)$, we have $\mathbb{Z}[x]/(2, x^3+1) \simeq \mathbb{F}_2[x]/(x^3+1)$. I notice that in $\mathbb{F}_2[x]$, we have $x^3+1 = (x+1)(x^2+x+1)$. So we can write a couple of the prime ideals in $\mathbb{Z}[x]$ as $(2, x^3+1, x+1)$ and $(2, x^3+1, x^2+x+1)$, which both clearly contain $(30, x^3+1)$ and quotient to $\mathbb{F}_2$ and $\mathbb{F}_4$, respectively. These are both fields, and hence domains, so those ideals are indeed prime and maximal.
I proceed with the same technique for the other ideals. Is this method correct in obtaining all the prime ideals? A second question is, will I ever get a non-maximal, prime ideal? It seems I only ever get maximal ideals because the quotients end up being fields.

A: You are correct. To show that the primes obtained by your procedure exhaust all the ones containing $(30, x^3+1)$, you can use the fact that if $\mathfrak{p}\supset (30,x^3+1)$ then $30=2\times 3\times 5\in \mathfrak{p}$ and one of $2\in \mathfrak{p}, 3\in \mathfrak{p}, 5 \in \mathfrak{p}$ holds.
In fact, they are necessarily maximal. This is because they properly contain a nonzero principal prime ideal and the Krull dimension of $\mathbb{Z}[x]$ is equal to $2$.


text:
Q: Javascript cannot create property 'guid' on number '100' I am trying to trigger the scroll action on a canvas element by clicking on a link.
Here are the examples I have been following: https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll

JS:
$('#zoom-in-button').click(function() {
    $('.vis-network canvas').scroll(0, 100);
    // $('.vis-network canvas').scroll({top: 1000});
});

HTML:

    +

    <canvas style="overflow:auto">

Error:
jquery.min.js:2 Uncaught TypeError: Cannot create property 'guid' on number '100'
    at Object.add (jquery.min.js:2)

A: First, $('.vis-network canvas') is neither window nor HTMLElement - it's jQuery object. While this object has scroll method (in its prototype chain), it does something completely different:

This method is a shortcut for .on( "scroll", handler ) in the first
  and second variations, and .trigger( "scroll" ) in the third.

Note that the third case doesn't let you parameterize the event.
You're probably looking for this:
var canvas = $('.vis-network canvas')[0];
canvas.scrollLeft = 0;
canvas.scrollTop = 100;

... but it looks weird that you try to scroll the child (the contents) and not the parent. Perhaps you should actually target $('.vis-network') instead.


text:
Q: Formula to extract hostname from variety of entered URL's Client's provide URL's in many different types of formats. I look for an Excel formula that can extract the hostname (including www if provided), all else needs to be trimmed off. Below are examples of URL's we have received and the bold text is the part I wish to extract in the next adjacent cell. A single-cell formula would be ideal (RIGHT, LEFT, REGEXMATCH etc), but I have not succeeded matching to all below variations, looking to community for help :-)

http://testing.com.my/college/openday/?
  utm_campaign=dec&utm_source=search&utm_medium=cpc&utm_content=link
http://testing.com?utm_source=test
http://testing.com/?utm_source=test
http://www.testing.com.sg/test?utm_source=test
https://www.testing.com/asdsd?utm_source=test
http://www.testing.edu.my/college/openday/?utm_campaign=dec&utm_source=search&utm_medium=cpc&utm_content=link
testing.edu.my
testing.com
testing.com/?asdomasd
www.testing.com
www.testing.com.my?test
www.testing.com.my/?test
www.testing.edu.my/openday/?utm_campaign=dec&utm_source=search&utm_medium=cpc&utm_content=link
www.testing.edu.my/college/openday/
//www.testing.com/test
//testing.com/ddsd?utm_source=test

A: Note that the regex you are looking for is not very common since you accept to match URLs possibly starting directly with //.
So, inside your Excel formula, use the following regex ^(https?:)?(\/\/)?([^\/]*).* and access the 3rd matching group when the regex matches.
Note that this will give you either the hostname, or the IP address (for IPv6 addresses, you will get [theIPv6Address] with carets around the address).

A: Sorry that I couldn't find a shorter one for you but here you go:
=MID(A2,FIND(MID(E2,IFERROR(FIND("|",SUBSTITUTE(LEFT(A2,FIND(".",A2)-1),"/","|",LEN(LEFT(A2,FIND(".",A2)-1))-LEN(SUBSTITUTE(LEFT(A2,FIND(".",A2)-1),"/","")))),0)+1,30),A2),FIND(MID(MID(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".","")))),10),1,IFERROR(IFERROR(FIND("/",MID(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".","")))),10)),FIND("?",MID(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".","")))),10))),LEN(MID(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".","")))),10))+1)-1),A2)+LEN(MID(MID(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".","")))),10),1,IFERROR(IFERROR(FIND("/",MID(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".","")))),10)),FIND("?",MID(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".","")))),10))),LEN(MID(A2,FIND("|",SUBSTITUTE(A2,".","|",LEN(A2)-LEN(SUBSTITUTE(A2,".","")))),10))+1)-1))-FIND(MID(E2,IFERROR(FIND("|",SUBSTITUTE(LEFT(A2,FIND(".",A2)-1),"/","|",LEN(LEFT(A2,FIND(".",A2)-1))-LEN(SUBSTITUTE(LEFT(A2,FIND(".",A2)-1),"/","")))),0)+1,30),A2))

This is a little bit hard to explain so I also upload the logic how I went through.

First, I want to find the first ., then remove the prefix, and then find the position of that first good wording.  See the columns that I highlight in green.
Second, I want to find the last ..  But this is a little bit tricky.  You don't know how it is going to end with so I added 10 characters (you can change to a bigger value).  Then I find / or ? (from your example, I believe / always go first) or include all words if those two characters do not exist.  Then I can retrieve the last good string and find the position.  This is all done in those yellow columns.
Lastly, in the blue columns.  I simply combined all the formulas into one single cell to show you the start and ending points.  BTW, you can also see the pertaining formulas in row 18.
Some tricks here that I have also learned from this exercise:

*

*LEN(A2)-LEN(SUBSTITUTE(A2,"/","")) help you to find how many / (replace this character to find the one you want) in the string.

*=SUBSTITUTE(A2,"/","|",LEN(A2)-LEN(SUBSTITUTE(A2,"/",""))) can find the last / (replace this character to find the one you want) character in that string.  Please note I used | here just because this character is rare to see but you can use whichever that you don't think it will appear in your string.
Hope this helps.


text:
Q: Why does redigo return ERR unknown command 'EVALSHA' https://github.com/garyburd/redigo
Why does redigo return error message?
error message:
ERR unknown command 'EVALSHA'
ERR unknown command 'EVALSHA'

code:
const lockScript = `
local v = redis.call("GET", KEYS[1])
if v == false or v == ARGV[1]
then
    return redis.call("SET", KEYS[1], ARGV[1], "EX", ARGV[2]) and 1
else
    return 0
end
`

func CounterRegScript() {
    rc := RedisClient.Get()
    defer rc.Close()

    script := redis.NewScript(1, lockScript)
    resp, err := script.Do(rc, "xiaorui.cc", "nima", int64(3))
    fmt.Println(resp)
    fmt.Println(err)
}

A: You are using an old version of Redis. Upgrade to version 2.6 or later.


text:
Q: From fetch request to DOM: How to convert the response into a walkable DOM structure? Example:

*

*Fetch call that gets a HTML document as response.

*Response gets interpreted as DOM structure.

*One can now use querySelector to search for specific elements in that structure.

My idea so far (probably way more complex than it should be):
const responseString = await(await fetch('https://.....')).text();
const element = document.createElement('html');
element.innerHTML = responseString;

There has to be a standard for this right?
Something like: const responseString = await(await fetch('https://.....')).domNodes();


text:
Q: Integrating to get the posterior distribution for the precision Our model is the following:
$x_i|\mu,\tau \sim N(\mu,\tau)$, where tau is the precision.
$\mu|\tau \sim N(\mu_0,n_0\tau)$,
$\tau\sim Ga(\alpha,\beta)$.
In the picture below, how is the normalization constant derived? I've tried integrating $\mu$, but I get a different expression...
I've seen some posts with similar questions, but different derivations. I'm interested how to do this specifically.
Any help would be appreciated

Edit: I have no idea how to do this so, I used mathematica with the following command line:  Integrate[E^(-t/2 (n0*(mu - mu0)^2 + n*(xbar - mu)^2)), mu].
I got this:
$$\frac{\sqrt{\frac{\pi }{2}} e^{-\frac{n n_0 t (\mu_0-\bar x)^2}{2 (n-n_0)}} \text{erfi}\left(\frac{\sqrt{t} (\mu(n-n_0)+\mu_0 n_0-n \bar x)}{\sqrt{2} \sqrt{n-n_0}}\right)}{\sqrt{t} \sqrt{n-n_0}}$$
If I take the limits, then I do get what it's stated.
How do we calculate the integral without using a computer?


text:
Q: Form consisting of boxes. How to glue par-/frameboxes? I was given the following to fill in, however the template was given in a word file and it is really awful to edit in and format properly.

I've tried to recreate it in Latex. My attempt is the following:
\documentclass[11pt]{article}

\usepackage[margin=1in,headheight=14pt]{geometry}
\usepackage{amsmath,amsthm,amssymb,graphicx,mathtools,tikz,hyperref, array, subcaption, caption}
\usepackage[utf8]{inputenc} %øåæ
\usepackage[danish]{babel}

\begin{document}

\noindent  \framebox{  \parbox[t][0.5cm]{10cm}{
%
\textbf{Øvelse:} Aritmetikkens fundamentalsætning

} }%%%
%
\framebox{ \parbox[t][0.5cm]{6cm}{
%
\textbf{Dato:}

} }

\noindent  \framebox{  \parbox[t][4cm]{9cm}{
%
{\centering \textbf{Øvelsens mål} \par }

{\small \textbf{Læringsmål: } }

} }%%%
%
\framebox{ \parbox[t][4cm]{7cm}{
%
{\centering \textbf{Læreplanens mål} \par }

{\small \textbf{Kernestof og kompetencer i læreplanen:} }

} }

\end{document}

Which produces

As you can see the boxes don't allign properly and there is some unwanted space between the first boxes and the next boxes. I've tried different methods without succes and have not been able to find any examples of someone creating something simular.
I would appreciate if someone could help me recreate the initial bit of the origianl, having seen an example of that I imagine I would be able to make the rest of it.

A: One option is to just stack tabularx environments. The picture can be drawn with TikZ. I didn't feel like typing in the elements of your screen shot, so I stopped in the middle, but I think it should be obvious how to continue.
\documentclass[11pt]{article}

\usepackage[margin=1in,headheight=14pt]{geometry}
\usepackage{amsmath,amsthm,amssymb,graphicx,mathtools,tikz,hyperref, array, subcaption, caption}
\usepackage[utf8]{inputenc} %øåæ
\usepackage[danish]{babel}
\usepackage{tabularx}
\usepackage{tikz}
\usetikzlibrary{positioning, babel}
\tikzset{% from https://tex.stackexchange.com/a/72793/121799
  double arrow/.style args={#1 colored by #2 and #3}{
    -stealth,line width=#1,#2, % first arrow
    postaction={draw,-stealth,#3,line width=(#1)/3,
                shorten <=(#1)/3,shorten >=2*(#1)/3}, % second arrow
  }
}

\begin{document}
\noindent
\begin{tabularx}{\linewidth}{|p{10cm}|X|}
\hline
\textbf{Øvelse:} Aritmetikkens fundamentalsætning
&
\textbf{Dato:} \\
\hline
\end{tabularx}\\[-1.5pt]
\begin{tabularx}{\linewidth}{|>{\centering}p{9cm}|X|}
\hline
\textbf{Øvelsens mål} & \textbf{Læreplanens mål}\\
{\small\textbf{Læringsmål: } }& {\small \textbf{Kernestof og kompetencer i læreplanen:} }\\[3cm]
\hline
\end{tabularx}\\[-1.5pt]
\begin{tabularx}{\linewidth}{|>{\centering}b{8cm}|X|}
\hline
\begin{tikzpicture}[baseline=(a.base)]
\node (a) {something};
\node[below=0.8cm of a] (b) {fang};
\draw[double arrow=7pt colored by black and blue] (a) -- (b);
\end{tikzpicture} & \textbf{Materialeliste}\\
\hline
\end{tabularx}
\end{document}

A: Similar to marmot, but I'd put everything into one tabular and create sub-tabulars for each line. Saves me from specifying any guessed negative skips to glue the tables together.
\documentclass[11pt]{article}

\usepackage[margin=1in,headheight=14pt]{geometry}
\usepackage[utf8]{inputenc} %øåæ
\usepackage[danish]{babel}

\newcommand\myline[2]
  {%
    \strut
    \begin{tabular}{@{}p{\dimexpr#1\linewidth-\tabcolsep\relax}|
      p{\dimexpr\linewidth-#1\linewidth-\tabcolsep\relax}@{}}%
      #2%
    \end{tabular}%
    \strut
  }%

\begin{document}
\noindent
\begin{tabular}[]{|p{\dimexpr\textwidth-2\tabcolsep}|}
  \hline
  \myline{.7}{\textbf{Øvelse:} Aritmetikkens fundamentalsætning
    & \textbf{Dato:}}\\
  \hline
  \myline{.5}{%
    \centerline{\textbf{Øvelsens mål}}%
    {\small \textbf{Læringsmål:}}%
    &
    \centerline{\textbf{Læreplanens mål}}%
    {\small \textbf{Kernestof og kompetencer i læreplanen:}}\par
    \rule{0pt}{2cm}%
  }\\
  \hline
  \myline{.6}{%
    This is some more text & with more to come\par
    \rule{0pt}{2cm}%
  }\\
  \hline
  \strut\begin{tabular}[]{@{}p{\dimexpr.2\linewidth-\tabcolsep\relax}|
      *2{p{\dimexpr.25\linewidth-2\tabcolsep\relax}|}
    p{\dimexpr\linewidth-\tabcolsep-.7\linewidth}@{}}%
    four & columns & are & trickier\par\rule{0pt}{2cm}
  \end{tabular}\strut\\
  \hline
\end{tabular}
\end{document}

\myline is a macro that takes two arguments and outputs two columns. The first argument is the width at which the vertical separation should appear (.5 meaning half of the available width), the second the contents of the two columns separated by a &.


text:
Q: Unable to view vote counts in review lists While going through the review (first posts) lists I noticed that I was unable to directly view the vote count from that interface.
Obviously it is pretty easy to just open the post in a new tab and see that information (and anyone that can view the review queues already has that privilege), so I was wondering if this is a bug or if it by-design?
(I wanted to check since there was a comment about the votes on that post.)


text:
Q: PhpMyAdmin Installation error I have installed apache,mysql,php and phpmyadmin in my kubuntu 13.10 32 bit. I can access localhost and localhost/info.php successfully. But while loading phpmyadmin, the browser shows as follows.
Please help me to fix this error

A: I think after adding Include /etc/phpmyadmin/apache.conf to the file /etc/apache2/apache2.conf you are not resetting the file pemission.
So reset the file permission to 555 by running
sudo chmod 555 apache2.conf


text:
Q: C# : Thread Workload and Memory useage the Windows Taskmanger is fine to check the CPU and memory useage of an application but in our programm we have different threads and we want to know how much of the total ammount is on each thread.
We would like to check this with an external programm and also from the application itself during runtime. It would be great if a thread could tell about his memory and cpu useage.

A: Here's is the example:
You have threadA and ThreadB.
ThreadA creats an object X.
ThreadB uses this object.
So what do you want to see in thread's information? Who created the object or who is using it?
The only thing you can see is how much CPU time is using thread AFAIK
And all the same the only program that I know that shows MAX info on process is Process Explorer. http://technet.microsoft.com/en-us/sysinternals/bb896653

A: You can use performance monitor to see how much memory is allocated to a process, but you cannot see the same for single threads inside it.
However, you could create custom performance counters to display any value you want to monitor from within your code.

A: SysInternals Process Explorer has this feature, check this Server fault thread.
There is an open source project on CodeProject, the screenshot looks promising: How to get CPU usage of processes and threads, but the demo project seems to be crashing on Win7 (probably missing some privileges).
[Edit] If you want to write it yourself, you can P/Invoke Thread32First and Thread32Next functions to enumerate threads within a single process, and then use QueryThreadCycleTime to query CPU time for each thread.

A: Objects are shared between threads, threads do not own objects.
Memory for an object is allocated on the heap, which lives in the realm of the application. Any thread can access any of this memory at any time during the lifetime of the application.
There is no way to determine which thread is or may be using any arbitrary blocks of memory.
Threads perform units of work. Unless you know which thread is going to be running which unit of work you will be able to get no reliable metrics out of CPU usage. If you do know which thread will be performing which tasks, then Process Explorer by SysInternals has this metric.


text:
Q: Creating custom progressbar in blackberry All, I want to crate an rich looking, custom progress bar for blackberry touch devices. I can used GaugeField, but it wont give the the rich look.
Here is sample prototype I have to make. Please suggest me how could I start with. Any sample or guide me with the steps.

A: Have a look at the "Creating a bitmap progress indicator" section of RIM's "Advanced UI components and managers" documentation.