text:
Q: null data received from server php using retrofit, but response is success I am trying to learn retrofit. It looks like the response received is success, but there is no data.
The php file works fine, I have checked it using postman. On postman i am receiving a response, but not on my App.
Below is my code :
ApiInterface File :
public interface ApiInterface {
    @FormUrlEncoded // annotation used in POST type requests
    @POST("/login.php")     // API's endpoints
    public void login(@Field("Login") String login, Callback<JSONObject> callback);
}

Api File :
public class Api {

    public static ApiInterface getClient() {
        RestAdapter adapter = new RestAdapter.Builder().setEndpoint(Constants.base_url).build();
        ApiInterface api = adapter.create(ApiInterface.class);
        return api;
    }
}

MainActivity File : (the below code is called on button click)
private void signUp() {
        Api.getClient().login(convert_JSON, new Callback<JSONObject>() {
            @Override
            public void success(JSONObject loginResponse, Response response) {
                try {
                    Toast.makeText(Login.this, loginResponse.get("message").toString(), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    Log.i("viky123", e.getMessage());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
                Log.i("viky", error.toString());
            }
        });
    }

Below is the error showning that JSON object key 'message' has no value. This error is caught in catch block of success method in MainActivity File :
2021-08-29 19:54:24.859 3372-3372/com.example.panshoptrail W/System.err: org.json.JSONException: No value for message
2021-08-29 19:54:24.860 3372-3372/com.example.panshoptrail W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
2021-08-29 19:54:24.860 3372-3372/com.example.panshoptrail W/System.err:     at com.example.panshoptrail.Login$1.success(Login.java:100)
2021-08-29 19:54:24.860 3372-3372/com.example.panshoptrail W/System.err:     at com.example.panshoptrail.Login$1.success(Login.java:92)
2021-08-29 19:54:24.860 3372-3372/com.example.panshoptrail W/System.err:     at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
2021-08-29 19:54:24.861 3372-3372/com.example.panshoptrail W/System.err:     at android.os.Handler.handleCallback(Handler.java:914)
2021-08-29 19:54:24.861 3372-3372/com.example.panshoptrail W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:100)
2021-08-29 19:54:24.861 3372-3372/com.example.panshoptrail W/System.err:     at android.os.Looper.loop(Looper.java:224)
2021-08-29 19:54:24.861 3372-3372/com.example.panshoptrail W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7560)
2021-08-29 19:54:24.861 3372-3372/com.example.panshoptrail W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
2021-08-29 19:54:24.862 3372-3372/com.example.panshoptrail W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
2021-08-29 19:54:24.862 3372-3372/com.example.panshoptrail W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)


text:
Q: The locate command cannot find obvious directory? I have a directory called OC located in /home/raph/OC.
I've updated the database with the updatedb command and i still can't find the directory.
I've seen in an another post that the problem could come from the /etc/updatedb.conf file.
I checked it and everything is normal(meaning that /home/raph/ is not in #PRUNEPATHS)
Does anyone have an idea why i can't find that obvious directory?
@ByteCommander i indeed forgot to mention it but when i use the find command i am able to find it :
link
@muru When i check the /etc/updatedb.conf file here is what i get :
link

redpajama_set_name: RedPajamaStackExchange


text:
Q: after running crao -n react-app, how do i implement routing I'm a noobie at react and internet isn't always available to me, so i've been using create-react-app-offline, but now i want to make a multi-page app with routing and i'm stuck. Thanks for the help.

A: You can try the Quick Start guide from React Router, and download the rest of the documentation. While you have internet access, try to install the necessary packages needed from npm or yarn


text:
Q: Display every single combination of lower case letters I am trying to figure out how to print every single combination of lower case letters starting at A, B, C , .. , Z AA, AB , .., ZZ ... AAA, AAB, AAC ... HWESA, HWESB, HWESC ... etc and I want the program to keep printing these endlessly, growing in length by 1 each time Z is found as the last letter.
Code that is have seen online is like this
for(int a = 0; a < alphabet.length; a++)
{
    Console.WriteLine(alphabet[a]);
    for(int b = 0; b < alphabet.length; b++)
    {
        Console.WriteLine(alphabet[a]+alphabet[b]);
        //With however many for loops you want which correspond to string length
    }
}

However, this doesn't work for me because I want the length to go till infinite (or in my program to stop when it matches a hard-coded string).

A: I have tried the same in java with recursive method , hope you understand the logic and write down in C#.You can check the whole program in the below shared link.
size - if 1 means a,b,c...z
       if 2 means aa,ab...zz
public static void recursion(long size,String prefix)//Recursive method
    {
    // Base case: size is 0, print prefix
    if(size==0)
    {   System.out.println(prefix);
        return;
    }
     // One by one add all characters from set and recursively
    // call for size equals to size-1
    for(int i=0;i<26;i++)
    {
         // Next character of input added
        String newPrefix = prefix + s[i];
         // Size is decreased, because we have added a new character
        recursion(size-1,newPrefix);
    }

}

Click Here to View Full Code


text:
Q: Find the field of two infinite strips of width $b$
Q:The two charged strips in the following picture  have width $b$, infinite height,and negligible thickness(in the direction perpendicular to the page).Their densities per unit area are $\sigma$ and $-\sigma$.
a)Find the field magnitude produced due to one of the strips from a distance $a$ away from it(in the plane of the page).
b)Show that the force(per unit height) between the two strips is equal to $\frac{\sigma^2 b \ln(2)}{\pi \epsilon_0}$. Note that this result is finite, even tough the field in the boundary of the strip diverges.
*Part a solved in the following lines:
**Struggling with part b

Attempted Solution:

Part a solved in the following lines:

As the figure shows I calculate the Field from a distance $a$ from the first tape:
$$\begin{aligned}E_x&=\int\int \frac{k dq}{r^2}\cos{\theta} \\ &=k\int\int \frac{\sigma da}{r^2}\cos{\theta} \end{aligned}$$
From the geometry of the figure we get:
$$\begin{aligned}E_x&=k\sigma\int_{-\infty}^{\infty}\int_0^b \frac{ dx dy}{(a+x)^2+y^2}\cdot\frac{a+x}{\sqrt{(a+x)^2+y^2}} \\ &=k\sigma\int_{-\infty}^{\infty}\Big(\int_0^b \frac{ (a+x)dx }{\Big((a+x)^2+y^2\Big)^{3/2}}\Big)dy\end{aligned}$$
If $u= (a+x)^2+y^2=(a^2+2ax+x^2+y^2)$, thus $du=(2a+2x)dx \Rightarrow du/2=(a+x)dx$
$$\begin{aligned}E_x&=k\sigma\int_{-\infty}^{\infty}\Big( \int_{c'}^{d'} \frac{du}{2u^{3/2}} \Big)dy=\frac{k\sigma}{2}\int_{-\infty}^{\infty}\Big( \Big[ \frac{-2}{u^{1/2}}\Big]_{c'}^{d'} \Big)dy \\ &=-k\sigma \int_{-\infty}^{\infty}\Big( \Big[(a+x)^2+y^2)^{-1/2} \Big]_{0}^{b}  \Big)dy \\ &=-k\sigma \int_{-\infty}^{\infty}\Big( (a+b)^2+y^2)^{-1/2} -(a^2+y^2)^{-1/2}  \Big)dy \\ &=-k\sigma \int_{-\infty}^{\infty}\Big( \frac{1}{\sqrt{(a+b)^2+y^2}} - \frac{1}{\sqrt{a^2+y^2}}  \Big)dy \end{aligned} $$
We can find an anti-derivative for the previous expression:
$$\begin{aligned}E_x&=-k\sigma \Big[ \ln(\sqrt{(a+b)^2+y^2}+y)-\ln(\sqrt{a^2+y^2}+y)\Big]_{-\infty}^{\infty}\\ &=-k\sigma \lim_{d \rightarrow \infty} \Big[ \ln\Big(\frac{\sqrt{(a+b)^2+y^2}+y}{\sqrt{a^2+y^2}+y}\Big) \Big]_{-d}^{d} \\ &=-k\sigma \lim_{d \rightarrow \infty} \Big[ \ln\Big(\frac{\sqrt{(a+b)^2+d^2}+d}{\sqrt{a^2+d^2}+d}\Big) - \ln\Big(\frac{\sqrt{(a+b)^2+d^2}-d}{\sqrt{a^2+d^2}-d}\Big)\Big] \end{aligned} $$
The first limit can be easily seen as tending to $0$ and the second one according to  Wolfram tends to  $\ln(\frac{(a+b)^2}{a^2})$ something that is rather convenient.
So the intensity of the field of the $\sigma$ tape is equal to :
$$E_{\sigma}=-k\sigma \ln \Big(\frac{(a+b)^2}{a^2}\Big)$$
This result seems right because the field diverges in $0$ and in $b$.
Using a similar approach we can calculate the other plate field changing the limits of integration of $x$ from $b$ to $2b$
$$\begin{aligned}E_x&=k\sigma\int_{-\infty}^{\infty}\Big(\int_b^{2b} \frac{ (a+x)dx }{\Big((a+x)^2+y^2\Big)^{3/2}}\Big)dy \\ &=-k\sigma \int_{-\infty}^{\infty}\Big( \Big[(a+x)^2+y^2)^{-1/2} \Big]_b^{2b}  \Big)dy \\ &=-k\sigma \int_{-\infty}^{\infty}\Big( (a+2b)^2+y^2)^{-1/2} -((a+b)^2+y^2)^{-1/2}  \Big)dy \\ &=-k\sigma \int_{-\infty}^{\infty}\Big( \frac{1}{\sqrt{(a+2b)^2+y^2}} - \frac{1}{\sqrt{(a+b)^2+y^2}}  \Big)dy \end{aligned} $$
We can find an anti-derivative for the previous expression:
$$\begin{aligned}E_x&=-k\sigma \Big[ \ln(\sqrt{(a+2b)^2+y^2}+y)-\ln(\sqrt{(a+b)^2+y^2}+y)\Big]_{-\infty}^{\infty}\\ &=-k\sigma \lim_{d \rightarrow \infty} \Big[ \ln\Big(\frac{\sqrt{(a+2b)^2+y^2}+y}{\sqrt{(a+b)^2+y^2}+y}\Big) \Big]_{-d}^{d} \\ &=-k\sigma \lim_{d \rightarrow \infty} \Big[ \ln\Big(\frac{\sqrt{(a+2b)^2+d^2}+d}{\sqrt{(a+b)^2+d^2}+d}\Big) - \ln\Big(\frac{\sqrt{(a+2b)^2+d^2}-d}{\sqrt{(a+b)^2+d^2}-d}\Big)\Big] \end{aligned} $$
Again the first limit can be easily seen as tending to $0$ and the second one according to  Wolfram tends to  $\ln(\frac{(a+2b)^2}{(a+b)^2})$ something that is again rather convenient.
So the intensity of the field of the $-\sigma$ tape is equal to :
$$E_{-\sigma}=k\sigma \ln \Big(\frac{(a+2b)^2}{(a+b)^2}\Big)$$
This result seems right because the field diverges in $b$ and in $2$
Now if I sum the two fields:
$$E_T=E_{-\sigma}+E_{-\sigma}=-k\sigma \ln \Big(\frac{(a+b)^2}{b^2}\Big) + k\sigma \ln \Big(\frac{(a+2b)^2}{(a+b)^2}\Big)$$
Reducing the last expression and using the properties of logarithms:
$$E_T=-2k\sigma \ln \Big(\frac{(a+b)}{b}\Big) + 2k\sigma \ln \Big(\frac{(a+2b)}{(a+b)}\Big)=-2k\sigma \ln \Big(\frac{a(a+2b)}{(a+b)^2}\Big)$$
It diverges when $x=b$.
Any other methods to find the field, I tried with polar coordinates but I don't know how to do it.

How can  solve part b), I don't know how to do it.

A: You can get the field for the tape by considering an infinite sum of parallel line charges.
$$E(a)=\int_{r=0}^{r=b}E_{line}(a+r)dr$$
$E_{line}$ is pretty standard result so I'll assume it.
$$ E(a)=\int_{r=0}^{r=b}\frac{\lambda}{2\pi\epsilon_0(a+r)}dr $$
The line charge density for each line will be the surface charge density $\sigma$ divided by the width $b$. Integrating:
$$ E(a)=\left[\frac{\sigma\ln(a+r)}{2\pi\epsilon_0b}\right]_{r=0}^{r=b} $$
$$ E(a)=\frac{\sigma}{2\pi\epsilon_0b}\left[\ln(a+b)-\ln(a)\right] $$
Which, with a little massaging, agrees with your expression for the field produced by the right tape a distance $a$ in the same plane from the edge of the tape
$$ E=k\sigma\ln\left(  \frac{(a+b)^2}{a^2} \right) $$
Force per unit height: The left tape sits in the field of the right tape. An infinitesimal of charge in the left tape $\mathrm{d}q$ feels an infinitesimal force $\mathrm{d}F=E\mathrm{d}q$. Integrating up $F=\int E\mathrm{d}q=\int E\rho\mathrm{d}A$. Using $\rho=\sigma$ and appropriate boundaries:
$$F=\int_{y=0}^{y=1}\int_{a=0}^{a=b} k\sigma^2\ln\left(  \frac{(a+b)^2}{a^2} \right)\mathrm{d}a\mathrm{d}y$$
$$F=2k\sigma^2\int_{a=0}^{a=b} [\ln (a+b) -\ln (a)] \mathrm{d}a$$
Integrating by Parts
$$F=2k\sigma^2\left[ a\ln(a+b)-a\ln(a) \right]_{a=0}^{a=b} -2k\sigma^2\int_{a=0}^{a=b} \left[a\frac{1}{a+b} -a\frac{1}{a}\right] \mathrm{d}a$$
Letting $a+b=c$
$$F=2k\sigma^2b\ln(2) +2k\sigma^2b -2k\sigma^2\int_{c=b}^{c=2b} \frac{c-b}{c}  \mathrm{d}c$$
$$F=2k\sigma^2b\ln(2) +2k\sigma^2b +2k\sigma^2\left[ b\ln(c) -c\right]_{c=b}^{c=2b}$$
$$F=2k\sigma^2b\ln(2) +2k\sigma^2b +2k\sigma^2\left[b\ln(2)-b \right]$$
$$ F=4k\sigma^2b\ln(2) $$
which is the given answer.


text:
Q: In Wagtail, how can I add a form to the bottom of another model's form in the WagtailAdmin, for a OneToOneField relationship? In Wagtail, let's say I have a page like this:
class MyPage(Page):
    field_1 = RichTextField()
    field_2 = models.DateField()

    content_panels = Page.content_panels + [
        FieldPanel('field_1'),
        FieldPanel('field_2'),
    ]

And I have another model which has a one-to-one relationship with the first model:
class PageSettings(models.Model):
    page = models.OneToOneField(MyPage)
    extra_setting_1 = models.BooleanField()
    extra_setting_2 = models.CharField(max_length=50)

How can I add a form for the PageSettings model to the bottom of the Wagtail admin form for the MyPage model?
Bonus points for a way to do it with generic relationships.

A: class MyPage(Page):
    field_1 = RichTextField()
    field_2 = models.DateField()

    content_panels = Page.content_panels + [
        FieldPanel('field_1'),
        FieldPanel('field_2'),
        InlinePanel('settings', label='Settings', min_num=1, max_num=1),
    ]

class PageSettings(models.Model):
    page = ParentKey(MyPage, related_name='settings')
    extra_setting_1 = models.BooleanField()
    extra_setting_2 = models.CharField(max_length=50)


text:
Q: addClass - new class not being recognized I have one text-box. That I'm using for two different entries depending on radio button. When radio-button is selected I change the name attribute and remove old class and add new class (keyup-numeric or keyup-charNumOnly) . Depending on the class there is edit functions performed.Using Chrome DEV Tools, I see the class is changing as expected (back in forth no problem). But the keyup-numeric function is the only one that gets performed. I'm new to JQUERY. So this may be oblivious.
Thanks for help.

$(document).ready(function() {
  $("#radio1").click(function() {
  $('p.error-keyup-1').remove();
  $("#requestedInput").val("Update Address using Account Number").attr('name','acctNumber').attr('maxlength','10');
  $("#requestedInput").removeClass().addClass('inputNumTextBox keyup-numeric');
 });
  $("#radio2").click(function() {
  $('p.error-keyup-1').remove();
   $("#requestedInput").val("Update Account Number using Address").attr('name', 'Address').attr('maxlength','23');
  $("#requestedInput").removeClass().addClass('inputNumTextBox keyup-charNumOnly');
 } );

  $('.keyup-numeric').keyup(function() {
  $('p.error-keyup-1').remove();
  var inputVal = $(this).val();
  var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
  var AcctReg9 = /^9/;
  if(!numericReg.test(inputVal)) {
   $('
Numeric characters only
').appendTo('#enterRequestDataSection');
  }
  if(!AcctReg9.test(inputVal)) {
   $('
Accounts Start with 9 .... Required
').appendTo('#enterRequestDataSection');
  }
  if ($('#requestedInput').val().length==0) {
    $('p.error-keyup-1').remove();
   }
  });

 $('.keyup-charNumOnly').keyup(function() {
  alert('keyup-charNumOnly I');
  $('p.error-keyup-1').remove();
  var inputVal = $(this).val();
  var characterReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
  if(!characterReg.test(inputVal)) {
   alert('keyup-charNumOnly II');
   $('
cRAP
').appendTo('#enterRequestDataSection');
  }
  if ($('#requestedInput').val().length==0) {
    $('p.error-keyup-1').remove();
   }
  });

});    // End of JQUERY CODE

<input type="radio" id="radio1" name="radio" value="radioAcctInp" checked="checked" >Account&nbspNumber

<input type="radio" id="radio2" name="radio" value="radioSwiftInp" >Show&nbspalphaNumeric&nbspAddress

<input type="text" id="requestedInput" name="acctNumber" value="Update Address using Account Number" maxlength="10" class="inputNumTextBox keyup-numeric">

Show Details

Add New

A: The keyUpCharNumOnly class doesn't exists when the keyup event is bound after document(ready(.
You will want to use:
$('.keyup-charNumOnly').on('keyup', function() {

A: Try this:
$(document).ready(function() {
    $("#radio1").click(function() {
        $('p.error-keyup-1').remove();
        $("#requestedInput").val("Update Address using Account Number").attr('name','acctNumber').attr('maxlength','10');
        $("#requestedInput").removeClass().addClass('inputNumTextBox keyup-numeric');
    });
    $("#radio2").click(function() {
        $('p.error-keyup-1').remove();
        $("#requestedInput").val("Update Account Number using Address").attr('name', 'Address').attr('maxlength','23');
        $("#requestedInput").removeClass().addClass('inputNumTextBox keyup-charNumOnly');
    } );

$(document).on('keyup', "#requestedInput.keyup-numeric", function() {
        $('p.error-keyup-1').remove();
        var inputVal = $(this).val();
        var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
        var AcctReg9 = /^9/;
        if(!numericReg.test(inputVal)) {
            $('
Numeric characters only
').appendTo('#enterRequestDataSection');
        }
        if(!AcctReg9.test(inputVal)) {
            $('
Accounts Start with 9 .... Required
').appendTo('#enterRequestDataSection');
        }
        if ($('#requestedInput').val().length==0) {
                $('p.error-keyup-1').remove();
            }
        });

$(document).on('keyup', "#requestedInput.keyup-charNumOnly", function() {
        alert('keyup-charNumOnly I');
        $('p.error-keyup-1').remove();
        var inputVal = $(this).val();
        var characterReg = /^\s*[a-zA-Z0-9,\s]+\s*$/;
        if(!characterReg.test(inputVal)) {
            alert('keyup-charNumOnly II');
            $('
cRAP
').appendTo('#enterRequestDataSection');
        }
        if ($('#requestedInput').val().length==0) {
                $('p.error-keyup-1').remove();
            }
        });

});    // End of JQUERY CODE


text:
Q: Mysql Deadlock on table that has autogenerated primary key and unique key I have a table sdr with an autogenerated primary key and a unique key. Randomly I get these deadlock errors as shown below. It is a hibernate based web application firing these insert queries.
After reading mysql documentation on https://dev.mysql.com/doc/refman/5.6/en/innodb-record-level-locks.html, it seems it could be resolved using READ_COMMITTED. Incidentally, the database is already set to tx_isolation = READ-COMMITTED.
I cannot remove the unique key because the business logic needs to check if the record already exists. Also, UI provides the unique key values for read operations.
I also cannot remove the auto generated primary column due to downstream application impacts.
Can this issue be fixed with the stated constraints?
More details:
Mysql 5.6 InnoDB
TABLE  statement:
     CREATE TABLE `sdr` (
        `s_d_r_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        `fk_d_r_id` bigint(20) unsigned NOT NULL,
        `fk_s_s_id` int(10) unsigned NOT NULL,
        `t_l_x_no` int(10) unsigned NOT NULL,
        `t_l_y_no` int(10) unsigned NOT NULL,
        `h_no` int(11) DEFAULT NULL,
        `w_no` int(11) DEFAULT NULL,
        `o_tx` varchar(4000) DEFAULT NULL,
        `f_d_c_tx` varchar(4000) DEFAULT NULL,
        `l_c_no` int(10) unsigned NOT NULL DEFAULT '0',
         `d_in` tinyint(1) NOT NULL DEFAULT '0',
        `c_ts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
         `c_u_id` bigint(20) unsigned NOT NULL,
        `l_m_ts` timestamp NOT NULL DEFAULT '1970-01-01 05:00:00',
         `l_m_user_id` bigint(20) unsigned NOT NULL,
         `r_no` decimal(3,0) NOT NULL DEFAULT '0',
         PRIMARY KEY (`s_d_r_id`),
        UNIQUE KEY `uk_s_d_r` (`fk_d_r_id`,`fk_s_s_id`,`t_l_x_no`,`t_l_y_no`,`r_no`),
    KEY `i_s_fk_s_s_id` (`fk_s_s_id`),
        CONSTRAINT `r_d_s` FOREIGN KEY (`fk_d_r_id`)
        REFERENCES `d_r` (`D_R_ID`)  ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `r_s_s` FOREIGN KEY (`fk_s_s_id`)
    REFERENCES `s_s` (`s_s_id`)
         ON DELETE NO ACTION ON UPDATE NO ACTION )
        ENGINE=InnoDB AUTO_INCREMENT=45904 DEFAULT CHARSET=utf8;

Deadlock log:
    2015-10-11 09:25:18 7f30cb700700InnoDB: transactions deadlock detected,
 dumping detailed information.
        2015-10-11 09:25:18 7f30cb700700
        *** (1) TRANSACTION:
        TRANSACTION 276584110286, ACTIVE 1 sec inserting
        mysql tables in use 1, locked 1
        LOCK WAIT 4 lock struct(s), heap size 1184, 2 row lock(s),
    undo log entries 1
        MySQL thread id 31640, OS thread handle 0x7f3510eff700, query id
    1796766867 server-1 21.222.12.123 db_user update
        insert into S_D_R (
    D_IN, L_C_NO, C_TS, C_U_ID, L_M_TS, L_M_U_ID,
    F_D_C_TX, FK_D_R_ID, H_NO, FK_S_S_ID, O_TX,
    T_L_X_NO, T_L_Y_NO, W_NO) values
    (0, 0, '2015-10-11 13:25:18.036', 123, '2015-10-11 13:25:18.036',
    123, '[]', 1234567, -1, 3, 'some', 555, 678, -1)
        *** (1) WAITING FOR THIS LOCK TO BE GRANTED:
        RECORD LOCKS space id 4577 page no 9296 n bits 528 index
    `uk_s_d_r` of table `test`.`s_d_r` trx id 276584110286
    lock mode S waiting
        *** (2) TRANSACTION:
        TRANSACTION 276584110033, ACTIVE 1 sec inserting
        mysql tables in use 1, locked 1
        7 lock struct(s), heap size 1184, 9 row lock(s),
     undo log entries 7
        MySQL thread id 32293, OS thread handle 0x7f30cb700700,
    query id 1796767643 server-2 21.222.12.124 db_user update
        insert into S_D_R (
    D_IN, L_C_NO, C_TS, C_U_ID, L_M_TS, L_M_U_ID,
    F_D_C_TX, FK_D_R_ID, H_NO, FK_S_S_ID, O_TX, T_L_X_NO,
    T_L_Y_NO, W_NO) values (0, 0, '2015-10-11 13:25:18.081', 123,
    '2015-10-11 13:25:18.081', 123, '[]', 6789064, -1, 7,
    'someother', 550, 15, -1)
        *** (2) HOLDS THE LOCK(S):
        RECORD LOCKS space id 4577 page no 9296 n bits 528 index
    `uk_s_d_r` of table `test`.`s_d_r` trx id 276584110033
    lock_mode X locks rec but not gap
        *** (2) WAITING FOR THIS LOCK TO BE GRANTED:
        RECORD LOCKS space id 4577 page no 9296 n bits 536 index
    `uk_s_d_r` of table `test`.`s_d_r` trx id 276584110033
    lock_mode X locks gap before rec insert intention waiting
        *** WE ROLL BACK TRANSACTION (1)

A: Some more code of your insert / update statements would be helpful to determine if concurrency is being done properly and released when completed.  It appears that something is holding onto the database when the next call comes in.  Are these being done in Transactions or single statements?


text:
Q: Error while running ARA server on Alpine linux I am trying to install the latest version of the Ansible Records Analyzer server on an alpine Linux I made sure that all requirements are well installed ( Django, GCC,python3, Pypi, ansible) the install went well except for a warning about the absence of root PATH on the PATH variable which I fixed:
The warning :
  WARNING: The script pbr is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

The fix:
~ # export PATH=/root/.local/bin:$PATH

So following the install guide on this step that intends to run the server I have an avalanche of errors as if the run command doesn't find the needed components to be executed although I'm sure all the components are installed :
~ # ara-manage runserver
[ara] No setting found for SECRET_KEY. Generating a random key...
Traceback (most recent call last):
  File "/root/.local/bin/ara-manage", line 8, in <module>
    sys.exit(main())
  File "/root/.local/lib/python3.8/site-packages/ara/server/__main__.py", line 41, in main
    if not os.path.exists(settings.ARA_SETTINGS):
  File "/root/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 79, in __getattr__
    self._setup(name)
  File "/root/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 66, in _setup
    self._wrapped = Settings(settings_module)
  File "/root/.local/lib/python3.8/site-packages/django/conf/__init__.py", line 157, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/root/.local/lib/python3.8/site-packages/ara/server/settings.py", line 263, in <module>
    ALLOWED_HOSTS=ALLOWED_HOSTS.to_list(),
AttributeError: 'list' object has no attribute 'to_list'

What could be the reason behind this behavior?

A: Well I managed to overcome this issue, the problem was in dynaconf the current version 3.1.3 doesn't read the conf files properly which fails in the server run.
Meanwhile, the only workaround is to install the previous version of dynaconf :
pip install 'dynaconf==3.1.2'

FYI dynaconf already has a fix proposed for the regression: rochacbruno/dynaconf#541
I've tested that it does resolve this issue and it will be released in dynaconf 3.1.4 soon.


text:
Q: When I'm trying to use mat tree's nestedControl's expandAll method it generates this error When I'm trying to use mat tree's nestedControl's expandAll method it generates this error. How can I fix this? I will appreciate any help.
error

Code


text:
Q: How to pick a random element from an array that matches a certain criteria in O(1) I have a list of recipes obtained from a database that looks like this:
List<RecipeNode> _recipeList;

RecipeNode, among other things, has a property that references one or more tags (Such as Dinner, Breakfast, Side, Vegetarian, Holiday, and about 60 others).
   public sealed class RecipeNode
   {
      public Guid RecipeId;
      public Byte[] Tags; //Tags such as 1, 5, 6, 8, 43
      //... More stuff
   }

Finding a random recipe from _recipeList in O(1) would of course be easy, however what I need to do is find a random recipe that has, say, 5 in the Tags in O(1).
Right now, my only idea is to make an array of List<RecipeNodes>, keyed by tag.  For example:
List<RecipeNode>[] _recipeListByTag;

Then, _recipeListByTag[5] would contain a list of all the recipes that have a 5 in the Tags array.  I could then choose a random allowed tag and a random recipe within that tag in O(1).
The drawback of this approach is the size of this multidimensional array would be Recipes * Tags (eg, the sum of Tags.length across all recipes), which starts to take up a lot of memory since I'm storing a potentially huge number of recipes in this array.  Of course, since RecipeNode is a reference type, I'm only repeating the 4byte pointers to the recipes, so this still might be the best way to go.
Is there a more efficient data structure or algorithm I could use to allow me to find a random recipe that contains a certain allowed tag?  Thanks!

A: List<RecipeNode>[] _recipeListByTag is probably the best approach for you, and its size is not Recipes * Tags because each list in the array will only contain as many recipes as match a tag, and not more.  Its size would become Recipes * Tags if every single recipe contained every single tag.
If the amount of memory occupied by your data structures is so very dear to you, do not forget to call List.TrimExcess() after you have populated each list.

A: Is this homework? I doubt any real-world recipe program would require O(1) access to tags, and be too slow for using a database. I also doubt any real-world recipe would have numeric tags. Understanding the real domain can help provide a better answer.
However, if it really is about recipes and numeric tags, and if you only have 256 tags, why don't you just choose a random recipe 1 million times? The odds of not finding a recipe with the required tag are minimal, and the complexity is still O(1). If you don't like the odds, choose a random recipe 10^20 times. The complexity is still O(1).
UPDATE:
Since it's not the O(1) you're worried about, but rather the time it takes to pick a random recipe, I suggest you let your database handle this for you - the same database that holds all the recipes anyway, and the same database you're going to access to show the random recipe.
You can SELECT a random record in SQL Server this way: SQL Server Random Sort . If you're using some other database, there are other ways: http://www.petefreitag.com/item/466.cfm . Just make sure your WHERE clause has Tag=17 in it.

A: If you want to keep the data in memory, you won't do much better than a list of (4 byte) pointers for each tag. If you can use a DB... well, others have already posted about that. Depending on how huge is "huge", you might just fork out some $$$ to add RAM to the target machine.
If you do want to keep the data in memory, but want to be ridiculously parsimonious with memory, you could try to squeeze down the 4 bytes per tag-recipe combination. For example, keep all the recipes in a big array, and (assuming you won't have more than about a million) store array indexes in 3 bytes each.
To go even further, you could divide the recipes with a given tag into equally-sized "buckets" (each occupying a contiguous area of the big array), store a starting index for each "bucket" (in 3-4 bytes), and then store a list of delta values between indexes of consecutive recipes with the given tag. Encode the delta values using an array of bytes, in such a way that a single delta value can use anything from 1-4 bytes, as required.
Because the number of recipes in a "bucket" will be limited to a constant number, retrieval using this approach is still O(1).
(I have done embedded programming on micros with as little as 256 bytes of RAM... when you do that you start thinking of very creative ways to save bytes or even bits. I'm sure that going to such lengths will not be necessary in your application, but I thought this was an interesting idea.)

A: I would make an export from the source list to another with references to all elements that suit you.   There make a random choosing and take an element from the source list, according to the reference.
If there is a possibility that you again coud use the same derived list, put such lists into a greater list of them.
(Of cource, the chosen algorithm depends on the real statistics of your list.)
If you use only one parameter, you could order your list by this parameter and remember in another list B of it references to where the elements with the same parameter value start.  Later you could simply take random in the interval (B[4];b[5]-1). This would make the speed of a random choosing equal to O(const).

A: In this case, I would, personally, go for SQlite solution (as I, personally, know it's better then others). I see that you worry about a space, and not performance in terms of speed, but in terms of constant recovery time, you worry about flexibility of data access too. Imo, in this case, SQlite is way to go.
Design your small DB in a way you like and execute queries and joins in a way you want.
This is old but always valid example of how can you use it.
There is also, naturally, ORM solution (for example LINQ driver), but to me personally it seems kind of overhead.
Hope this helps.


text:
Q: Maximum recursion with large lists I am making a binary tree with a very large list, almost 10000 objects. The issue is that I get a maximum recursion error due to the huge size. It happens specifically in  the binarytree class where TreeNode is being called to create new objects. I am unsure how to implement this without recursion, as it seems to be the easiest way to implement the code.
class TreeNode:
def __init__(self,key,val,left=None,right=None,parent=None):
    self.key = key
    self.payload = val
    self.leftChild = left
    self.rightChild = right
    self.parent = parent

def hasLeftChild(self):
    return self.leftChild

def hasRightChild(self):
    return self.rightChild

def isLeftChild(self):
    return self.parent and self.parent.leftChild == self

def isRightChild(self):
    return self.parent and self.parent.rightChild == self

def isRoot(self):
    return not self.parent

def isLeaf(self):
    return not (self.rightChild or self.leftChild)

def hasAnyChildren(self):
    return self.rightChild or self.leftChild

def hasBothChildren(self):
    return self.rightChild and self.leftChild

Binary Tree:
class BinarySearchTree:

def __init__(self):
    self.root = None
    self.size = 0

def length(self):
    return self.size

def __len__(self):
    return self.size

def put(self,key,val):
    if self.root:
        self._put(key,val,self.root)
    else:
        self.root = TreeNode(key,val)
    self.size = self.size + 1

def _put(self,key,val,currentNode):
    if key < currentNode.key:
        if currentNode.hasLeftChild():
               self._put(key,val,currentNode.leftChild)
        else:
               currentNode.leftChild = TreeNode(key,val,parent=currentNode)
    else:
        if currentNode.hasRightChild():
               self._put(key,val,currentNode.rightChild)
        else:
               currentNode.rightChild = TreeNode(key,val,parent=currentNode)

def __setitem__(self,k,v):
   self.put(k,v)

def get(self,key):
   if self.root:
       res = self._get(key,self.root)
       if res:
              return res.payload
       else:
              return None
   else:
       return None

def _get(self,key,currentNode):
   if not currentNode:
       return None
   elif currentNode.key == key:
       return currentNode
   elif key < currentNode.key:
       return self._get(key,currentNode.leftChild)
   else:
       return self._get(key,currentNode.rightChild)

def __getitem__(self,key):
   return self.get(key)

def __contains__(self,key):
   if self._get(key,self.root):
       return True
   else:
       return False

A: It is fairly simple to convert your recursive methods to iterative ones, e.g.:
def get(self, key):
   node = self.root
   while node:
      if node.key == key:
         return node.payload
      elif key < node.key:
         node = node.leftChild
      else:
         node = node.rightChild
   return None

def put(self, key, val):
    if not self.root:
        self.root = TreeNode(key, val)
    else:
        self._put(key, val, self.root)
    self.size = self.size + 1

def _put(self, key, val, currentNode):
    while True:
        if key < currentNode.key:
            if currentNode.hasLeftChild():
                currentNode = currentNode.leftChild
            else:
                currentNode.leftChild = TreeNode(key, val, parent=currentNode)
                break
        else:
            if currentNode.hasRightChild():
                currentNode = currentNode.rightChild
            else:
                currentNode.rightChild = TreeNode(key, val, parent=currentNode)
                break

This gets rid of any recursion (limits) and is just as readable.


text:
Q: Git not working in NanoServer (in Docker) I need to install Git in Nano Server. During my research I saw that Nano Server can't work with MSI files and that's why that I thought I can easily download it in another container (Windows Server Core in my situation) and move the contents of Git to the other container (the Nano Server container) (Idea is from here: https://stefanscherer.github.io/how-to-build-nodejs-nanoserver-image/). I tried with the following dockerfile:
FROM mcr.microsoft.com/windows/servercore:ltsc2019
RUN powershell Invoke-WebRequest -outfile gitsetup.exe https://github.com/git-for-windows/git/releases/download/v2.7.0.windows.1/Git-2.7.0-64-bit.exe

RUN setx /M Path "%Path%;c:\git\cmd;c:\git\bin;c:\git\usr\bin"

RUN powershell -command start-process .\gitsetup.exe -ArgumentList '/VERYSILENT /SUPPRESSMSGBOXES /CLOSEAPPLICATIONS /DIR=c:\git' -Wait

FROM mcr.microsoft.com/dotnet/core/sdk:3.1.101-nanoserver-1909

USER ContainerAdministrator
RUN setx /M Path "%Path%;c:\git\cmd;c:\git\bin;c:\git\usr\bin"
COPY --from=0 "c:\git\cmd" "c:\git\cmd"
COPY --from=0 "c:\git\bin" "c:\git\bin"
COPY --from=0 "c:\git\usr\bin" "c:\git\usr\bin"
USER ContainerUser
RUN git version

But when I try to build the image, I get the following error after the Step 12/14 : RUN git version hangs for a while:

The command 'cmd /S /C git version' returned a non-zero code:
  3221225495 Bus error

I thought ok, that's simple, I'll just remove the RUN git version from the dockerfile and run the command directly in the container after the image has successfully been built, so that I can check what is the actual error. But when I call git in the attached container, it just hangs for a few seconds and does nothing (like I didn't type any command). Any ideas?
PS: I don't want MinGit (even though MinGit works in Nano Server for some reason) because I use NPM, which spawns git commands (to download a specific commit from GitHub) that do not exist in MinGit.
PS2: I can't change my main container to Windows Server Core, since I am using it  with .NET Core and Windows Containers. The SDK is only available with a Nano Server build.
Edit: I tried @Voc's answer and it works. For anyone that wants the exact code dockerfile:
FROM mcr.microsoft.com/windows/servercore:ltsc2019

RUN setx /M Path "c:\git\cmd;c:\git\bin;c:\git\usr\bin;%Path%;c:\gcc\bin;c:\7zip"

RUN powershell -command Invoke-WebRequest -outfile portableGit.7z.exe https://github.com/git-for-windows/git/releases/download/v2.26.0.windows.1/PortableGit-2.26.0-64-bit.7z.exe
RUN powershell -command Invoke-WebRequest -UserAgent 'DockerCI' -outfile 7zsetup.exe http://www.7-zip.org/a/7z1514-x64.exe
RUN powershell -command start-process .\7zsetup.exe -ArgumentList '/S /D=c:/7zip' -Wait

RUN powershell 7z x portableGit.7z.exe -ogit

FROM mcr.microsoft.com/dotnet/core/sdk:3.1.101-nanoserver-1909

USER ContainerAdministrator
RUN setx /M Path "C:\git\bin;C:\git\usr\bin;C:\git\mingw64\bin;C:\nodejs;%Path%"
COPY --from=0 "c:\git" "c:\git"
RUN git version

A: First, you don't have to run the GIt for Windows setup.
You could also try and uncompress the Portable extractable archive PortableGit-2.26.0-64-bit.7z.exe anywhere you want in the image, and then add to the path:
set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%


text:
Q: Can I modify [appname].exe.config without having to manually read/write the XMl? I have created some settings in a C# application using .NET 3.5 and Visual Studio 2008 Express. I have a number of application-scoped settings which I would like to be able to modify from within the application - I can access them through Properties.Settings.Default but they are read only as expected. I do not want to have to make these become user-scoped settings as they should be application-wide. Is this possible without loading the XML and reading/writing from/to it myself?
I have seen examples using System.Configuration.ConfigurationManager.OpenExeConfiguration, but the config xml looks to be in a different format to that which I am using (is this from an older version?)
Thanks

Edit
I worked out that I can modify the values doing this, but it seems like a ridiculous hack.
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
SettingElementCollection settingElements = ((ClientSettingsSection)config.GetSectionGroup("applicationSettings").Sections[0]).Settings;

SettingElement element = settingElements.Get("SettingName");
element.Value.ValueXml.InnerText = "new value";

config.Save(ConfigurationSaveMode.Modified, true);

A: OpenExeConfiguration (or any of the other ConfigurationManager methods) is the preferred entry point for most modifications to configuration files. Once you have a Configuration instance you should get the section you wish to modify and after the modifications call any of the ConfigurationManager.Save methods. However, it is impossible to retrieve the applicationSettings section this way.
There is no API for changing settings from the applicationSettings section in your app.config file. Only user-scoped settings can be changed this way.
So actually changing these settings can only be done by directly manipulating the app.config XML file.
Some confusion may occur because the indexed property from Properties.Settings.Default is actually writable. The following is perfectly legal:
Properties.Settings.Default["MySetting"] = "New setting value";
Properties.Settings.Default.Save();

However, the setting will not be saved.

A: You could also use the Windows Registry to store app-specific state.  There are per-user and per-machine keys in the registry - either or both are available to you . For example, some people use the registry to store the location and size of the app window upon exit.  Then when the app is restarted, you can position and size the window according to its last known size.  This is a small example of the sort of state you can store in the registry.
To do it you would use different APIs for storage and retrieval. Specifically the SetValue and GetValue calls on the Microsoft.Win32.RegistryKey class. There may be libraries that are helpful in persisting complex state to the registry.  If you have simple cases ( a few strings and numbers) then it is easy to just do it yourself.
  private static string _AppRegyPath = "Software\\Vendor Name\\Application Name";

  public Microsoft.Win32.RegistryKey AppCuKey
  {
      get
      {
          if (_appCuKey == null)
          {
              _appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(_AppRegyPath, true);
              if (_appCuKey == null)
                  _appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(_AppRegyPath);
          }
          return _appCuKey;
      }
      set { _appCuKey = null; }
  }

  private void RetrieveAndApplyState()
  {
      string s = (string)AppCuKey.GetValue("textbox1Value");
      if (s != null) this.textbox1.Text = s;

      s = (string)AppCuKey.GetValue("Geometry");
      if (!String.IsNullOrEmpty(s))
      {
          int[] p = Array.ConvertAll<string, int>(s.Split(','),
                           new Converter<string, int>((t) => { return Int32.Parse(t); }));
          if (p != null && p.Length == 4)
          {
              this.Bounds = ConstrainToScreen(new System.Drawing.Rectangle(p[0], p[1], p[2], p[3]));
          }
      }
  }

  private void SaveStateToRegistry()
  {
      AppCuKey.SetValue("textbox1Value", this.textbox1.Text);

      int w = this.Bounds.Width;
      int h = this.Bounds.Height;
      int left = this.Location.X;
      int top = this.Location.Y;

      AppCuKey.SetValue("Geometry", String.Format("{0},{1},{2},{3}", left, top, w, h);
  }

  private System.Drawing.Rectangle ConstrainToScreen(System.Drawing.Rectangle bounds)
  {
      Screen screen = Screen.FromRectangle(bounds);
      System.Drawing.Rectangle workingArea = screen.WorkingArea;
      int width = Math.Min(bounds.Width, workingArea.Width);
      int height = Math.Min(bounds.Height, workingArea.Height);
      // mmm....minimax
      int left = Math.Min(workingArea.Right - width, Math.Max(bounds.Left, workingArea.Left));
      int top = Math.Min(workingArea.Bottom - height, Math.Max(bounds.Top, workingArea.Top));
      return new System.Drawing.Rectangle(left, top, width, height);
  }

That code uses Microsoft.Win32.Registry.CurrentUser, and so it sets and retrieves user-specific app settings.  If you are setting or retrieving machine-wide state, you want Microsoft.Win32.Registry.LocalMachine.


text:
Q: $_{m}A=0\Leftrightarrow \text{Ext}{{\left( A,\mathbb{Z} \right)}_{m}}=0$
For any abelian group $A$, let $mA=\left\{ b\in A\mid b=ma,a\in A \right\}$, $_{m}A=\left\{ a\in A\mid ma=0 \right\}$, ${{A}_{m}}=A/mA$. Prove: $_{m}A=0\Leftrightarrow \text{Ext}{{\left( A,\mathbb{Z} \right)}_{m}}=0$.

I know the $0{{\to }_{m}}A\to A\to mA\to 0$ is an exact sequence and $Hom\left( _{m}A,\mathbb{Z} \right)=0$. So $0\to Ext\left( mA,\mathbb{Z} \right)\to Ext\left( A,\mathbb{Z} \right)\to Ext\left( _{m}A,\mathbb{Z} \right)\to 0$ is an exact sequence.

A: Here is a proof in a two steps:
1)
Let $m \in \mathbb Z$ also denote the multiplication $\mathbb Z \xrightarrow{\cdot m} \mathbb Z$.
$0=A_m=A/mA$ is equivalent to the surjectivity of $A \xrightarrow{\cdot m} A$ or in other words: The functor $\operatorname{Hom}(-,A)$ takes $m$ to a surjective map.
$0={}_mA=\{a \in A|ma=0 \}$ is equivalent to the injectivity of $A \xrightarrow{\cdot m} A$ or in other words: The function $- \otimes A$ takes $m$ to an injective function. Note that the dual functor $\operatorname{Hom}(-,\mathbb Q/\mathbb Z)$ is not only exact, but it also reflects injections, i.e. the above is equivalent to the statement that the functor $\operatorname{Hom}(- \otimes A,\mathbb Q/\mathbb Z)$ takes $m$ to a surjective map.
Thus we have shown:
$0={}_mA$ is equivalent to the fact that the functor $\operatorname{Hom}(- \otimes A,\mathbb Q/\mathbb Z)$ takes $m$ to a surjective map.
$\operatorname{Hom}(A,\mathbb Q/\mathbb Z)_m=0$ is equivalent to the fact that the functor $\operatorname{Hom}(-,\operatorname{Hom}(A,\mathbb Q/\mathbb Z))$ takes $m$ to a surjective map.
By tensor-hom adjunction these are the same functors, i.e. we have shown
$$0={}_mA \Longleftrightarrow \operatorname{Hom}(A,\mathbb Q/\mathbb Z)_m=0.$$
2)
Now consider the commutative diagram of exact sequences
$$\require{AMScd}
\begin{CD}
0 @>>> \mathbb Z @>>> \mathbb Q @>>> \mathbb Q/\mathbb Z @>>> 0 \\
{} @VV{\cdot m}V @VV{\cdot m}V @VV{\cdot m}V \\
0 @>>> \mathbb Z @>>> \mathbb Q @>>> \mathbb Q/\mathbb Z @>>> 0
\end{CD}$$
Apply $\operatorname{Hom(A,-)}$ to get a commutative diagram of long exact sequences:
$$\require{AMScd}
\begin{CD}
0 @>>> \operatorname{Hom}(A,\mathbb Z) @>>> \operatorname{Hom}(A,\mathbb Q) @>>> \operatorname{Hom}(A,\mathbb Q/\mathbb Z) @>>> \operatorname{Ext}^1(A,Z) @>>> 0 \\
{} @VV{\cdot m}V @VV{\cdot m}V @VV{\cdot m}V @VV{\cdot m}V \\
0 @>>> \operatorname{Hom}(A,\mathbb Z) @>>> \operatorname{Hom}(A,\mathbb Q) @>>> \operatorname{Hom}(A,\mathbb Q/\mathbb Z) @>>> \operatorname{Ext}^1(A,Z) @>>> 0
\end{CD}$$
Of course we can make this into short exact sequences:
$$\require{AMScd}
\begin{CD}
0 @>>> \operatorname{Hom}(A,\mathbb Q)/\operatorname{Hom}(A,\mathbb Z) @>>> \operatorname{Hom}(A,\mathbb Q/\mathbb Z) @>>> \operatorname{Ext}^1(A,Z) @>>> 0 \\
{} @VV{\cdot m}V @VV{\cdot m}V @VV{\cdot m}V \\
0 @>>> \operatorname{Hom}(A,\mathbb Q)/\operatorname{Hom}(A,\mathbb Z) @>>> \operatorname{Hom}(A,\mathbb Q/\mathbb Z) @>>> \operatorname{Ext}^1(A,Z) @>>> 0
\end{CD}$$
Now it is easy to see that $\operatorname{Hom}(A,\mathbb Q)$ is divisible for any $A$, hence $\operatorname{Hom}(A,\mathbb Q)/\operatorname{Hom}(A,\mathbb Z)$ is also divisible as a quotient. Thus the left vertical map is surjective, i.e. by the snake lemma the middle vertical map is surjective if and only if the right vertical map is. Thus we have shown:
$$\operatorname{Hom}(A,\mathbb Q/\mathbb Z)_m=0 \Longleftrightarrow \operatorname{Ext}^1(A,Z)_m=0.$$
This completes the proof.


text:
Q: How to connect to intranet over VPN if on the same subnet? I have a VPN Server running at home a few thousand kilometers away, providing access to my network on 192.168.0.x. This works perfectly in most cases, but once I am in a network that is using the same subnet 192.168.0.x it will fail.
Unfortunatelly this is sometimes the case and I can not change either of the subnets. Is there a way to reconfigure my remote VPN server to overcome this issue?

A: maybe adding specific routes to specific remote server, hoping it doesn't have another IP you need to access on your corporate network.
https://technet.microsoft.com/en-us/library/cc757323%28v=ws.10%29.aspx


text:
Q: round corners for text input in flash i im using the text input component in flash as2,but i need text input with round corners, is there a script that can do it? or somthing?
thanks

A: You'll need to turn off the outlines on your textfield, and just put a graphic of a box with rounded corners underneath it. There's no way to customize the display of the default textfield outlines, if you have them enabled.


text:
Q: Multitouch Trackpad Gestures Dell XPS 15 I'm trying to enable some multitouch gestures to mirror what OS X is capable of doing, such as brushing three fingers across the trackpad to switch desktops, swiping two fingers to navigate back in nautilus or firefox etc. I'm trying to use touchegg, but I'm not sure if ubuntu sees my trackpad as a device with more than two finger support. Two finger scrolling works fine.

*

*Does touchegg work in Ubuntu 12.04?

*How can I find out if my trackpad (Dell XPS L502x) supports 3+ finger support in Ubuntu?

*Are there any compiz plugins that might help?

I have a friend who is trying to achieve the same thing on his Sony Vaio, because he can do most of the aforementioned gestures in Windows.
Thanks for any help!

A: Touchegg doesn't work for me in 12.04, and seems its a confirmed bug:
https://bugs.launchpad.net/ubuntu/+source/touchegg/+bug/918551
As for the rest I have no idea, sorry. Would like to know for my own laptop!


text:
Q: How do you group pandas dataframe rows based on permutation of booleans? Imagine there is a pandas dataframe with five columns and n rows. Each column holds a boolean value.
Maths says there should be 32 permutations of boolean values.
How do I group them by the permutation of boolean values associated with each row so I can get a count on each group or return other properties?
For example, how do I find out how many rows associated with TTTTTs or TTTTFs or whatever permutation I'm interested in?

A: There are a couple of ways of doing this. One way would be to just group by all the columns you care about at once. If you want the counts, you can call the GroupBy.count method on the result:
df.groupby(['c1', 'c2', 'c3', 'c4', 'c5']).count()

Or more simply, if all the columns are of interest:
df.groupby(list(df.columns)).count()

You could also convert the booleans to a number, and group on that:
df['Num'] = (df.to_numpy() << [4, 3, 2, 1, 0]).sum(0)
df.groupby('Num').count()

A more general solution that does not require creating a new column could use value_counts
names = ['c1', 'c2', 'c3', 'c4', 'c5']
pd.Series((df[names].to_numpy() << np.arange(len(names))).sum(0)).value_counts()

Which you can very conveniently rewrite as
pd.Series.value_counts((df[names].to_numpy() << np.arange(len(names))).sum(0))


text:
Q: " 'pattern' must be a non-empty character string" error with agrep in R I am receiving the following error:
'pattern' must be a non-empty character string

when trying to run the following:
rapply(as.list(Database1), function(x) agrep(x,Database2, max.distance=c(cost=1), value=T))

with large databases
> length(Database1)
[1] 15876500

> length(Database2)
[1] 605

But not when I run it with small ones
> length(Database1)
[1] 29

> length(Database2)
[1] 8

I know I should put up reproducible code so the databases are just 15-25 character strings of random letters that can be generated using the following:
Database1<- unlist(replicate(n, paste0(sample(LETTERS, m), collapse="")))

where "n" is the length and "m" is an integer between 15-25.

A: Well I can get that error message by supplying "" to pattern.  as seen here but not with other potentially bad patterns:
agrep("", "hello")
agrep(" ", "hello")
agrep(NA, "hello")
agrep(NULL, "hello")

## > agrep("", "hello")
## Error in agrep("", "hello") :
##   'pattern' must be a non-empty character string

## > agrep(" ", "hello")
## [1] 1

## > agrep(NA, "hello")
## [1] NA

## > agrep(NULL, "hello")
## Error in agrep(NULL, "hello") : invalid 'pattern' argument

So I'm guessing you got a "" in Database`.  To check use:
which(Database1 == "")

EDIT:
Use:
rapply(as.list(Database1), function(x) {
    try(agrep(x,Database2, max.distance=c(cost=1), value=T))
)

This will tell you where the errors are and then you can hone in on that element and figure out what's causing it.  I'd try on multiple subsets of the data.


text:
Q: Creating a Value List Using Values from Another Table in Laravel I have a simple database application that records contacts (name, address, etc.). I am trying to draw on various other tables to generate value lists for the forms. Then I would like to have all form values entered by the user to be saved into the appropriate tables on submit.
For example, I have the people table which includes the name and address. I have a title table with the different possible values for the title (i.e. Mr., Mrs., Ms. Dr.). Upon filling in the contact form, I would like to generate the values for the title field in the form from the title table. I am trying to do this one model for Contact that includes separate classes for the people table and the title table.
In my ContactController.php I have:
class ContactController extends Controller {

    public function index()
    {

        $people = Contact::all();

        // return main homepage for Contacts section
        return view('pages.contacts.home', compact('people'));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $title = Contact::lists('title', 'id');
        return view('pages.contacts.create');
    }

In my Contact.php model I have the following:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Contact extends Model {

    protected $table = 'people';

    protected $fillable = [

        'title_id',
        'name_first',
        'name_middle',
        'name_last',
        'date_birth',
        'date_death',
        'bio',
        'created_at',
        'modified_at'

    ];

    public function title() {

        return $this->belongsTo('Title', 'title_id', 'id');

    }
}

class Title extends Model {

    protected $table = 'title';

    protected $fillable = [

        'title',
        'created_at',
        'modified_at'

    ];

    public function contacts() {

        return $this->hasMany('Contact', 'title_id', 'id');

    }

}

In the form I have the following:

    {!! Form::label('title', 'Title: ') !!}
    {!! Form::select('title', $title) !!}

    {!! Form::label('name_first', 'First Name: ') !!}
    {!! Form::text('name_first', null, ['class' => 'form-control']) !!}

    {!! Form::label('name_middle', 'Middle Name: ') !!}
    {!! Form::text('name_middle', null, ['class' => 'form-control']) !!}

    {!! Form::label('name_last', 'Last Name: ') !!}
    {!! Form::text('name_last', null, ['class' => 'form-control']) !!}

    {!! Form::label('name_nick', 'Nickname: ') !!}
    {!! Form::text('name_nick', null, ['class' => 'form-control']) !!}

I am getting an error saying the variable title is undefined. I cannot determine why the value list is not being returned. Are my relationships returned incorrectly?

A: You don't pass the $title variable to your view.
In your create method in the ContactController, assign the $title variable to your view:
public function create()
    {
        $title = Contact::lists('title', 'id');
        return view('pages.contacts.create')->with('title', $title);
    }

See http://laravel.com/docs/5.0/views for more documentation.


text:
Q: How to fix React Native Metro initialization I wanted to continue working on my React Native App but when I run npx react-native start then npm run android I get the following:

I tried the following:

*

*re-installing packages

*re-checking for local.properties


text:
Q: LwM2M specification for multiple clients We are reading the LwM2M 2m spec for a college assignment simulation and trying to implement client and server requests.
Finding it hard to understand few details. Documentation is limited on it. We were told a requirement was to configure multiple clients. Does that mean each end point will have its own object ids according to LwM2M? What will be unique for each client? What we understood was each client has several objects like location, device, access control, security etc. Is there any good documentation out there or can someone give us a pointer for basic hierarchy of LwM2M?

A: LwM2M server registers client devices by uniqued endpoint name. To understand the lwm2m server and client flow better, you should play this demo sand box from leshan lwm2m
https://leshan.eclipseprojects.io/#/clients
You can read this to understand more about API in lwM2M
https://www.win.tue.nl/~lrahman/iot_2016/tutorial/LeshanTutorial_2016_v2.pdf


text:
Q: How to prevent an account from downloading in Windows 7 Is there a way to prevent accounts from downloading files in Windows 7?

A: Yes and No.
You can prevent this in Internet Explorer by going to Control Panel or Tools menu, then  Internet Options.
Go to the Security Tab and under Internet choose Custom Level.
From here, you can disable File Download

However, this can easily be overwritten by someone who knows what they are doing, you may want to consider locking down the machine through Group Policy if on a domain or the Local Security policy otherwise.


text:
Q: Path issue with autoload function to get files for use in Ajax So my project uses an MVC framework and I have a page with an Ajax script I run to get content from the server.  When the PHP script is called in the Ajax script, I want to access the classes already in my library for use in the PHP script.  To do this, I use what I call an ajaxBootstrap to call the appropriate function that then instantiates the objects needed for that specific Ajax script.
To load those classes from my library I have an autoload function in my ajaxBootstrap so I don't need to use a bunch of require and include statements.  My problem is those files aren't being loaded due to a path issue with the autoload function.  When I use a require statement with the same path, the classes load with no problems, its only when I try to load them using the autoload function that I get an 500 internal server error.
Here is my ajaxBootstrap file:
// This file routes Ajax requests made in JS files and instantiates a specific object to carry out the actions needed for that particular Ajax operation

// Autoload any classes that are required
function autoLoad($classToLoad)
{
    if(file_exists('../library/' . $classToLoad . 'class.php')) // File in the library folder
    {
        require('../library/' . $classToLoad . '.class.php');
   }
    else if(file_exists('../../app/models/' . $classToLoad . 'class.php')) // File in the models folder
    {
        require('../../app/models/' . $classToLoad . '.class.php');
    }
}

spl_autoload_register('autoLoad');

// Determine which function to call based on the url that's listed in the Ajax request
switch($_GET['action'])
{
    case 'pageOne':
        pageOne();
        break;
    case 'pageTwo':
        pageTwo();
        break;
}

function pageOne()
{
    $test = new Test();
    $test->funcThatReturnStuff();
}

function pageTwo()
{
    $test2 = new Test2();
    $test2->funcThatReturnStuff();
}

Like I mentioned eariler, if I use a require statement such as:
require('../library/Test.class.php');
$test = new Test();
$test->funcThatReturnStuff();

The class loads and works just fine.  But using the same path in the autoloader function throws an error.  The really odd thing is if I put an else if statement in the autoloader that loads a class from the folder where my ajaxBootstrap is it also works fine too...
I know I could just use the require statements and be done with the problem but I want to be able to scale the project and not need to use loads of require statements in the future.  BTW, I use '../' to get from where my ajaxBootstrap file is to my other folders.
Also, to add to my previous post, I've tried replacing the ../ with absolute paths using define('ROOT', dirname(__FILE__) . '/') and also define('ROOT', $_SERVER['DOCUMENT_ROOT'] . '/path/to/folder/') neither of which worked and still gave me the internal server error in Firebug.  In addition, I haven't received any errors in my error log either.

A: Nevermind...  Even after staring at my code for the past few hours I somehow missed the missing period in two of my file paths.  I hate coding sometimes...  Thank you to anyone who took time to read this.


text:
Q: How to use custom storage type for liferay 7 forms? I am following this tutorial CREATING ADVANCED FORMS, but I am not able to understand how to use external database for storing form data.
I cant find any tutorial about this concept. I am using liferay 7 CE.
Also tutorial says that

developers can implement their own storage types if JSON is not
  desirable. If they do, the option will appear here in Form Settings.
  See the tutorial on custom storage types (not yet written) for more
  information.

My question is which service-wrapper to use, I cant understand how to know which Service is being used for forms.

A: You can change the storage type only when you are creating a new form in the form settings. The JSON type is the default but you can create a new StorageAdapterto create additional types.
Have a look at the JSONStorageAdapter to get an inspiration how to develop a custom one. Should be enough to create a bundle put the new class in. Extend the BaseStorageAdapter and implement new necessary methods.
The new class will be picked up after deployment and you should get a new option in the Form settings.


text:
Q: What is the best method to start understanding BIG project source code?
Possible Duplicate:
How do you dive into large code bases?

Sometimes before developing new products we need to understand some existing products or existing source code.
Sometimes to write another small module of that big project we need to understand that big source code.
In our case we need to study and understand a project with lots of files and folders. What is the easiest and most comfortable way to do it ? (especially for C and C++ and under Linux)

A: All big projects have some sort of documentation usually Doxygen which can help a lot in understanding the code.
You can also use code browsing tools like SourceInsight to study the code.
Last but the best approach is run the code and debug use cases.

A: Als have already mentioned doxygen which is used for documentation in many projects.
For source browsing: vim along with plugins, cscope & ctags work very well. These can be installed easily on Linux environment and work very well in tandem.
Hope this helps!

A: There are different approaches. Documentation if present should help, but in the real world sadly there are quite a few poorly documented code bases. In many cases you can ask some senior developer in the company for guidance, make sure to ask for some high level view of what and how are things done in each module.
You can use a UML analysis tool to extract information from the code base, I suggest BoUML, it is not pretty, but it does a good job at processing C++, and you can create class diagrams by just pulling one class and expanding from there.
An IDE or a similar set of tools that help you navigate through code will also help, as they will allow you to navigate through code much easier than with a plain editor.
While doing the analysis, make sure that you take notes on what you believe each part of the code does, or where you have doubts, then ask a senior in the company to confirm your understandings or to fill in the gaps.

A: While reading and documentation can be helpful, writing helps too!
Write some tests (nothing serious) which use common features of the codebase, or focus on the components you will need to use.
Try to document some of the things you did not expect, issues you had, and deviations from your team's practices.
You may be surprised by how some programs operate, and how they are expected to be used.

A: You just need hard work.
Getting familiar with a large codebase is like disentangle a skein. You start somewhere, understand nothing. Then start again elsewhere, still understand nothing.
Start after start, some parts get less obscure. Starting again where you started the first time now provides some clues.
Then the strategy is divide and conquer. Isolate modules and understand them one after the other.
Possible starts are: Makefiles, main() function, file hierarchy, existing documentation (at least a README file) or whatever Doxygen is able to extract even if it was not planned.


text:
Q: $_SESSION['table'] being overwritten by POST method var Why is my $_SESSION['table'] being overwritten every time I use POST method? Whenever I get a new $mark variable from $POST method $_SESSION ['table'], its being placed on the place of the older one.
<?php
session_start();

    if (!isset($_COOKIE['name'])) {
        setcookie('name', serialize($_SESSION['table']), time() + 3600 * 24);
        echo('Cookie has been made');
    }

    if (isset($_SESSION['counter'])) {
        $counter = $_SESSION['counter'];
        $_SESSION['counter'] = $_SESSION['counter'] + 1;
    }

    $_SESSION['table'] = [];

    var_dump($_SESSION['table']);

    if ('POST' === $_SERVER['REQUEST_METHOD']) {

        $mark = isset($_POST['mark']) ? trim($_POST['mark']) : NULL;
    }

    $_SESSION['table'][] = $mark;
    $_SESSION['table'][] = 3;

    var_dump($_SESSION['table']);

     function calcArithmeticMark() {
       $sum = 0;
           foreach ($_SESSION['table'] as $value) {
        $sum += $value;
              }
            $result = $sum / count($_SESSION['table']);

            return $result;
    }
    ?>

A: Your script empties the session variable every time with:
$_SESSION['table'] = [];

You should only do that if the variable is not set and needs to be initialized:
if (!isset($_SESSION['table'])) {
    $_SESSION['table'] = [];
}


text: Q: Return Quickest Result Let's say I have two methods for completing a task, MethodA & MethodB to do Task1. How can I have a Step Function which executes both methods, and completes Task1 as soon as A or B has finished, and then proceeds to Task2.


text:
Q: After rotate image how to find correct position to crop in specific area I want to crop image in specific area, I made below example
it is work when the inner not been rotate
my problem is after rotate the inner, I don't get how to find correct sx,sy,sw,sh to crop
UPDATE
base on this answer fix the draw rotate image part, I update in fiddle.
but I still don't get how to find correct position to crop rotated image ...
https://jsfiddle.net/ve219z34/3/

var crop = function() {
  var transformMediaBlock = $('.mediaBlock');
  var transformCropInner = $('.transformCropInner');
  var transformCropLimit = $('.transformCropLimit');
  var canvasContainer = $('.canvasContainer')

  var limitLeft = transformCropLimit.offset().left;
  var limitTop = transformCropLimit.offset().top;
  var limitRight = limitLeft + transformCropLimit.width();
  var limitBottom = limitTop + transformCropLimit.height();

  var imageRatio = transformMediaBlock.find('img')[0].naturalWidth/transformMediaBlock.find('img').width();

  // draw rotate image
  var deg2Rad = Math.PI/180;

  var rotateDegree = -20;

  $('<canvas/>',{'class':'rotate'}).appendTo($(canvasContainer));
  var canvas = $('.canvasContainer canvas')[0];

  var ctx = canvas.getContext("2d");
  var width = 0;
  var height = 0;
  var diagonal = 0;
  var angleInDegrees = 0;

  width = transformMediaBlock.find('img')[0].naturalWidth;
  height = transformMediaBlock.find('img')[0].naturalHeight;
  diagonal = Math.sqrt(Math.pow(width,2)+Math.pow(height,2));
  ctx.canvas.width = diagonal;
  ctx.canvas.height = diagonal;
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.save();
  ctx.translate(diagonal/2,diagonal/2);
  ctx.rotate(0*Math.PI/180);
  ctx.drawImage(transformMediaBlock.find('img')[0],-width/2,-height/2);
  ctx.restore();

  var drawRotated = function(degrees){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    ctx.translate(diagonal/2,diagonal/2);
    ctx.rotate(degrees*Math.PI/180);
    ctx.drawImage(transformMediaBlock.find('img')[0],-width/2,-height/2);
    ctx.restore();
  };

  drawRotated(rotateDegree);

  // problem is here don't know how to get correct sx sy sw sh with image been rotate
  // draw crop rotate image
  var imageLeft = transformMediaBlock.find('img').offset().left;
  var imageTop = transformMediaBlock.find('img').offset().top;
  var imageRight = imageLeft + transformMediaBlock.find('img').width();
  var imageBottom = imageTop + transformMediaBlock.find('img').height();

  if (limitLeft <= imageLeft) {
    var sx = 0;
  } else {
    var sx = limitLeft - imageLeft;
  }
  if (limitTop <= imageTop) {
    var sy = 0;
  } else {
    var sy = limitTop - imageTop;
  }
  if (limitLeft <= imageLeft) {
    var l =  imageLeft;
  } else {
    var l = limitLeft;
  }
  if (limitRight <= imageRight) {
    var r = limitRight;
  } else {
    var r = imageRight;
  }
  var sw = r - l;
  if (limitTop <= imageTop) {
    var t = imageTop;
  } else {
    var t = limitTop;
  }
  if (limitBottom <= imageBottom) {
    var b = limitBottom;
  } else {
    var b = imageBottom;
  }
  var sh = b - t;

  sx = sx*imageRatio;
  sy = sy*imageRatio;
  sw = sw*imageRatio;
  sh = sh*imageRatio;

  var dx = 0;
  var dy = 0;
  var dw = sw;
  var dh = sh;

};

$('#container').on('click', '.action.crop', function (e) {
  var transformMediaBlock = $('.mediaBlock');
  transformMediaBlock.find('img').on('load', function() {
   $('.transformCropInner').addClass('rotate');
    crop();
  }).each(function() {
    if(this.complete) $(this).load();
  });
});
.mediaBlock {
  position: relative;
  display: block;
  overflow: hidden;
}
.mediaBlock img {
  max-width: 100%;
}

.transformCropLimit {
  position: relative;
  top: 20px;
  left: 20px;
  width: 200px;
  height: 200px;
  border: 1px solid blue;
}

.transformCropInner {
  width: 100px;
  cursor: pointer;
  position: relative;
  top: 10px;
  left: 100px;
}

.transformCropInner.rotate {
  transform: rotate(9-2deg);
  -ms-transform: rotate(-20deg); /* IE 9 */
  -moz-transform: rotate(-20deg); /* Firefox */
  -webkit-transform: rotate(-20deg); /* Safari and Chrome */
  -o-transform: rotate(-20deg); /* Opera */
}

Crop

Please don't provide plugin as an answer, and css crop is not what I'm looking for.


text:
Q: MySql FULLTEXT INDEX with JOINS Is it possible to create a fulltext index on two columns derived from the inner-join of two tables? If yes, Please give me the syntax with an example.
Suppose
`table1 = Car_first (Columns: car_id, car_name)`

`table2 = Car_second (Columns: car_id, car_description)`

Now I want to MATCH (car_name, car_description) AGAINST query string.
Please help. TY. :)

A: Not directly, but MySQL's relevance scoring is additive so the result would be the same as having separate FULLTEXT indexes on the columns in each table and doing:
MATCH(car_name) AGAINST 'foo' + MATCH(car_description) AGAINST 'foo'


text:
Q: Is there any way to add data to clipboard? I am making a chrome extension where I need to add data to user's clipboard , so that he/she only needs to press cmd + V / ctrl + V to paste, wherever they want.
Its only about Chrome, no browser compatibility required.
Can I do it with JS ?

A: Chrome used to have this support by default, but security changes to Webkit prevented it, even for extensions.  It sounds like it is possible with a workaround though, described here:
http://fartersoft.com/blog/2010/11/20/accessing-operating-system-clipboard-in-chromium-chrome-extensions/


text:
Q: How to bypass DNSMASQ traffic redirect (address=/#/10.0.0.1) after Captive Portal Authentication? I wanted to write a captive portal from scratch using the following:

*

*hostapd v2.10 to setup my wlan0 as an AP and eth0 is connected to the internet router.

    #/etc/hostapd/hostapd.conf

    interface=wlan0
    driver=nl80211
    ssid=MyWIFI
    hw_mode=g
    channel=11

*

*dnsmasq v2.86 as DHCP & DNS

    #/etc/dnsmasq.conf

    interface=wlan0
    dhcp-range=10.0.0.2,10.0.0.250,24h
    dhcp-option=3,10.0.0.1
    dhcp-option=6,10.0.0.1
    domain-needed
    bogus-priv
    no-resolv
    address=/#/10.0.0.1

*

*iptables to share internet of eth0 to wlan0
    sysctl -w net.ipv4.ip_forward=1
    sysctl -p
    iptables -X
    iptables -F
    iptables -F INPUT
    iptables -F OUTPUT
    iptables -F FORWARD
    iptables -F -t mangle
    iptables -X
    iptables -t nat -X
    iptables -t nat -F

    iptables -t nat -I POSTROUTING -o eth0 -j MASQUERADE

*

*Ubuntu 22.04 Server

*Apache v2.4.52 as my webserver

    #Added below config in /etc/apache2/sites-available/000-default.conf.  Just right
    #below the </VirtualHost>

    <Directory "/var/www/html">
        RewriteEngine On
        RewriteBase /
        RewriteCond ${HTTP_HOST} ^www\.(.*)$ [NC]
        RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ / [L,QSA]
    </Directory>

*

*Angular is used to write the Captive Portal

*nodejs is used to write the APIs for the Captive Portal
I managed to trigger the Sign-in to network for Android which when tapped redirects to the Captive Portal & for iOS the redirection is automatic.
In the Captive Portal, I have a button to accept a Voucher Code that is validated in the backend (nodejs).  My objective is to allow the device with a valid Voucher Code to access the internet with a limited time and should not be redirected anymore to the Captive Portal.
But I don't know how to proceed since in my dnsmasq.conf I have configured address=/#/10.0.0.1 and as far as I know this will redirect back network traffic to my dnsmasq server where apache is configured to redirect the request to the Captive Portal.
Hope someone could lead me to the right direction.  Thank you very much.


text:
Q: net::ERR_TIMED_OUT flutter web http package I use the HTTP package to post a request to the server and handle errors but there is a net::ERR_TIMED_OUT error when sending a request to the server which I can not figure out how to handle it.
Here is my send request
  Future<Session> login(String username, String password) async {
    final request = Uri.https(
      _baseUrlGeocoding,
      '/login',
      {'email': username.trim(), 'password': password},
    );

    try {
      final response = await _httpClient.post(request);
      if (response.statusCode != 200) {
        throw LoginRequestServerFailure();
      }

      final responseJson = jsonDecode(response.body) as Map<String, dynamic>;

      if (responseJson['message'] != 'OK') throw LoginCredentialsFailure();

      return Session.fromJson(responseJson['data'] as Map<String, dynamic>);
    } catch (error) {
      print(error.toString());
      throw InternetConnectionFailure();
    }
  }

After sending a request instead of catching an error debugger freezes at send request point and no error is thrown.In the console of the web I've got this error message:
POST https://sample.com/account?email=g81%40ekcsoft.com&password=123456 net::ERR_TIMED_OUT

How to handle net::ERR_TIMED_OUT error in flutter http package when send request to server?

A: write like this
   Uri myUri = Uri.parse(url);
      var response = await http.post(
        myUri,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $token',
        },
      ).timeout(const Duration(minutes: 3));


text:
Q: FileObserver service getting closed by another app I'm running a FileObserver service that is watching for new files created in a certain folder however whenever I open a separate app that creates said files in that folder, it closes my FileObserver service app (I no longer see it in the Task Manager).  I would like both to run at the same time so that app #2 can create files in the same folder that app #1 is watching.  Any tips as to how to do this?

A: Android has the freedom to terminate any service at any time to reclaim memory. To make it less likely for your service to be chosen for reclaiming memory, set it to foreground.


text:
Q: Add labels for selected observations in ggplot2 histogram at the same height as the bins I'd like to add an "id" annotation to certain observations in a histogram.
So far, I'm able to add the annotation with no problem, but I'd like the 'y' position of my annotations to be the count of the bin + 1 (for aesthetic reasons).
This is what I have so far:
library(tidyverse)
library(ggrepel)

selected_obs <- c("S10", "S100", "S245", "S900")
set.seed(0)
values <- rnorm(1000)
plot_df <- tibble(id = paste0("S", 1:1000),
                  values = values) %>%
    mutate(obs_labels = ifelse(id %in% selected_obs, id, NA))

ggplot(plot_df, aes(values)) +
    geom_histogram(binwidth = 0.3, color = "white") +
    geom_label_repel(aes(label = obs_labels, y = 100))

I've seen multiple answers dealing with annotating the count for each bin using geom_text(stat = count", aes(y=..count.., label=..count..).
Based on that, I've tried these two work-arounds, but no success:

*

*geom_label_repel(stat = "count", aes(label = obs_labels, y = ..count..)) yields:
"Error: geom_label_repel requires the following missing aesthetics: label"

*geom_label_repel(aes(label = obs_labels, y = ..count..)) yields "Error: Aesthetics must be valid computed stats. Problematic aesthetic(s): y = ..count...
Did you map your stat in the wrong layer?".

Anybody that can shed some light here?

A: That may be a mildly misleading visualisation, because you are labelling a unique ID, but with the positioning of this label to the count height you are suggesting that this ID was counted that often. Anyways.
The most straight forward option is to manually calculate the bin to which your ID belongs, then count this bin, and then use this data in order to set the x and y for your labels.
Unfortunately, I have to use R online and cannot create a nice reprex, therefore including a screenshot. But the code should be reproducible, as it is running online
library(tidyverse)
library(ggrepel)

selected_obs <- c("S10", "S100", "S245", "S900")
set.seed(0)
values <- rnorm(1000)

plot_df <- tibble(id = paste0("S", 1:1000),
                  values = values) %>%
    mutate(obs_labels = ifelse(id %in% selected_obs, id, NA),
bins = as.factor( as.numeric( cut(values, 30)))) # cutting into 30 bins

label_df<- plot_df %>% filter(id %in% selected_obs) %>% left_join(plot_df, by = 'bins') %>%
group_by(values = values.x, obs_labels = obs_labels.x) %>% count

ggplot(plot_df, aes(values)) +
    geom_histogram(color = "white") + # removed your bin argument, as to default to 30
    geom_label(data = label_df, aes(label = obs_labels, y = n))

The label positions are not quite perfect - this is because I chose to cut into 30 equal bins and the binning may be slightly different between cut and histogram. This may need some tweaking, depending on the size of your bins, and if you include upper/lower margins.
P.S. Credit to cut into equal bins goes to this answer by user pedrosaurio


text:
Q: Regular Expression in R (removing spacing and punctuation characters) Suppose I have the following text:
text = c("Initial [kHz]","Initial Value [dB]",
         "Min Accept X [kHz]","Min Accept [dB]",
         "Cut-Off Frequency [kHz]",
         "Min Bandwidth Limit [kHz]","y min [dB]",
         "Max Bandwidth Limit [kHz]","y max [dB]",
         "Iter: 1 [kHz]","Iter: 1","Value: 55 [dB]",
         "Iter: 2 [kHz]","Iter: 2","Value: 59 [dB]")

But what I want is (which removed the spacing and the punctuation characters:
text = c("InitialkHz","InitialValuedB",
         "MinAcceptXkHz","MinAcceptdB",
         "CutOffFrequencykHz",
         "MinBandwidthLimitkHz","ymindB",
         "MaxBandwidthLimitkHz","ymaxdB]",
         "Iter1kHz","Iter1","Value55dB",
         "Iter2kHz","Iter2","Value59dB")

Can anyone help me? Please...

A: We can use gsub to remove all the punctuations and spaces from text.
gsub("[[:punct:]]| ", "", text)

# [1] "InitialkHz"           "InitialValuedB"       "MinAcceptXkHz"
# [4] "MinAcceptdB"          "CutOffFrequencykHz"   "MinBandwidthLimitkHz"
# [7] "ymindB"               "MaxBandwidthLimitkHz" "ymaxdB"
#[10] "Iter1kHz"             "Iter1"                "Value55dB"
#[13] "Iter2kHz"             "Iter2"                "Value59dB"

A: You can choose to keep only alpha numeric values like this:
gsub('[^[:alnum:]]', '', text)


text:
Q: How would you analyse two likert scales answered by the same people on several occasions? I don't usually need to use stats in my work so this might seem like a basic question but, to me, it's baffling!
I have two questionnaires that I'm giving to the same group of people who are undergoing a treatment programme. Both are self-report measures; one on stress and one on quality of life. Both are Likert scales.
I'm not so interested in individual items but we want to find out whether people who score higher on stress take longer to complete the treatment. We also want to know if people who score higher on stress take longer to score higher quality of life.
After much Googling, I've seen Spearman's Rho suggested, which I kind of get for my first question about stress and length of time taken to treat, but I'm not sure. And I have no clue how to analyse the data to answer my second question about stress scores and quality of life scores. The same people would be answering the questionnaires at set intervals throughout treatment.
Any suggestions would be appreciated.


text:
Q: Can't marshall WebAPI XML response into C# object I have some XML coming back from a REST service that I am having trouble marshalling to a C# class.
The XML looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SCResponse>
    <link href="http://192.168.6.126:8001/affiliate/account/81/notifications?startRow=2&limit=20" rel="next_page" title="Next"/>
    <link href="http://192.168.6.126:8001/affiliate/account/81/notifications?startRow=1&limit=20" rel="previous_page" title="Previous"/>
    <RecordLimit>20</RecordLimit>
    <Notifications>
        <Notification href="http://192.168.6.126:8001/affiliate/account/81/notifications/24">
            <NotificationDate>2013-03-15T16:41:37-05:00</NotificationDate>
            <NotificationDetails>Notification details 1</NotificationDetails>
            <Status>New</Status>
            <NotificationTitle>Test notification 1</NotificationTitle>
        </Notification>
    </Notifications>
    <RecordsReturned>1</RecordsReturned>
    <StartingRecord>1</StartingRecord>
    <TotalRecords>1</TotalRecords>
</SCResponse>

and the class that was automatically generated by 'Paste as Special' looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using System.Xml.Serialization;

namespace CMINet.Models.notifications
{

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

// to make it work I must replace the above with:
//    [XmlType]
//    [DataContract(Namespace = "")]

public partial class SCResponse
{

    private SCResponseLink[] linkField;

    private byte recordLimitField;

    private SCResponseNotifications notificationsField;

    private byte recordsReturnedField;

    private byte startingRecordField;

    private byte totalRecordsField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("link")]
    public SCResponseLink[] link
    {
        get
        {
            return this.linkField;
        }
        set
        {
            this.linkField = value;
        }
    }

    /// <remarks/>
    public byte RecordLimit
    {
        get
        {
            return this.recordLimitField;
        }
        set
        {
            this.recordLimitField = value;
        }
    }

    /// <remarks/>
    public SCResponseNotifications Notifications
    {
        get
        {
            return this.notificationsField;
        }
        set
        {
            this.notificationsField = value;
        }
    }

    /// <remarks/>
    public byte RecordsReturned
    {
        get
        {
            return this.recordsReturnedField;
        }
        set
        {
            this.recordsReturnedField = value;
        }
    }

    /// <remarks/>
    public byte StartingRecord
    {
        get
        {
            return this.startingRecordField;
        }
        set
        {
            this.startingRecordField = value;
        }
    }

    /// <remarks/>
    public byte TotalRecords
    {
        get
        {
            return this.totalRecordsField;
        }
        set
        {
            this.totalRecordsField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class SCResponseLink
{

    private string hrefField;

    private string relField;

    private string titleField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string href
    {
        get
        {
            return this.hrefField;
        }
        set
        {
            this.hrefField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string rel
    {
        get
        {
            return this.relField;
        }
        set
        {
            this.relField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string title
    {
        get
        {
            return this.titleField;
        }
        set
        {
            this.titleField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class SCResponseNotifications
{

    private SCResponseNotificationsNotification notificationField;

    /// <remarks/>
    public SCResponseNotificationsNotification Notification
    {
        get
        {
            return this.notificationField;
        }
        set
        {
            this.notificationField = value;
        }
    }
}

/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class SCResponseNotificationsNotification
{

    private System.DateTime notificationDateField;

    private string notificationDetailsField;

    private string statusField;

    private string notificationTitleField;

    private string hrefField;

    /// <remarks/>
    public System.DateTime NotificationDate
    {
        get
        {
            return this.notificationDateField;
        }
        set
        {
            this.notificationDateField = value;
        }
    }

    /// <remarks/>
    public string NotificationDetails
    {
        get
        {
            return this.notificationDetailsField;
        }
        set
        {
            this.notificationDetailsField = value;
        }
    }

    /// <remarks/>
    public string Status
    {
        get
        {
            return this.statusField;
        }
        set
        {
            this.statusField = value;
        }
    }

    /// <remarks/>
    public string NotificationTitle
    {
        get
        {
            return this.notificationTitleField;
        }
        set
        {
            this.notificationTitleField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string href
    {
        get
        {
            return this.hrefField;
        }
        set
        {
            this.hrefField = value;
        }
    }
}

}

The problem is, none of the object's fields get marshalled. Fields are null or zero after the call even though the XML returned from WebApi definitely has values.
What could be going wrong?
thanks.

A: It's possible you didn't turn on XmlSerializer on your XML formatter. Try this:
config.Formatters.XmlFormatter.UseXmlSerializer = true;

You should also check the controller's ModelState property for any deserialization errors that may have occurred.


text:
Q: Property 'subscribe' does not exist on type. even returning Observable I'm receiving a compilation error when I try to subscribe to a method in a service, yes I am returning an Observable.
The related versions are from default .net core angular template.

*

*Angular => 4.4.4

*rxjs => 5.4.2

VS Code error

Below, the login.component.ts with references.
login.component.ts
import { Component, OnInit } from "@angular/core";
import { LoginViewModel } from "../models/ApplicationUserViewModel";

import { LoginService } from "../services/Login.service";

@Component({
  selector: "app-login",
  templateUrl: "./login.component.html",
  styleUrls: ["./login.component.css"]
})
export class LoginComponent implements OnInit {
  public loginViewModel: LoginViewModel;

  constructor(private loginService: LoginService) {
    this.loginViewModel = new LoginViewModel();
  }

  ngOnInit() {}

  login(): any {
    this.loginService.login(this.loginViewModel).subscribe(
      result => {
        alert("success");
      },
      error => {
        alert("error");
      }
    );
  }
}

Below, the login.service.ts with references.
login.service.ts

import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Rx";
import { of } from "rxjs/observable/of";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { map } from "rxjs/operator/map";

import { LoginViewModel } from "../models/ApplicationUserViewModel";

const httpOptions = {
  headers: new HttpHeaders({ "Content-Type": "application/json" })
};

@Injectable()
export class LoginService {
  constructor(private http: HttpClient) {}

  login(loginViewModel: LoginViewModel): Observable<any> {
    return this.http.post<LoginViewModel>(
      'account/login',
      loginViewModel,
      httpOptions
    );
  }
}

Thank you.


text:
Q: Filter UltraGrid column by a different column I have two columns in an UltraWinGrid. The first column is rich text formatted text. The second column has the plain text equivalent (RTF removed) of the first column.
I am only showing the first, RTF formatted, column to the user. When the user types in the filter row, I'd like to filter by the second, hidden, column. Is this possible?


text:
Q: error[im006][microsoft][odbc driver manager] driver's SQLsetconectionattr failed I'm getting below error: it works fine on one of my dev servers and but on remote prod server it fails
 string msAccessConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};DBQ=" + fileName;

        try
        {
            using (OdbcConnection sourceConnection = new OdbcConnection(msAccessConnectionString))
            using (sqlConnection)
            {
                sourceConnection.Open();

                 // code to update the table or retrieve the table

             }
           }catch (Exception ex)
        {
            sb.AppendLine("ERROR --- ERROR --- ERROR --- ERROR --- ERROR ---");
            sb.AppendLine(ex.Message.ToString());

        }


text:
Q: Can anyone explain how the complex matrix representation of a quaternions is constructed? I am reading some properties of quaternionic matrices and I am unable to understand how can we got such matrix representation. please help in this regards.

A: The ring of quaternions $\mathbb{H}$ is isomorphic to the
ring of matrices with complex entries of the form $A =\begin{pmatrix}
x & y
\\
- \bar{y} & \bar{x}
\end{pmatrix} $
For a quaternion $z=a+b\mathbf{i}+c\mathbf{j}+d\mathbf{k}$ the isomorphism is given by:
$$
z=a+b\mathbf{i}+c\mathbf{j}+d\mathbf{k} \quad  \mapsto \quad \mathbf{Z}= a\mathbf{U}+b\mathbf{I}+c\mathbf{J}+d\mathbf{K} \quad a,b,c,d \in \mathbb{R}
$$
with:
$$
\mathbf{U}=
\left(
 \begin{array}{ccccc}
1&0  \\
 0 &1
\end{array}
\right)
\qquad
\mathbf{I}=
\left(
 \begin{array}{ccccc}
i&0  \\
 0 &-i
\end{array}
\right)
\qquad
\mathbf{J}=
\left(
 \begin{array}{ccccc}
0&1  \\
 -1 &0
\end{array}
\right)
\qquad
\mathbf{K}=
\left(
 \begin{array}{ccccc}
0&i  \\
 i &0
\end{array}
\right)
$$
We can easy see that:
$$
\mathbf{I}^2=\mathbf{J}^2=\mathbf{K}^2=\mathbf{I}\mathbf{J}\mathbf{K}=-\mathbf{U}
$$
and
$$
z=a+b\mathbf{i}+c\mathbf{j}+d\mathbf{k} \quad  \mapsto \quad \mathbf{Z}=
\left(
 \begin{array}{ccccc}
 a+ib&c+id  \\
 -c+id &a-ib
\end{array}
\right)
$$
with
$$
\mbox{det}(\mathbf{Z})=
\left |
\left(
 \begin{array}{ccccc}
 a+ib&c+id  \\
 -c+id &a-ib
\end{array}
\right)
\right |=
a^2+b^2+c^2+d^2=|z|^2
$$

A: The key is as Jyrki states in the comments: view $\mathbb{H}$ as a right vector space over $\mathbb{C}$. That means we apply scalars from the right, instead of the left. This way, if $q\in\mathbb{H}$ is a scalar and $L_q(x)=qx$ is the left-multiplication-by-$q$ map, it is $\mathbb{C}$-linear in the sense that $L_q(x\lambda)=L_q(x)\lambda$ for all $x\in\mathbb{C}$ and complex scalars $\lambda\in\mathbb{C}$. As a complex vector space, $\mathbb{H}$ is $2$-dimensional with basis $\{1,\mathbf{j}\}$.
With this idea, every $L_q$ corresponds to a $2\times 2$ complex matrix:
$$ \begin{cases} L_1(1)=1+\mathbf{j}0 \\ L_1(\mathbf{j})=0+\mathbf{j}1 \end{cases} \implies \quad L_1\leftrightarrow \begin{pmatrix} 1 & 0 \\ 0 & 1\end{pmatrix} $$
$$ \begin{cases} L_{\mathbf{i}}(1)=\mathbf{i}+0\mathbf{j} \\ L_{\mathbf{i}}(\mathbf{j})= 0-\mathbf{j}\mathbf{i} \end{cases} \implies \quad L_{\mathbf{i}}\leftrightarrow \begin{pmatrix} i & 0 \\ 0 & -i \end{pmatrix} $$
$$ \begin{cases} L_{\mathbf{j}}(1)=0+\mathbf{j}1 \\ L_{\mathbf{j}}(\mathbf{j})=-1+\mathbf{j}0  \end{cases} \implies \quad L_{\mathbf{j}}\leftrightarrow \begin{pmatrix} 0 & -1 \\ 1 & 0 \end{pmatrix} $$
$$ \begin{cases} L_{\mathbf{k}}(1)=0-\mathbf{ji} \\ L_{\mathbf{k}}(\mathbf{j})=-\mathbf{i}+\mathbf{j}0 \end{cases} \implies \quad L_{\mathbf{k}}\leftrightarrow \begin{pmatrix} 0 & -i \\ -i & 0 \end{pmatrix} $$
The correspondence $\mathbf{q}\leftrightarrow L_{\mathbf{q}}$ preserves addition and multiplication, hence is an $\mathbb{R}$-algebra homomorphism from $\mathbb{H}$ into $M_2(\mathbb{C})$. The image is then an isomorphic copy of $\mathbb{H}$.
Other conventions are possible. For instance, we could associate $\mathbf{q}\mapsto R_{\overline{\mathbf{q}}}$ (notice that conjugation).

A: Your question is essentially the aim of representation theory: representing the elements of a group as matrices.
https://en.m.wikipedia.org/wiki/Group_representation


text:
Q: How to implement crypt() and wordexp.h in Android Posix I know that these 2 functionalities are not provided by Bionics libc implementation. I do need these for a C++ to Android port. How can I solve this problem? I dont know where to start here.
I get these error messages:
error: unknown type name 'wordexp_t'
error: use of undeclared identifier 'crypt'
Any ideas?

A: A full BSD UNIX does provide that type and that function. However, there are good reasons why they aren't provided on Android.
wordexp_t is for shell-style word expansions.
crypt() is for UNIX password encryption. This is not any kind of general-purpose encryption; it is for taking an entered password, creating a hash (because that's what this kind of encryption does) and then seeing if the resulting string matches the user's password hash in the UNIX password file.
Android, of course, does not have a user login system, nor does it have a command line (unless you add one, or use ADB, neither of which is normal for Android app users).
So the uses of this type and this call are in code within your library that is not relevant to Android. Discoveries like this are commonplace when you port software to a very different platform.
Solving this problem properly requires finding out and understanding what the missing type and function are being used for in your source code. When you understand their purpose, you'll be able to figure out if they are needed on Android, in which case they'll need to be replaced with something else.
Then you need to revise the source of the library so that it uses them on the platforms where they exist, and something else gets used on Android. It's generally best to refactor the code, so that (for example), you end up with a source file that contains platform-specific code for word expansion, and another one with platform-specific code for password access.
The good news is that this structure will serve you well if and when you need to port the same code to iOS.


text:
Q: Partition full on Ubuntu, I have to move a mount point but I don't know how I have a server with a full partition. If I type
root@server:/dev# df -H
Filesystem                             Size  Used Avail Use% Mounted on
udev                                   4.2G     0  4.2G   0% /dev
tmpfs                                  838M  9.5M  828M   2% /run
/dev/mapper/TV--INSTORE--vg-root       13G   12G  112M 100% /
tmpfs                                  4.2G     0  4.2G   0% /dev/shm
tmpfs                                  5.3M     0  5.3M   0% /run/lock
tmpfs                                  4.2G     0  4.2G   0% /sys/fs/cgroup
/dev/sda1                              247M  106M  129M  46% /boot
/dev/sdb1                              527G  4.7G  495G   1% /data
cgmfs                                  103k     0  103k   0% /run/cgmanager/fs
overlay                                527G  4.7G  495G   1% /data/docker/overlay2/7769c388ccc9c8a14a08e12932b05a8c384144bead64c74e61950914c590de5a/merged
overlay                                527G  4.7G  495G   1% /data/docker/overlay2/0eca01cbad8077e00d6411b7eb079017290b49619ac4a260ae4fd7cbd3f45701/merged
overlay                                527G  4.7G  495G   1% /data/docker/overlay2/a70cd62c5ff52498f3f767cac7eff4eb82b61f4f96bac83ac48438c2d76ac3d0/merged
shm                                     68M     0   68M   0% /data/docker/containers/483b952cd54b067330cbd52e1fee25b2f77aed0f0e8364cdaaaccdd1629628e4/shm
shm                                     68M     0   68M   0% /data/docker/containers/7acf87a8175389b1bf012cf1b93d5222a9b6fc201d77c97b4507220af4dca4a2/shm
shm                                     68M     0   68M   0% /data/docker/containers/8ac4d5448661b085b69c9e7f814bb5822ec6be09d15f2bb06fc086ea4224cf8c/shm
tmpfs                                  838M     0  838M   0% /run/user/1000

It's not a server I manage, I'm a developer, but I need to fix this asap.
I notice that I have a lot of space on /dev/sdb1
Now if I type
du -sh /* | sort -h
0   /dev
0   /initrd.img
0   /initrd.img.old
0   /proc
0   /sys
0   /vmlinuz
0   /vmlinuz.old
4.0K    /lib64
4.0K    /srv
8.0K    /media
8.0K    /mnt
16K /lost+found
24K /tmp
56K /root
60K /home
6.7M    /etc
9.0M    /run
13M /bin
14M /sbin
99M /boot
625M    /lib
851M    /var
1.3G    /usr
4.3G    /data
8.0G    /opt

Basically now every data on my server is in /opt that is mounted on the disk with 13 GB. I understand that I need to move /opt/ to /dev/sda1 where I have a lot of GB it's right? How can I do?

A: *

*Create new folder on /dev/sdb1

mkdir /data/opt-backup

*Copy all the data to opt-backup folder

cd /opt
mv ./* /data/opt-backup


text:
Q: Contents of ng-bind-html is not wrapped in modal When I use ng-bind-html in a modal, e.g.

... the html that is bound to the div will not be contained in the modal, it will spill over its edges. How can I prevent this?