How rotate around another point keeping the same orientation - Animation Android

Question: I want to rotate (animation) an object around another point BUT I want my object keep the same orientation while rotating. How I can do that, can we do simply by calling Android functions or have to use maths (2d matrix formula)?
I want this result
My Code:
public class MainActivity extends AppCompatActivity {

    Button button;
    float radius = 195.0f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.t);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rotate()
            }
        });

        button.setX(button.getX() + radius);

    }
}

My Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <Button
        android:id="@+id/t"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:text="R"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Comment: You are rotating the view around itself, you need to move in a circular path. Have a look at this: http://stackoverflow.com/questions/20281265/move-an-image-in-circular-path-in-android
Comment: Thank you for your help, my fauft I don't understand that kind of rotation is  a "Translation" in circular path.
Answer: Solution: This kind of rotation is a simple "Translation in Circular Path":
private void rotate(){

             final ValueAnimator animator = ValueAnimator.ofFloat(0.0f, 360.0f);
             animator.setDuration(5000);
             animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                   @Override
                   public void onAnimationUpdate(ValueAnimator valueAnimator) {
                   float value = (Float) animator.getAnimatedValue();

                   DisplayMetrics metrics = new DisplayMetrics();
                   getWindowManager().getDefaultDisplay().getMetrics(metrics);

                   float cx = metrics.widthPixels / 2;
                   float cy = metrics.heightPixels / 2;

                   float x = (float) (cx + radius * Math.cos((float) Math.toRadians(value))); // center x in arc
                   float y = (float) (cy + radius * Math.sin((float) Math.toRadians(value))); // center y in arc

                   x -= (button.getWidth() / 2);
                   y -= (button.getHeight() / 2);

                   button.setX(x);
                  button.setY(y);
                }
            });

            animator.start();
}


Remove an element based on its ancestor presence in first child of its ancestor

Question: Please suggest for how to remove an element(mstyle) based on its ancestor(msubsup) presence  in first child (position=1) of its(msubsup) ancestor(msub or msup).
See my comments placed in XML as well as in XSLT for quick reference. (XSLT2)
Input XML:
<root>
<math>

<msubsup>
    <mrow><mi>H</mi></mrow>
    <mstyle width="70%"><mrow><mn>2</mn></mrow></mstyle>
</msubsup>

<mrow><mtext>The text 1</mtext></mrow>

<msub>
    <mrow>
        <msubsup>
            <mi>K</mi>
            <mstyle width="70%"><mn>2</mn></mstyle>
            <mo>+</mo>
        </msubsup>
    </mrow>
    <mrow><mn>2</mn></mrow>
</msub>

<mrow><mtext>The text 2</mtext></mrow>

<msup>
    <mrow>
        <mrow>
            <msubsup>
                <mrow><mi>K</mi></mrow>
                <mstyle width="70%"><mrow><mn>2</mn></mrow></mstyle>
                <mrow><mo>+</mo></mrow>
            </msubsup>
        </mrow>
    </mrow>
    <mrow><mn>2</mn></mrow>
</msup>

<mrow><mtext>The text 3</mtext></mrow>

<msub>
    <mrow><mn>A</mn></mrow>
    <mrow>
        <mrow>
            <msubsup>
                <mrow><mi>K</mi></mrow>
                <mstyle width="70%"><mrow><mn>2</mn></mrow></mstyle>
                <mrow><mo>+</mo></mrow>
            </msubsup>
        </mrow>
    </mrow>
</msub>

</math>

</root>

XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
    <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>

<xsl:template match="mstyle">

    <xsl:choose>
        <xsl:when test="ancestor::msubsup/ancestor::msub or ancestor::msubsup/ancestor::msup">
            <xsl:choose>
                    <xsl:when test="ancestor::msubsup/ancestor::*[position()=1]/ancestor::msub or ancestor::msubsup/ancestor::*[position()=1]/ancestor::msup">
                        <xsl:apply-templates/>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
                    </xsl:otherwise>
            </xsl:choose>
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
    </xsl:otherwise>
    </xsl:choose>

</xsl:template>

</xsl:stylesheet>

Required OutPut:
<root>
<math>
<msubsup>
    <mrow><mi>H</mi></mrow>
    <mstyle width="70%"><mrow><mn>2</mn></mrow></mstyle>
</msubsup>
<mrow><mtext>The text 1</mtext></mrow>

<msub>
    <mrow>
        <msubsup>
            <mi>K</mi>
            <mn>2</mn>
            <mo>+</mo>
        </msubsup>
    </mrow>
    <mrow><mn>2</mn></mrow>
</msub>
<mrow><mtext>The text 2</mtext></mrow>

<msup>
    <mrow>
        <mrow>
            <msubsup>
                <mrow><mi>K</mi></mrow>
                <mrow><mn>2</mn></mrow>
                <mrow><mo>+</mo></mrow>
            </msubsup>
        </mrow>
    </mrow>
    <mrow><mn>2</mn></mrow>
</msup>
<mrow><mtext>The text 3</mtext></mrow>

<msub>
    <mrow><mn>A</mn></mrow>
    <mrow>
        <mrow>
            <msubsup>
                <mrow><mi>K</mi></mrow>
                <mstyle width="70%"><mrow><mn>2</mn></mrow></mstyle>
                <mrow><mo>+</mo></mrow>
            </msubsup>
        </mrow>
    </mrow>
</msub>

</math>

</root>

Answer: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="msub/*[1]//msubsup/mstyle|msup/*[1]//msubsup/mstyle">

        <xsl:apply-templates select="node()"/>
    </xsl:template>
</xsl:stylesheet>

Comment: Element mstyle should be removed, but inner elements to be retained, thanks for suggestion


why is my ubuntu 16.04 32 bit fresh install painfully slow?

Question: I have intel core i3 with 4GB ram and 2.4Ghz machine. Previously i was using Windows 10 to run Android Studio. But as its license experied i switched to Ubuntu 16.04 LTS 32 bit. But unfortunately its lagging very much for simple task only. I don't know what will happen if I start using Android Studio :(
Also do i need to upgrade to 64 bit? Or switch to any lower versions of Ubuntu like 14.04LTS? Or switch to Windows again.
Specs--

Os : Ubuntu 16.04 LTS
RAM : 3.8 GiB
Processor : Intel Core i3-3110M CPU @ 2.4GHz x 4
Graphics : Intel ivybridge Mobile x86/MMX/SSE2
OS type : 32-bit
Disk : 488.1 GB

Please let me know if anyone faced similar problem.
Also any further clarification needed to this question? For graphic card detail i got this information from my system
Comment: You really should use 64-bit Ubuntu instead. However, what mode is your disk set to in BIOS? What video drivers are you using? What video card do you have?
Comment: Again, 64-bit, and if you just installed then please install again 16.04 as there's no point in installing 14.04 to then upgrade. Install 16.04 64-bit from the start. But before check at UEFI (the replacement for old BIOS) and make sure the disk (or disks) are in AHCI mode. Then, after installing, you also need Nvidia proprietary drivers for optimal performance. You can find the proper driver in Additional drivers (unless you're card is brand new in which case you may need to add a PPA). Please edit and post your hardware specs, especially the exact model of the Nvidia graphics.
Comment: @dobey I just afternoon only i installed Ubuntu 14.04 and in evening upgrade to 16.04. No drivers yet installed. Although my laptop support Nvidia GeForce. From where I can check bios mode?
Comment: @dobey I just referred to this [UEFI docs](https://help.ubuntu.com/community/UEFI)   found that my disk mode is "Legacy boot on HDD"
Comment: @CelticWarrior Sorry I just deleted my 1st comment by mistake(new on stackexchange) to which you referred. I tried finding model of Nvidia
Comment: Legacy boot is not the disk mode. You need to go to the SATA/IDE settings, and make sure the hard disk is set to AHCI mode.
Comment: @dobey yes, just found my hardisk is AHCI mode and UEFI mode is Enabled. shall i update this information in post?
Comment: @dobey Going to install ubuntu-16.04.1-server-amd64 from start. i will update here.
Comment: @dobey "Legacy boot on HDD" meant boot mode is "non-UEFI".
Comment: If this is a desktop system, you probably should _not_ install the server version (i.e: you should download the desktop version, and _not_ the version with `-server-` in the name.
Comment: @JonasCz I identified this mistake.... But after installing server version (lol). My whole laptop is working in terminal mode only. Will again install desktop version. Thank you for commenting :)
Comment: @pallavbohara I know what Legacy boot mode means. It has nothing to do with how the disk is accessed by the SATA/IDE drivers. I never said anythinga bout EFI mode. The open source drivers for your card might also not perform very well if you're using the NVidia only for graphics. Installing the proprietary nvidia drivers might help there, with perceived performance.
Comment: After using 64-bit os and Nvidia Proprietary driver my system is working great :) Thank you @dobey and JonasCz for such a in depth information and help.
Answer: After using 64-bit os and Nvidia Proprietary driver my system is working great :) Thank you @dobey and @JonasCz for such a in depth information and help. And i am adding this line just to complete minimum word limit to answer on StackExchange.


Noise from headphones

Question: I've recently installed Ubuntu 14.04. When I plug my headphones in I hear an annoying noise . The noise is not influenced by the volume level as well as the software used. It is just always there. Any idea? I have a Dell M3800.
 I tried different kind of headphones but the white noise is there.
This might help:
    card 0: HDMI [HDA Intel HDMI], device 3: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: HDMI [HDA Intel HDMI], device 7: HDMI 1 [HDMI 1]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: HDMI [HDA Intel HDMI], device 8: HDMI 2 [HDMI 2]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 1: PCH [HDA Intel PCH], device 0: ALC668 Analog [ALC668 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

Thank you in advance.
Answer: They say that it is fixed in kernel 3.16 so try this first.
sudo apt-get install linux-generic-lts-utopic

It didn't work for me so i tried the workaround found in the link below and that worked for me.
http://xps13-9333.appspot.com/#background_noise

mkdir -p /usr/local/bin
wget -O /usr/local/bin/white_noise_fix.py http://xps13-9333.appspot.com/root/usr/local/bin/white_noise_fix.py
chmod 744 /usr/local/bin/white_noise_fix.py

After that, disable the power saving mode of the audio card to prevent pop noises, electrical noises and, more importantly, the white noise, which otherwise will come back:
mkdir -p /etc/pm/config.d
echo INTEL_AUDIO_POWERSAVE=false > /etc/pm/config.d/snd_hda_intel

More information about the bug can be found here.
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1315770
Comment: This kind of works for me on my Dell M3800.  After following all these steps, and then executing the Python script with `sudo white_noise_fix.py` the white noise goes away completely, but then it comes back, like if I close and open the Sound Settings.  Also, when I restart my computer the white noise is back.
Comment: In the beginning of the appspot link page you will find a script and instructions how to run it every startup.
Comment: Great helped me out on Dell 3800 Ubuntu 14.04
Comment: Worked for me on my Asus Zenbook Ubuntu 16.04 -- thanks a ton!
Answer: It can be Alsa boost or more likely you are using wireless mouse or some usb or wireless port that is right next to headphones jack and headphones intercept interference. The solution is to specially separate the jack and interference device. In my case it was wireless mouse and I just took usb extension cord + wireless Ian hub for mouse and connected it to use port furthest from headphones. Hope this helps
Comment: I'd upvote this a thousand more times if I could. I searched the internet for like hours and couldn't find a  working fix for this. Then I re-searched every page and looked at this answer. Half-heartedly, I thought that it couldn't hurt to *try* so I removed my wireless mouse dongle from the front USB port and BAM! Noise gone.
Answer: I had a similar problem,
since I couldn´t find an answer for my problem I started synaptic and erased "alsa-base" and "alsa-utils". Reboot, no background sound anymore. Heaven. Hope it works
Comment: How to do that? Can you please mention the steps?
Answer: I haven't addressed the root of the problem, but just kind of made it a virtually unnoticable.
So, the hack is quite simple. As the problem persists only when there is no playback, I came up with a hack to always have a playback!
Now, this should be true only when the headphones are connected. And the playback should stop when headphones are removed.
Follow these simple steps-
Step #1: Install mplayer and configure it. (mplayer because I am very sure that I won't be using it for playing music ever!)
sudo apt install mplayer
nano ~/.mplayer/config

type in that file-> lirc=no
Step #2: Download this mp3 file from here (silence-10sec.mp3)
Step #3: Create a folder in home directory and name it .hush
Copy the mp3 file in your .hush directory
cp ~/Downloads/silence-10sec.mp3 ~/.hush/

In that folder, create a script file and name it silence.sh
Copy paste this code in the script file.
#!/bin/bash

plugged="jack/headphone HEADPHONE plug"
unplugged="jack/headphone HEADPHONE unplug"

acpi_listen | while IFS= read -r event;
do
    if [ "$event" == "$plugged" ]
    then
       mplayer -really-quiet -loop 0 ~/.scripts/silence-10sec.mp3 &
    elif [ "$event" == "$unplugged" ]
    then
       pkill -f mplayer
    fi
done

Make it executable with the command chmod +755 silence.sh
Step #4: Type startup applications in the Dash and add the path of silence.sh script to it.

So, basically what we are doing is listening to events of headphones been connected and disconnected and playing or stopping the blank mp3 file in a loop. Now, I have used mplayer because I know that I am never gonna use that for any other purpose and killing its process is completely safe for me.

Noise from headphones


Yii2 unit testing :: Access denied for user 'something'@'localhost' (using password: NO)

Question: When creating automated testing in unit testing. I get this error.
My code is in unit test
 function testSavingUser()
{
    $user = new User();
    $user->auth_key='value';
    $user->password_hash='value';
    $user->password_reset_token='value';
    $user->email='value';
    $user->status=1;
    $user->first_name='value';
    $user->last_name='value';
    $user->image='value';
    $user->role_id=1;
    $user->created_date='2016-08-31 16:57:10';
    $user->updated_date='2016-08-31 16:57:10';

    $user->save();
    $this->assertEquals('Miles Davis', $user->getFullName());
    $this->tester->seeInDatabase('users', ['name' => 'Miles', 'surname' => 'Davis']);
}

This my config file
    $config =  yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/web.php'),
    //require(__DIR__ . '/main-local.php'),
    [
        'id' => 'app-tests',
        'components' => [
            'db' => [
                'class' => 'yii\db\Connection',
                'dsn' => 'mysql:host=' . getenv('DB_HOST'). ';dbname=' . getenv('DB_NAME'),
                'username' => getenv('DB_USER'),
                'password' => getenv('DB_PASSWORD'),
                'charset' => 'utf8',
            ],
        ]
    ]
);
return $config;

In functional.suite.yml
class_name: FunctionalTester
    modules:
      enabled:
         - Yii2:
             configFile: 'config/test.php'

When trying to execute my test with codecept run it shows error like this

[yii\db\Exception] SQLSTATE[28000] [1045] Access denied for user 'something'@'localhost' (using password: NO)
Comment: `using password: NO` is a clue that something is wrong with your database parameters
Comment: Are you sure 'something' user have access for database?
Comment: Yes  i  am sure user have access
Answer: Possible reasons of error:

Provided credentials are incorrect or mixed with each other. Check them accurately for typos, etc.
Environment variables are not accessed or extracted correctly with getenv calls. Check if the keys are right and make sure that correct values returned (you can use something like var_dump).
User has no privileges to access this database. You can see how to set it for example in this related question.


VSCode Git via Remote-SSH

Question: I have a VMWare Fusion 11.5 running which holds my repos. I prefer to run my tools on the Mac (Azure SQL Studio, VSCode etc) and not on the VM so I have setup VSCode to SSH to the VM machine.
Everything works, updating the code git status, add and commit however when I try to git pull/push from bitbucket nothing happens, no error message no time out nothing.
SSH is password based i think (it asks me for my password when I try to connect to the VM via SSH).
Any ideas?
Answer: If it asks for a password (the password of the remote account) and not a passphrase, that means the public key was not properly registered to the VMWare remote machine, at ~/.ssh/authorized_keys.
Start by adding your MacOS ~/.ssh/id_rsa.pub content to the remote user ~/.ssh/authrized_keys file.
Comment: I have failed to make VSCode connect via private-public key pair, I have followed the the instructions on the VSCode website in regards to the Remote-SSH.

However using the keys to connect is not my problem (I do not really have a problem having to enter a password when I connect) unless I need to connect via a key pari for git push / pull to work. But why would that be the case?
Comment: If it is a public repo, it won't be the case for pulling. But pushing is generally linked to authentication first.
Comment: it is not public, usually i get asked password to push and pull but that shouldn't have anything to do with my shh authentication to the VM. Does it mean that it expects authentication to bitbucket but the request for my repo password is not coming through to the ssh terminal?
Comment: @user3829059 If your SSH private key is not protected by a passphrase, and it still asks for a *password*, that means it (the remote side) does not find your public key and defaults to username/password.
Comment: Yes I understand this. But is a key/passphrase necessary for git push/pull?
Comment: @user3829059 Yes at least for push (not pull for public repo)
Comment: ok thank you I will try to set it up again and post with the results.
Comment: So this hasn't actually done anything , I have managed to use a pubkey to authenticate ssh sessions from VSCode to VM windows, however pull and push still do not work.

VSCode Git via Remote-SSH


Does a closed form solution for $x$ exist for $k\cdot\Bigg(1-\bigg(\frac{1}{2}\bigg)^{\frac{x}{y}}\Bigg) = x $?

Question: In an engineering problem I was working on, I have found a function of three variables:
$$f(x, y, k) = k\cdot\Bigg(1-\bigg(\frac{1}{2}\bigg)^{\frac{x}{y}}\Bigg) = x $$
In certain applications, we hold $y$ and $k$ constant, and consider it to act as a function of one variable. In that case, is it possible to express the zeroes of the function $f(x) = 0$ in closed form in terms of $y$ and $k$? Of course the solutions can be found numerically, but it would be convenient to have a closed form if possible.
For example, in one case, $k=134201.63$ and $y=5\cdot10^4$. In this case, the zero occurs at approximately $x=101208.723$.
Comment: It has a closed form solution, but it won't be in terms of elementary functions.
Answer: Let set  $X=\frac xk$ and $a=\left(\frac 12\right)^{\frac ky}$
The equation becomes $1-a^X=X$
No set $U=1-X$ then $U=a^X=a^{1-U}=aa^{-U}\iff Ua^U=a$
Finally for $\alpha=\ln(a)$ and $V=\alpha U$ leads to $$Ve^V=a\ln(a)=\alpha e^\alpha$$
But $xe^x$ is not injective, its reciprocal the Lambert $W$ function has two branches $W_0$ and $W_{-1}$
https://en.wikipedia.org/wiki/Lambert_W_function
From the figures you have given we have $\alpha<-1$ so the two solutions are

$V_1=W_{-1}(\alpha e^\alpha)=\alpha\implies U_1=1\implies x_1=0$
$V_2=W_0(a\ln(a))\implies x_2=k\left(1-\dfrac{W_0(a\ln(a))}{\ln(a)}\right)$

For other values of $a$, it may happen that the non-zero value is reached for $W_{-1}$ instead.
You have to evaluate though, whether calculating this thing is more efficient than a numerical solving of the initial equation or even numerically solve the simpler $Ua^U=a$, I guess it all comes to whether you have a good implementation of the LambertW function on your platform or not.


Colors in grouped boxplots in R

Question: I am creating grouped boxplots for a stratified sample using ggplot. As a made up example, on the y-axis is the value (say, test scores) and on the x-axis are the categories (White, Black, and Asian. But I also am gruoping eaching category by another variable (say, male vs. female). So, there will be 6 boxes.
I want the categories to have the colors red, blue, and purple. But I want the sex grouping variable to make the colors light and dark (e.g., male asian = light purple and female asians = dark purple).
Is this possible? Thanks!
I have searched pretty extensively online and not found a solution. I am sure I can't be the first person doing this, but I haven't found an explanation for how to do this yet.
Comment: A common way to do this is to map `sex` to the `alpha` aesthetic, which controls transparency. [Here's one example](https://stackoverflow.com/q/24800626/903061).
Comment: It's worth pointing out that from a data visualisation perspective, there is no reason to color each group on the x axis a different color: they are already clearly labelled, so this is unnecessary embellishment that ultimately makes the plot more difficult for the viewer to parse, purely for the "eye candy" effect of color.
Comment: Check this gallery as well https://r-graph-gallery.com/boxplot.html
Answer: There are a couple of different ways to do this. You could use the alpha aesthetic:
ggplot(df, aes(Race, Score, fill = Race, alpha = Sex,,
               group = interaction(Sex, Race))) +
  geom_boxplot(outlier.colour = NA) +
  geom_point(size = 0.5, position = position_jitterdodge(0.1), alpha = 0.2) +
  scale_fill_manual(NULL, values = c("deepskyblue", "purple", "red")) +
  scale_y_continuous(limits = c(0, 6), expand = c(0, 0)) +
  theme_minimal(base_size = 20) +
  labs(x = NULL) +
  scale_alpha_manual(values = c(0.5, 1)) +
  guides(alpha = guide_legend(override.aes = list(fill = "gray"))) +
  theme(panel.grid.major.x = element_blank())

Or fill by the interaction of Sex and Race
ggplot(df, aes(Race, Score, fill = interaction(Sex, Race, sep = " "),
               group = interaction(Sex, Race))) +
  geom_boxplot(alpha = 0.7, outlier.colour = NA) +
  geom_point(size = 0.5, position = position_jitterdodge(0.1), alpha = 0.2) +
  scale_fill_manual(NULL, values = c("deepskyblue3", "deepskyblue",
                                     "purple3", "purple",
                                     "red3", "red")) +
  scale_y_continuous(limits = c(0, 6), expand = c(0, 0)) +
  theme_minimal(base_size = 20) +
  labs(x = NULL) +
  theme(panel.grid.major.x = element_blank())

Personally, I find this use of color gratuitous and confusing. When presenting data, color should be used to clearly identify groupings, but there is no need to do this if the grouping are already apparent on the axis. I think the following is cleaner, classier and easier to understand at a glance (as well as being colorblind safe)
ggplot(df, aes(Race, Score, fill = Sex, group = interaction(Sex, Race))) +
  geom_boxplot(alpha = 0.5, outlier.colour = NA, width = 0.3,
               position = position_dodge(0.5)) +
  geom_point(size = 0.5, position = position_jitterdodge(0.05, 0, 0.5),
             alpha = 0.2) +
  scale_fill_manual(NULL, values = c("gold", "deepskyblue4")) +
  scale_y_continuous(limits = c(0, 6), expand = c(0, 0)) +
  theme_minimal(base_size = 20) +
  labs(x = NULL) +
  theme(panel.grid.major.x = element_blank(), legend.position = "top")

Colors in grouped boxplots in R


C# can't split a string into an array by newline (from StreamReader)

Question: StreamReader login = new StreamReader("C:/Users/Me/Documents/logins.txt");
            string ar = login.ReadToEnd();
            string[] names = ar.Split("\r\n");
login.Close();

I'm reading from a file a set of logins, exampled as "username,password" then a newline as "usr,pwd" or something else. I want to split the txt file into a set of arrays by splitting at the start of a new line, but "\r\n" doesn't seem to be working, coming up with the error "cannot convert from string to char". I have tried Environment.Newline, but that is not working either, coming with the same error message.
Comment: Why not just use [`File.ReadAllLines`](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readalllines?view=netframework-4.8#System_IO_File_ReadAllLines_System_String_) instead?
Answer: Instead of dealing with a stream just use File.ReadAllLines
string[] names = File.ReadAllLines("C:/Users/Me/Documents/logins.txt");

Comment: Thanks! I was told to use stream, but I was just wondering, what's the difference between each one?
Comment: The difference is that `File.ReadAllLines` basically handles opening and closing the stream and reading in the lines for you.  You can check out the implementation [here](https://referencesource.microsoft.com/#mscorlib/system/io/file.cs,675b2259e8706c26)
Answer: String.Split needs an array or eiter char or string values to split on. You need to change your code to:
string[] names = ar.Split(new string[]{"\r\n"}, StringSplitOptions.None);

Comment: Thanks! Works fine now. Just curious, what does the StringSplitOptions do? Why does it make a difference?
Comment: @EdwardPugh - It's used to specify whether you get lines which are empty (`None`) or if it should remove empty lines from the resulting array (`RemoveEmptyEntries`)
Answer: You can read each line individually like so:
using (StreamReader reader = new StreamReader(pathToFile)) {
    string line = reader.ReadLine();
}

This may be preferable as you don't have to rely on the line return type to be correct using a char


How to create RPMs under Windows only by useing install free binaries or .net?

Question: I am looking for a lightweight method to create rpm packages under MS Windows environments.
Actually I use Cygwin. I generate the rpm by using cmake(cpack). For cmake I need to install gcc to bypass the compiler check. For the rpm generation I have the rpm & rpm-build packages installed. When I am checking the size of the Cygwin dir it is around 2.2GByte. Quite a lot for generating a "simple" rpm.
Is there a "better" way to generate RPMs? Maybe in .net etc.?
Comment: why do you need an rpm for windows ?
Comment: to manage configuration for an embeeded system
Answer: I know I'm a bit late to the party, but I've started the dotnet-packaging project, which allows you to create RPM and Debian packages on any platform that hosts .NET/.NET Core. So that includes Windows.
You can either use it as a library or as a .NET command-line utility (e.g. you could just run dotnet rpm on your project and it would create a RPM file for you).
https://github.com/qmfrederik/dotnet-packaging has the code and a getting started guide, let me know if that works.


What does a m*n*3 matric signify?

Question:
Possible Duplicate:
What are the 3 dimensions of an RGB image in MATLAB?

in matlab my colored images are in the form of a m*n*3 matrix form, what does the 3 dimension signify?
will i lose any data if u skip the third dimension?
as far as i reason, at the coordinates m,n the value is a pixel, what is the third dimension for?
For example is
<code>B(1,2,3)=B(1,2)
</code>
???
Comment: Probably one dimension per color channel in the image....
Answer: The third dimension is the color channel. It stands for Red,Green and Blue.
B(1,2,3) is the blue channel of the pixel located at row 1, column 2.
Answer: It's color! In the form of triplets representing each color's intensity (R,G,B).  If you skip the third dimension, you picture will only display shades of one color channel -- red, I think.
Comment: Well, it will be the information from the red channel, BUT the picture will display in shades of GRAY, not red.

What does a m*n*3 matric signify?


residue of $\frac{1}{1+z^{2}}$

Question: I first expanded the equation into $\frac{1}{(z-i)(z+i)}$, then I apply the theorem that
$$\underset{z=i}{Res}\frac{1}{(z-i)(z+i)}=\lim_{z\rightarrow i}(z-i)\frac{1}{(z-i)(z+i)}=\frac{1}{2i} $$ but the correct answer should be $\frac{-i}{2}$, which step is wrong?
Comment: $\frac{-i}{2}=\frac{1}{2i}$.
Answer: Note that $\frac{1}{i} = -i$, since $i^2 = i \cdot i = -1$.

residue of $\frac{1}{1+z^{2}}$


No windows 7 option in grub

Question: Gys I installed ubuntu 12.04 on my desktop which had windows 7 previously.
After installing ubuntu their was no option for boot selection and ubuntu 12.04 was getting booted automatically. I used boot repair to fix this problem, but now grub shows only options to boot into ubuntu.
Here is the log from boot repair:
http://paste.ubuntu.com/1633565/
Comment: Maybe you find `Windows 7 loader locacted on dev/xyz` msg?
Answer: You didn't mention which boot manager is your preference, windows or Ubuntu.
If you want windows to manage the boot menu, it wouldn't recognize Ubuntu directly without a 3rd party boot manager like easyBCD.
 If you want Ubuntu to manager the boot menu, you need to load grub2. or you can repair your windows boot manager from the windows 7 install disk in repair mode.

No windows 7 option in grub


Swift initialization of array if nil

Question: I want to initialiaze an array if it is nil.
The reason for this is that I have an optional array (as I want it to be nil until an API call is made - it is optional and this is part of the question context):
Here is the issue:
var array: [String]? = ["1","2","3"]
if array == nil { pageArray = []}
array! += ["4"]

The code works but is not easy to read. There is a force unwrap for array which is not good.
What the question isn't: Note this is not production code, does not contain the imports for UIKit or other code not related to the array.I may have badly named variable etc. but this question is about an array. I may have misspelt something in this question and it might not be clear, but I really need help on the initialization of the array and the title of the question (and the question itself) refers to this.
What I've tried I tried a guard, but of course guards should not fallthrough so this seems a poor option.
The question How can I initialize an array if and only if it is nil?
Comment: Your first issue is that `LoginResponse` response works by setting the value of a global variable like `pageArray`. That's nasty, and it's going to bite you in the ass. Instead, use a proper async mechanism. It could be callback closures, Futures/Promises, or observable streams like from RxSwift or Apple's Combine. I would start with https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f
Comment: I am. This is a code snippet to explain the problem with the initialization of an array. It is nothing to do with global variables or similar, the response is given to give some idea of the issue at hand (note: there is also no network code here at all, I haven't included UIKit/Foundation and more: this isn't a mistake it is to make this a small example about the initialization of an array).
Comment: Hmm, then I don't get it. What relevance does `let content = LoginResponse(linkslist: ["1","2","3"])` have, exactly? Does it effect `pageArray` in some capacity? If it doesn't, then why is there the seperation between declaration (`var pageArray: [Page]?`) and initialization (`if pageArray == nil { pageArray = [] }`)? Why couldn't you just write `var pageArray = []`
Comment: It's a minimal example, without an API call. To try to head off inevitable questions of "just don't use an optional array". I'll rewrite the question then, to give less context for you then to make it easy to understand.
Comment: My issue is that I assumed that everythign you provided was already part of a minimal example. As such, I figure that there's a reason why the line `let content = LoginResponse(linkslist: ["1","2","3"])` is where it is, and that there's a reason that you wrote a seperate decl/init rather than just `var pageArray = []`.
Comment: I hope I don't get downvoted for not providing context. People will now ask why the array is optional. But I'll deal with that when the questions + downvotes come.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/199813/discussion-between-alexander-and-wishihadthreeguns).
Answer: First of all, you should better re-consider if you really need to distinguish an empty Array and nil. You may think you need it, but your example is so simplified that readers cannot judge if it really is needed.
Assuming you need it Optional, I would write it as:
var array: [String]? = ["1","2","3"]
array = (array ?? []) + ["4"]

Swift initialization of array if nil


How is the material design Snackbar accessible if someone is using a screen reader?

Question:
I have an accessibility question about the snackbar pattern used in Material Design. Snackbars - Material Design
The behaviour of a snackbar is to appear for a temporary period of time then automatically dismiss itself.
To me it doesn't appear to be accessible for a user who has screen reader turned on as the reader may miss reading out this message.
What are your thoughts?
Answer: UI elements that appear after the page is loaded can be annotated with aria-live so that screen readers will read the changes in the UI.

Using JavaScript, it is possible to dynamically change parts of a page without requiring the entire page to reload — for instance, to update a list of search results on the fly, or to display a discreet alert or notification which does not require user interaction. While these changes are usually visually apparent to users who can see the page, they may not be obvious to users of assistive technologies. ARIA live regions fill this gap and provide a way to programmatically expose dynamic content changes in a way that can be announced by assistive technologies.
— Mozilla Developer Network, retrieved 2019-09-03

It is up to the implementation to ensure the Material Design guidelines are used in a way that is accessible for all users. For example, a Material Design framework for Angular specifically addresses accessibility for snackbars in their implementation. They mention:

Snack-bar messages are announced via an aria-live region. By default, the polite setting is used.
Answer: There are accessibility options for the snacker, as detailed in this forums post here:
https://github.com/material-components/material-components/issues/60
Comment: Thanks for sending the link Darryl. My understanding from reading this is that for it to be accessible the snackbar duration needs to be set to 99999/infinite and an explicit dismiss button should be added so it can be manually dismissed by the user. Is that your understanding too?


how can I build a lucene query with two or more "in" clauses

Question: My document in Lucene (solr, really) has several fields, lets call them textField1, numField1, numField2.
My application will have a list of search terms words1 textField needs to query against, a list of numbers list1 for numField1, and another list of numbers list2 for numField2.
I will like to create a Lucene query that does this:
<code>textField matches one or more words in words1
AND either (
    numfield1 is one of the values in list1 OR
    numfield2 is one of the values in list2)
</code>
I'm trying to use BooleanQuery to build the query, but I'm not exactly sure how to do it. It seems the AND and OR boolean operations map to the different enums in BooleanClause.Occurs, but I can't glean from the documentation how they map to each other.
Answer: I recommend you to get Luke and play with it until you are sure your query is correct and brings back what you want.
When you're done, you can have a look at parsed query (hint: click on Explain structure) and it will show you how BooleanQueries are stacked.
Just make sure you are using the same analyzer you used to index the documents.
Answer: you should use

textfieldl1:words1 AND (list1:numfield1 OR list1:numfield2)


Handling gzip compression in Nancy/Owin

Question: We are developing backend API's using Nancy. Other than hosting it using IIS, we are self-hosting it using Owin. Since Owin does not handle gzip compression automatically (as IIS does), we need to introduce a middleman to handle response/request compression or de-compression. Are there any libraries available already? If there is no libraries available, what is the best way to do it?
Comment: Here is a link to an open source project.  https://github.com/Thorium/Owin.Compression
Answer: <code>    using System.IO.Compression;

  protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
        pipelines.AfterRequest.AddItemToEndOfPipeline(AddGZip);
    }

private void AddGZip(NancyContext context)
    {
        if ((!context.Response.ContentType.Contains("application/json")) || !context.Request.Headers.AcceptEncoding.Any(
               x => x.Contains("gzip")) || !CompressResponse(context.Request.Url.ToString())) return;
        var jsonData = new MemoryStream();

        context.Response.Contents.Invoke(jsonData);
        jsonData.Position = 0;
        context.Response.Headers["Content-Encoding"] = "gzip";
        context.Response.Contents = s =>
        {
            var gzip = new GZipStream(s, CompressionMode.Compress, true);
            jsonData.CopyTo(gzip);
            gzip.Close();
        };
    }
</code>

Handling gzip compression in Nancy/Owin


How do I ensure my wood screws have a minimum of 120 lbs pull out or shear strength?

Question: Some assembly instructions for a project I am doing requires that I use fasteners (screws) with a minimum of 120 lbs pull out or shear strength.  What I plan to use is #8 2 1/2" coarse thread wood screws.  I've noticed that none of the boxes of screws I've ever bought in the past two years indicate any such thing anywhere on the box.  Is this pretty much a standard weight threshold with all wood screws or are some brands just "cheap" and don't make the cut?
Update:  I'll mark the only answer as the answer because it answers my question.  However, if you're not sure about the strength of your screws and you absolutely need to be, buy a brand new box that has the shear and pull-out strength clearly labeled on the box.  This is what I ultimately did.
Comment: You know there are two ways of measuring strength of screws: 1) initial strength, which is called "impact strength" and is usually about 2 times the strength of "working strength", 2) Working strength is the long term strength of screws in wood.
Answer: The pull-out strength of a wood screw is going to be more dependent on the wood into which it is installed than on the material of the screw. The geometry of the screw thread also plays a role. "Cheap" screws therefore aren't what you need to worry about, instead, focus on the screw size.
Pull-out happens when you have a shear failure of the wood. A couple of formulas have been proposed to make an estimate of holding power
The Forest Products Lab of the US Department of Agriculture proposes the following:
p=15700*G^2*D*L

where p is the pull out force in pounds; G is the specific gravity of the wood (density of the wood divided by the density of water, see table 5-3 here); D is the shank diameter of the screw in inches; L is the penetration of the threaded part of the screw in inches. (Assumes reasonable pilot hole, screw into side-grain, etc...I haven't communicated all the nuance here. If your application is important enough to be calculating the pullout load, read the whole relevant section of the source document.)
Others have proposed a simple formula (stated incorrectly after the link, corrected here by me) related directly to the shear strength of the wood:
p=pi*D*L*S

where p is again the pullout strength; pi=3.14; D is the diameter of the screw, L is the length of engaged threads, and S is the shear strength of the wood. (make sure your shear strength is in units compatible with your length, e.g. if your length is in inches, your shear strength should be in PSI).
This simpler formula idealizes things and assumes that all the load is carried by a cylindrical region of the wood that is the diameter and length of the embedded screw threads (the pi*D*L above is the area of this surface). If you use this formula, be sure to reduce the actual load by a generous safety factor of 2 or more.
Personally, I'd read the FPL report and use the first formula.
Comment: "So the writers of these instructions for my project expect..." likely, no. Rather, this is text the lawyers insisted be added.
Comment: So the writers of these instructions for my project expect people to read page-long reports to find out what they mean by "pull-out" or "shear" stength?  There has got to be a simpler answer.
Comment: Ignorance is bliss. I'll still stand on the other side of the room when I come over to your house, though.
Comment: I think the writers of your instructions "punted." I assume the step you're talking about connects something they provided, like a bracket, to something you provided, like a wall. Therefore there's no one right answer.
Comment: You're spot-on.  Their RSIC and my studs.  I think I am just going to wing it with some good, name-brand wood screws like your average, not-so-worrysome DIY'er.
Comment: That was my assumption, as well.  I ended up getting #10 screws that illustrate their shear/pull-out which is far greater than what's required for this project.  Of course, I realize that the studs play a part in it, but I think I am in good shape here.
Answer: The method I use is make a bracket, attach it to a stud in my garage low down and stand on it. I weigh 260. If it will hold me it is safe for 130-150 installed with the same screws in studs of the same wood. Empirical, but simple.
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming!


How to add a table name in EXECUTE IMMEDIATE query?

Question: I have one question about "EXECUTE IMMEDIATE".
I have dynamicly changed table name in next plsql statement
DECLARE

TYPE CurTyp IS REF CURSOR;
cur CurTyp;
str1 VARCHAR2(30);
str2 VARCHAR2(30);
table_name  VARCHAR2(30);

BEGIN

select data
  into table_name
  from ref
 where o_id = 111
   and a_id = 222;

OPEN cur FOR
'select  name, sname  from :1 b,myobjects a where a.obj_id = b.obj_id'
USING table_name;
LOOP
FETCH cur INTO str1, str2;
EXIT WHEN cur%NOTFOUND;
dbms_output.put_line(str1||str2);
END LOOP;
CLOSE cur;
END

Is it possible to read the result of next Execute Immediate query to cursor?
'select  name, sname  from :1 b,myobjects a where a.obj_id = b.obj_id'
    USING table_name;

Or maybe is there any way to do this?
Thanks in advance.
Answer: For object names you must use concatenation, not bind variables.
From the Dynamic SQL chapter of the PL/SQL Language Reference:

The database uses the values of bind variables exclusively and does
  not interpret their contents in any way.

Bind variables help with security and performance.  But they won't work with objects like tables.  If you pass in a table name then Oracle must interpret the contents, which will negate the security and performance benefits.
Comment: jonearles thanks for you answer, and thanks for this link it very usefull.
Answer: You can use ref_cursor
see http://docs.oracle.com/cd/B10500_01/appdev.920/a96590/adg09dyn.htm
the example:
CREATE OR REPLACE PROCEDURE query_invoice(
       month VARCHAR2,
       year VARCHAR2) IS
    TYPE cur_typ IS REF CURSOR;
    c cur_typ;
    query_str VARCHAR2(200);
    inv_num NUMBER;
    inv_cust VARCHAR2(20);
    inv_amt NUMBER;
BEGIN
    query_str := 'SELECT num, cust, amt FROM inv_' || month ||'_'|| year
      || ' WHERE invnum = :id';
    OPEN c FOR query_str USING inv_num;
    LOOP
        FETCH c INTO inv_num, inv_cust, inv_amt;
        EXIT WHEN c%NOTFOUND;
        -- process row here
    END LOOP;
    CLOSE c;
END;
/

but as @jonearles said, you can't insert the table names as params


How to fetch data from Apollo-Server without using React in nodeJs?

Question: I was wondering If I can fetch data from Apollo-Server (GraphQL) without using React,
I searched for some tutorials which based on fetch but node-fetch didn't work that way
here is my code for fetching data
const getData = (query)=>{

return fetch("http://localhost:4000/graphql",{
    method: "POST",
    headers: {
        "Content-Type" : "application/json",
        "Accept" : "application/json"
    },
    body: JSON.stringify(query)
}).then(response=>response.json()).then(data=>{
    return data
}).catch(err=>console.log(err));

}
and the query was:
query=`
query Blogs {
    blogs {
      title
      content
      imageUrl
    }
  }

EDIT
Axios worked very well! here is the final code:
const getData = async () => {

const endpoint = "http://localhost:4000/graphql";
const headers = {
    "content-type": "application/json",
};
const graphqlQuery = {
    "query": `query Blogs {
    blogs {
      title
      content
      imageUrl
    }
  }
`,
};

const response = await axios.post(endpoint, graphqlQuery, {
    method: 'post',
    headers: headers,
});

console.log(response.data.data.blogs); // data
console.log(response.errors); // errors if any

}
Answer: Try to use axios for fetching data and set headers = {}


Can a Lucio ult counter a McCree ult?

Question: McCree's ult is...complicated. He ramps up potential damage against all targets in his field of view over time. Once he has enough damage ramped up, a skull appears. When he pulls the trigger, he kills all enemies with a skull, and deals damage to all other enemies based on how long they were in his field of view (i.e. how much damage ramped up). Enemies with more health, like Roadhog, take longer to get the "skull" because the damage ramps up slower proportional to his max health.
I get all that.
But how does this interact with Lucio's ult? I've tried to use a Lucio ult to counter a McCree ult in the past, and I'm not sure how effective it was.
How does this work in these situations:

Lucio and McCree ult at the same time. Everyone gets a huge, but diminishing health pool while McCree ramps up damage. I imagine that this kind of Lucio ult doesn't help much, because by the time McCree fires most of the bonus health is gone anyway. Does McCree lock on "faster" because of the diminishing health?
McCree ults, and then just before he pulls the trigger, Lucio ults. This is the more interesting case. Can Lucio "remove" the skull symbol from McCree's locked on targets by ulting and temporarily boosting their health pool?
Answer: Situation 1: McCree's lock-on delay for each player is increased proportional to the amount of effective health gained through Lucio's ult. Given that McCree is allowed to use his ult unhindered, you are correct in your assumption that Lucio's ult would do very little.
That said, the delay caused by Sound Barrier is likely to afford your team the time to either prevent him from going through with it or at least to find suitable cover.
Situation 2: It is exactly as you have said. In my experience, and as indicated by a player's account of his experience in this reddit post, increasing a player's effective health removes McCree's lock on effect; however, I am not sure if this resets the delay entirely or if it just increases the delay proportional to the health gained. Either way, it's worth investigation.
In short, Lucio's ult is very effective at countering Deadeye.
Comment: +1, I can say personally that I've stopped Deadeye from killing *any* of my teammates by using Sound Barrier multiple times.
Comment: Worth noting that as McCree's Deadeye charges lock-on at a rate of 170 health per second, while Lucio's Sound Barrier decays at a rate of 100 per second, it appears as though Deadeye locks on faster, as it is increasing the damage floor by 170 while the ceiling drops by 100.
Comment: That is correct in the case where he is allowed to stand and charge it. But the initial spike in Health will remove the lock-on provided that he has not charged it enough to out-damage the shield.
Answer:
McCree has 6 seconds to pull the trigger while Lucio's ultimate will be fully exhausted in 5 (+500 armor and -100 armor per second).
Grudging by this (where they talk about McCree) Lucio and his teammates will have the upper hand.
Comment: Throw in the fact that if you're dropping the beat in response to the 'High Noon' all, you can bait the lock-in damage, then drop the beat a few seconds in to prevent the McCree from fully locking-in to most targets as he'll have to fire while Sound Barrier is still decaying.

Can a Lucio ult counter a McCree ult?


Black screen when playing a movie in VLC player in Kubuntu 12.04

Question: This is not a duplicate of this question. In my situation, my AVI files will play correctly in other installed players -- but not in VLC. Unfortunately, I need frame-by-frame controls, and VLC is the only player I have installed that offers that feature. But VLC won't always play my AVI files. It seems to depend on the recording options (such as HD or standard def and frame rate), although I'm not entirely sure why some play and some don't.
Given that some other players on my system play these files, can I assume I have all the drivers needed? The players that work include MPlayer and Dragon player. Everything is fine in those players. And VLC sometimes plays AVI video files. (The files it won't play are played by the other players, so I believe my system has all the codecs required.)
When I installed Kubuntu I installed these packages:
sudo apt-get --yes install app-install-data-medibuntu apport-hooks-medibuntu

sudo apt-get install w64codecs libdvdcss2 non-free-codecs ffmpeg libxine1-ffmpeg gxine mencoder libmpcdec6 libquicktime2 libmp4v2-2 flac faac faad sox ffmpeg2theora libmpeg2-4 uudeview flac libmpeg3-1 mpeg3-utils mpegdemux liba52-dev mpeg2dec vorbis-tools id3v2 mpg123 libflac++6 ffmpeg totem-mozilla icedax tagtool easytag id3tool lame libmad0 libjpeg-progs kubuntu-restricted-extras libdvdread4

(Do I need all those?)
These were not installed:
gstreamer0.10-plugins-ugly-multiverse gstreamer0.10-plugins-bad-multiverse gstreamer0.10-plugins-bad gstreamer0.10-plugins-ugly gstreamer0.10-ffmpeg

Answer: The solution was as simple as this:
$ sudo apt-get --reinstall install kubuntu-restricted-extras

VLC works now! :)
Answer: A little late on the issue, but in my case VLC was failing to embed video output window into the main window (I've concluded that from observing a small window appearing with video displayed right after quitting the player while the video was playing). So after switching off
Tools > Preferences > All > Video > Embedded video

checkbox and restarting VLC the video played with HW acceleration, but in a separate window.
Installing/uninstalling kubuntu-restricted-extras had no effect, though I've had ubuntu-restricted-extras installed all along.
On another note, mpv was able to display the same video from the box.
Comment: As this question is over 10 years old it is probably of no use to try and offer an answer that is for a different version of VLC.


What are the long term consequences of building with your second settler?

Question: Sometimes when playing Civilization II, you will be graced with a second settler. This settler can be quite advantageous, because the settler doesn't require any food support, nor taking your city size down by 1 to start improving your initial city. Saving 40 shields at this stage of the game is nothing to sneeze at either.
I have historically made a point to never build with a free settler (starter or wandering nomads): if I am going to build, I might as well do it with one that costs food somewhere, so that city can get that food back.
But it occurs to me that I might also be well served making an improvement or two and then immediately planting a second city. Is it conceivable to go about making an objective analysis of these two initial strategies and what the long term consequences are of this initial decision?
Comment: Haha, yeah Civ 5 is a great one. But there's something about civ2 that has always captivated me. I was playing Settlers of Catan the other night and happened to have civ on the laptop. I couldn't help but notice the striking similarity, especially in color scheme haha!
Comment: lol thought this was a Civ 5 question for a second...was like what are you talking about!
Answer: Think about the shield production of your first city and irrigation/roads it needs. Can you build a third settler in the time your settler is upgrading? Churn out settlers from that city, rely on new cities for production, and use the foodless settler for roads.
Is there a danger/need of early armies? Make that settler into a city quickly, unless it will stretch your potential defenses (2 cities shouldn't), in which case consider joining it into your first city after a few improvements.
Does your first city lack the ability to churn out new settlers, no matter the improvements that can be made (not uncommon)? You're going to want that second city with the ability to increase your production. Limiting yourself early on can put you dangerously behind.
If you've got time, try an iterative experiment. Compare the state of your civ 50 turns in with the second city built and without on many maps.
Comment: Oh, I hadn't considered building it into the capital. That would make a great initial boost from say, size 3 to size 4! And the idea of doing a simple run of 50 (maybe 75 ish) turns is a great idea. The 'long term' effects should have stableized by then such that I can get some hard numbers (# cities, # breakers gained, etc). Thanks a bunch!
Answer: In most cases, I try to keep that second settler until about midgame (that is, when I get, or am about to get engineers). Then the settler costs less (in terms or productivity) than engineers to build a new city. And having a settler needing no shield or food support represents a massive savings.
I also try to get "second" settlers near enemy cities. That is, I capture a (small) enemy city, depopulate it (using a settler created from it to "rush build" new ones until the city size is 0). If it is closer to other enemy cities than my own, the settler will have "none" as its home base. Of course, I have military units on hand to protect the settler.
The exceptions are as the other poster mentioned; if you made a mistake with your first city and need to correct it, or if there are enemies nearby, and you need cities now.
Comment: You don't aim for Leo's Workshop to upgrade your settlers into engineers? (To me that's the biggest benefit of it...)
Comment: @corsiKa: That's not my highest priority in medieval times. In descending order, they are Adam Smith's trading company, Michaelangelo's Chapel, and Bach's Cathedral. The computer player usually builds Leo before I do. One disadvantage is that your military units don't upgrade to veterans. I prefer Sun Tzu's Academy, which gives my military that 50% increment; in other words a 40-shield rifleman is really worth 60.


Deleting Realm database while parsing objects

Question: I'm working on an app that uses Realm as database. User can log out at any time and this deletes all objects in realm.
But as my app uses networking, I may be in process of parsing objects at the same time, and I get crash.
*** Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'

Here is my logout function:
- (void)logout {
    RLMRealm *realm = [RLMRealm defaultRealm];

    [realm beginWriteTransaction];
    [realm deleteAllObjects];
    [realm commitWriteTransaction];

    [self showLoginScreen];
}

What is the correct way to handle this? I want to remove all data I have stored on logout.
Comment: I haven't used Realm, but just thinking off the top of my head, you could delete all the objects in a background thread, and put `@synchronized` blocks around the parsing code and the object deletion code (synchronizing on the same mutex, of course).  Alternatively, you might be able to copy the objects you get from Realm so you're not parsing the "live" copies, although I have no idea if Realm supports this.  Finally, you could try just checking whether each object is deleted, although that sounds kinda hackish.
Answer: You can check via the property invalidated whether an object still exists. As locking mechanism you can use the write transaction itself, as these are exclusive with Realm. You enter only one write transaction at a single point in time.


What do I do with a sewer pipe (toilet rough-in) full of cement?

Question: I have a problem that is mind boggling. I bought a house and am now just getting ready to put a toilet in the basement, which has a cement slab. I just took the cover off the rough-in expecting the sewer smell, but to my surprise I got a drain full of poured cement, YES IN THE DRAIN.
What do I do with that? Why anyone would fill the drain with cement is boggling my mind!
Comment: Um, this sounds bad. I wonder how much concrete got in there. If it got far enough it could be blocking other sewer drains as well.
Comment: I have heard rumors that the use of [Drano](http://en.wikipedia.org/wiki/Drano) at incorrect water temperatures can cause it to harden *(and will look like cement)*.
Answer: Since the ultimate solution may be to open floor and cut out the affected drains, lets hope it was only a  poorly sealed cap..  Its worth a few experiments:

Screw in a wedge anchor in center (of cement in drain) and use several pry bars or jacks to lift slug out

Drill a few inches down with a 2" coring bit (rented with a SDS max rotary hammer at local orange big box).  Repeat across the face of drain, being careful not to drill through drain.  Try chisel and point bits to see how deep it extends.  Shop vac pieces as you go, in case you breakthrough (think positively).

Call emergency hotline on the extended home warranty policy (its in with the mortgage papers)
Answer: Sometimes pissed off sellers/foreclosures will do this to ruin the plumbing.  I doubt this was an accident.  Given the situation I would be very careful drilling the concrete.
You could make the situation worse if you drop a big chunk of concrete in your main line out to city.  I would carefully try to get something very thin in to see how thick it is - like a metal coat hanger.
If it isn't "deep", I would jackhammer the area up and cut below the concrete line.  And then replumb from there.
If it is deep you need to get at least to the first elbow and see if you have concrete there.
This isn't a terribly expensive thing if you DIY.  It requires a jackhammer or sledgehammer, shovel, hacksaw, and corresponding replacement PVC.  This isn't rocket science but you need to make sure you aren't dropping huge concrete chunks in you main line.  I have been helping flip houses before and this was my biggest early mistake.  I made a 4 hour job turn into a 20 hour job.


what is it used for _.once in underscore?

Question: I just look at the once API of source in underscore.js, then wandering what is it the used for
in the method, it seems doing nothing:
func = null

the source:
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      memo = func.apply(this, arguments);
      func = null;
      return memo;
    };
  };

Comment: [Have you checked the documentation??](http://underscorejs.org/#once)
Comment: You want to know about the method, or why `func = null` is done?
Answer: What the function does can be found in the documentation:

Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.

Why set func = null is explained in this commit message:

Assuming we'll never run the wrapped function again on _.once(), we can
  assign null to the func variable, so function (and all its inherited
  scopes) may be collected by GC if needed.
Answer: From the official underscorejs website:
once _.once(function)
Creates a version of the function that can only be called one time. Repeated calls to the modified function will have no effect, returning the value from the original call. Useful for initialization functions, instead of having to set a boolean flag and then check it later.
var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.

http://underscorejs.org/#once
Answer: It's unclear if you are asking about the entire function or just the func = null line. If the latter, see just step 3, below.

ran is initially false.
When you run the returned function for the first time:

ran is set to true
the function passed into once is called
the function reference is deleted (presumably to aid garbage collection)
memo is returned

When you run the returned function again (since ran is now true):

memo is returned
Comment: yes, it seems I didn't explain clear, I want to know what the `func = null` is for.
Comment: Removing the reference to it allows it to be garbage collected so it doesn't eat memory.
Answer: Also worth pointing out is that the memo will hold the result of the initially executed function.
So when you call your function again, it will not be executed but the result of the first call will be returned.


Error : The input is not a valid Base-64 string

Question:

    <video autoplay="true" id="videoElement">
    </video>
    <canvas id="myCanvas" width="400" height="350"></canvas>
    <button onclick="snapshot()">Click</button>

Here I am passing the value of imgInfo by ajax call to my MVC controller.

I am passing this data to contact controller and it gives me the error in Convert.FromBase64String() that ..

The input is not a valid Base64 string, as it contains a character that is not a base 64 character, more than two fill characters, or an invalid character among the fill characters

[HttpPost]
public ActionResult Contact(string base64)
{
    var arr = Convert.FromBase64String(base64); //this line gives error.
    Stream stream = new MemoryStream(arr);
}

The string controller is receiving
"data:image/png;base64,iVBsRq1Hm1dxzRO0XRdtB3rHjGO3o/DOOpZtoO+HM08RFvV0VRNVLzPtoqZ/aO7a7T20XYRsY1an8nzrKLvD2Kqxph1hxtdcx6nGOZe+1V7i7c09tFFHcsxotuOsYltnC8qFjDGaeZla3+NVR3TPOo9tXPEIqqYFpP2FHt6mip2bDQt73wbUfXRdry7Kpp5FXM96P2x1tzVPHVs0d2vqamjm3lGv3P2SsOJqrqodQ9TzBPntY2m64NtV0/siyqGRRt9XceyrWJZNXqeYaqimg9irhfas9M8xHo8jXqaoh11amIYNlG1c2yaMeppjGWz0M92bRf11EZbs15z9PMUw6JjU0RU51FNTVRTG3V1I4a5i7ZTqWCBQ0g6Sn0gNTwFtlDXz80k256S07YU/VP2nQ2b59+/kX78uuv2oOPkD+3NvPs5NAmCvW5oz9evmw///RjW67+USLEO2YfS4igIEhllfc+dZ5HApCJdRIlAlvaOKFMC1fWgKVzL/72pQ/XGZwKxcb/p6xEXROyvtqN2tR80bEeQPdH+dsugEwvY6NPufXDeHn38qD24P9fxkKn2P//6uy0WCzntkStJE5os58njJ+3i6dMASUVORK5CYII="

How can I convert this string into base64 Format?
Answer: You can fix this issue by removing data:image/png;base64, from the string like:
public ActionResult Contact(string base64)
{
   if (base64.IndexOf(',') > 0)
   {
      base64 = base64.Substring(base64.IndexOf(',') + 1);
   }
   var arr = Convert.FromBase64String(base64);
   Stream stream = new MemoryStream(arr);

}


Text replacement on different lines

Question: I have multiple entries in a file as mentioned below.
 "Item_1";"Item_1";"Products///Item///ABC///XYZ";"Item_1.jpg}";"";"Buy item

Items

Time";"";"";"";"";"";"Category: M[Item]";"";"";"Y";"N";"N";"None";""

 "Item_2";....

In above text, there is a newline after "Buy item" in the first line & after '/strong>' in second line.
The change which I want to make is -
1. Replace Products///Item///ABC///XYZ with Products///ABC///XYZ
2. Replace "Category: M[Item]" with "Category: M[ABC]"
3. In case if Entry 1 is Products///Item///ABC or Products///ABC, I dont want to change "Category: M[Item]" with "Category: M[ABC]", just change Products///Item///ABC to Products///ABC

I am trying to read entire file line by line & then split by '///' storing number of entries & storing 3rd entry. But this creates issues as I have multiple newlines.
Is there a simpler way of doing it by using regex or something else?
Comment: use the csv module: https://docs.python.org/3.3/library/csv.html
Answer: Like @Casimir suggested, you can use csv module to parse your file (because it'll handle the newlines), like this
import csv

with open(your_filename) as f:
    reader = csv.reader(f, delimeter=';', quotechar='"')

rows = list(reader)

and then do what you want to the parsed result (I'm not quite sure about what you want to achieve here, comment if that's not what you want)
for row in rows:
    if 'Products///Item///ABC///XY' in row:
        index = row.index('Products///Item///ABC///XY')
        row[index] = 'Products///ABC///XYZ'
        continue # If we replaced the first thing, skip to next row
    elif 'Category: M[Item]' in row:
        index = row.index('Category: M[Item]')
        row[index] = 'Category: M[ABC]'

Comment: Further it sounds like @AFH either needs to remember what was found for the 'Products///.....' line and use it for later lines in the CSV or they may need to read all of the CSV, process it, and write out if they really need more complicated logic.
Comment: Let's wait for him to clear this up. Also, he might not need help on how to deal with data anyway, just how to parse files with newlines (that's how I understood him).
Comment: Thanks for all your help!

I was able to change the parameters as needed using csv module. I have only one hurdle now, I want '"' enclosing each row element but I am just getting row with delimiter without quotes. I tried

cw = csv.writer(open("File", "wb"), delimiter=';' , quotechar='"')
cw.writerow(row)

Where I am wrong?
Comment: Do you have any other problems with this? If not, consider accepting the answer, if it helped you:)

Text replacement on different lines


has_many association for only soft deleted records

Question: I want to do a has_many association for a model that has some records with deleted_at not nil and i want to be able to only retrieve those records via a has_many association but currently it is not working and i am not sure how to fix it.
class LoanApplication < ActiveRecord::Base
  acts_as_paranoid
  has_many :applicant_co_applicants, :class_name => "ApplicantCoApplicant", :foreign_key => "loan_application_id"
  has_many :co_applicant_infos, :through => :applicant_co_applicants, :source => :loan_application_co_applicant, :dependent => :destroy
  has_many :removed_co_applicant_infos, :through => :applicant_co_applicants, :source => :loan_application_co_applicant, :dependent => :destroy
end

class ApplicantCoApplicant < ActiveRecord::Base
  acts_as_paranoid
  attr_accessible :loan_application_id, :co_applicant_id, :deleted_at

  belongs_to :loan_application_co_applicant, class_name: 'LoanApplication', foreign_key: "co_applicant_id"
  belongs_to :loan_application, class_name: 'LoanApplication', foreign_key: "loan_application_id"
end

I tried to retrieve only the loan_application objects of soft_deleted records in the ApplicationCoApplicant table but my query still searched only for records with deleted_at: nil instead of deleted_at != nil
Is there any way i can only get the soft_deleted records from the ApplicantCoAppliant model and use that to filter the co_applicant_infos association?
Thanks much appreciated
**LoanApplication Table**
id     name    deleted_at
1   person a        nil
2   co person b     nil
3   co person c     nil

**ApplicantCoApplicant Table**
  id     loan_application_id     co_applicant_id   deleted_at
  1          1                       2               nil
  2          1                       3               2017-07-24 02:34:37

This is my sample Table. I want to a has_many associated whereby when i call
LoanApplication.find(1).removed_co_applicant_infos, it will return only the record of LoanApplication with id 3.
Comment: Can you show the query which you had tried with?
Answer: change LoanApplication model:
has_many :applicant_co_applicants, -> { not_deleted }

add this to ApplicantCoApplicant model:
scope :not_deleted, -> { where.not('deleted_at' => nil) }

Comment: this doesnt quite solve my issue but thanks for the assistance.
Comment: @KingsleySimon I made some minor changes. What results are you getting now?
Comment: What is the result now?
Comment: i had to switch it to has_many :applicant_co_applicants, -> { not_deleted }, :class_name => "ApplicantCoApplicant", :foreign_key => "loan_application_id". Your option returned errors and even after running it like this, it still returns empty


How Can I remove my account?

Question: How can I remove my account?
I found another more suitable forum for my questions and I would like to remove this one.
Comment: P.s. your question seemed to be on topic here, but we do expect a minimum amount of initial research when asking questions on this site. With a minimal amount of edits (as commented on) your question would be well-received.
Answer: It is a bit hidden away, but the help center provides the information you are looking for:
How do I delete my account?
Comment: It seemed to have been a helpful answer, given the state of the account :) +1

How Can I remove my account?


Can I set a pkl property value outside of an object declaration?

Question: Is there a syntax for doing this in pkl? The following fails:
class Foo {
    Bar: String
}

f = Foo {
    Bar = "Baz"
}

f.Bar = "Something else"

output {
    value = f
}

–– Pkl Error ––
Mismatched input: `.`. Expected one of: `{`, `=`, `:`

9 | f.Bar = "Something else"
     ^
at fail (file:///Users/ezbeard/Source/pkl/fail.pkl, line 9)

I also can't set a property value within a class method.
Answer:
Can I set a pkl property value outside of an object declaration?

All Pkl data is immutable. "Changing" something just yields new data. For objects, amend them into a new object to get a copy which "only differs in selected properties":
class Foo {
    Bar: String
    Num: Number
}

f: Foo = new {
    Bar = "Baz"
    Num = 42
}

g = (f) {
    Bar = "Something else"
}

output {
    value = g
}

Bar = "Something else"
Num = 42

I also can't set a property value within a class method.

You can set default properties directly within the class:
class Foo {
    Bar: String = "Something else"
}

f: Foo

output {
    value = f
}

Bar = "Something else"


A method that calls an array and returns a different array is giving a can't resolve B to a variable error

Question: I am calling one array and returning another array that is sorted based on the other array.
I think my method is proper but when I try to print out from the new array in the main method i'm getting an error that reads,
"Cannot resolve B to a variable."
B is the name of the new array that my method should return.
Thanks in advance.
package sort;

public class SortByFinal {

    public static int [][] sortByFinal(int n, int [][] A)
    {
        int [][]B = new int [n][3];

        int max = 0;

        for(int i =0; i<n; i++)
        {
            for(int j = i; j<n; j++)
            {
                max = Math.max(A[i][1], max);
            }

            for(int k = i; k<n; k++)
            {
                if(A[k][1] == max)
                {
                    B[k][0] = A[k][0];
                    B[k][1] = A[k][1];
                    B[k][2] = A[k][2];
                }
            }
        }

        return B;

    }

    public static void main(String []args)
    {
        int num = 5;

        int[][] now = new int [num][3];

        now[0][0] = 2342;

        now[0][1] = 88;

        now[0][2] = 98;

        now[1][0] = 3901;

        now[1][1] = 75;

        now[1][2] = 71;

        now[2][0] = 1444;

        now[2][1] = 60;

        now[2][2] = 85;

        now[3][0] = 5327;

        now[3][1] = 95;

        now[3][2] = 80;

        now[4][0] = 4888;

        now[4][1] = 83;

        now[4][2] = 100;

        //int [][] B = new int[num][3];

        sortByFinal(num, now);

        for(int i = 0; i<num; i++)
        {
            for(int j = 0; j<3; j++)
            {
                System.out.print(B[i][j]);//this gives me the "B cannot be resolved to a variable."
                System.out.print(" ");
            }
            System.out.println();
        }

    }

}

Answer: B is defined in sortByFinal(), but not in main().  To fix this, you could change your main to the follow:
int[][] B = sortByFinal(num, now);

Since sortByFinal(num, now) returns a int[][], this will work.
In your code, you're calling the function, but not doing anything with the return value, and you do not have access to the local variables of other methods; hence, the message.


C++ help with error : cannot convert parameter 1 from 'float' to 'float [][2]

Question: and I was doing a program, that isn't so important. Apparently, I cant send parameters to a float function.
the code look something like this
float myfunction(float array[1][2])
{
// ...
return 0;
}

int main()
{
float array[1][2];
int foo = 0;
// assigning values to the array

foo = myfunction(array[1][2]);
return 0;
}

when I try to compile, I get the error "cannot convert parameter 1 from 'float' to 'float [][2]"
What is wrong? And how can I solve it?
Answer: Just pass array, without the indexes:
foo = myfunction(array);

Answer: A couple of things.
First, a function prototyped float myfunction(float array[1][2]) is confusing (you), since what it actually mean is: float myfunction(float array[][2]) or float myfunction(float (*array)[2]). The function accepts a pointer to (one or more) array(s) of two floats.
Second, the error you get is because the function accepts a pointer to an array, while you're tryinmg to pass it single float - element [1][2] of the two-dimensional array float array[1][2]. Perhaps you meant to pass the entire array to the function?
Comment: Oh. I'm feeling kinda dumb right now, since I didn't figure that out myself, but thanks for the answer!
Answer: You've defined the variable: float array[1][2];
Then, you call the function in this way: foo = myfunction(array);
As a parameter, only you have to set the variable name. You shouldn't do this: foo = myfunction(array[1][2]);
When you make a function, do it in this way: type myfunction(float Array[][w]) , being type the type of function (void, float...) and "w" a constant integer.
Answer: You are passing a certain cell and not the array


How to create CheckStyle Check for validating Annotation Fields

Question: <code>@WebService(serviceName="TestImpl",
targetNamespace = "http://example.org"
)
public class TestImpl implements Test{
</code>
If my Test class is something like above my check should verify if the targetNamespace value always starts with "http://"
If no existing checks can do that how should my Custom check look like?
Answer: You can do this using Checkstyle out of the box by applying a RegexpMultiline check like this:
<code><module name="RegexpMultiline">
    <property name="format"
        value="(?s)@WebService\s*\(.*?targetNamespace\s*=\s*"(?!http:\/\/).{7}"/>
    <property name="message"
        value="Target namespace must start with "http://""/>
</module>
</code>
Here's an explanation of the regex.


Observe running time of a Java code in cmd prompt

Question: I have a java class file in my hand and can simply able to run it from windows cmd to view the output. Only thing I need to observe the running time of this java program depending on different input parameters. I don't have the source code so I can not modify it to generate the running time for me. Please suggest possible way out to observe this. Thanks in advance.
Comment: Can you post the code of the class you are trying to instrument?
Answer: Wrap it in another class and run that. For example if your class (to which you dont have code) is called Runner then you may be currently running it as
java -jar jarContainingRunner.jar Runner

If you create another class that then calls Runner you can do anything in that class. For example you could call the class InstrumentedRunner.
public class InstrumentedRunner {

   public static void main(String... arg) {
       long start = System.currentTimeMillis();
       new Runner().run();
       long dur = System.currentTimeMillis() - start;
       System.out.format("Runner took %s milliseconds", dur);
   }
}

(I haven't tested the code above.)
You could then run
java -jar jarContainingRunner.jar;jarContainingInstrumentedRunner.jar instrumentedRunner

It would then run Runner's run method (assuming that is the method you want to time) and output the time it took.
Comment: I've tried and found that through this way I can not able to get the actual running time of the MyClass.class as it has always gone in the background and keep running. While the MyClassRunner can only shows the running time of itself. Any other idea??
Comment: Hi, sorry for this late post. I've figured out the solution with the help of Windows Power Shell commands and here it is.

PS C:\> Measure-Command {java MyClass 1000 1234}

Days              : 0

Hours             : 0

Minutes           : 0

Seconds           : 0

Milliseconds      : 692

Ticks             : 6925010

TotalDays         : 8.01505787037037E-06

TotalHours        : 0.000192361388888889

TotalMinutes      : 0.0115416833333333

TotalSeconds      : 0.692501

TotalMilliseconds : 692.501

where 1000 is the input size and 1234 is a random number seed.
Answer: What you can do is you can write a batch file and there you can call your java class but before this save start time in variable and after class finish subtract it with start time.
Answer: You can write a simple Java program to observe this.
Use runtime executions within your new code and observe the execution time.
A sample overview of this new code:
//... before your class runs.
Runtime.getRuntime().exec("java -jar yourClass");
//... after your class runs.

Comment: I've tried and found that through this way I can not able to get the actual running time of the MyClass.class as it has always gone in the background and keep running. While the MyClassRunner can only shows the running time of itself. Any other idea??


When Should I Use connection.OpenAsync in Dapper?

Question: I am using "Using" Statement like this:
using (SqlConnection connection = new(ApplicationSettingsData.ConnectionString)
{
    // connection.Query();
}

As I Searched and understand about the connection of dapper, it has 2 workarounds. one is automatic open/close of the connection by dapper, and the other is fully control by me.
what I understand is, If I have only one query, I should just use dapper methods and done! (Like the Code above)
and if I have multiple queries and methods and works to do, I should Open connection myself and let it open until the last query I have, then close it (Like the Example Below).
Did I understand it correctly?
using (SqlConnection connection = new(ApplicationSettingsData.ConnectionString)
{
    await connection.OpenAsync();
    // QueryAsync<>...
    // Execute()...
    // QueryAsync<>...
    await connection.CloseAsync();
}

Answer: Yes you are correct.
Dapper will automatically open and close the connection if needed. But if you are doing multiple queries and want to keep the conenction open in between then open it explicitly.
Do note that because of connection pooling, the physical connection is not actually closed. It is returned to the pool, and if it is reused within a certain amount of time then it will just stay open and be reset on next usage. Because of this, you should not ever cache connection objects, as the connection pool handles the lifetime.
Closing explicitly is not needed as the using does that.
Comment: Yes correct, as long as you have a `using`.
Comment: so, If I use `using` I don't even need to close it? It will automatically close and dispose that object? just open if needed? Thanks for Your Answer
Answer: Async methods are used for asynchronous programming. In both examples, you have full control. And you should open the connection in the first example as well.
using (SqlConnection connection = new(ApplicationSettingsData.ConnectionString)
{
    connection.Open();
    // connection.Query();
}

Closing doesn't have to be done since the using statement will call connection.Dispose() and dispose will close the connection.


Arranging letters with two letters not next to each other

Question: just wanna know what's the answer to this one.
How many ways can the word "ARRANGED" be arranged so that N and D aren't next to each other?
Thanks. :)
Comment: Wouldn't you rather learn how to do problems like this, instead of just knowing the answer to this one problem?
Comment: Find in "How many ways can the word "ARRANGED" be arranged so that N and D are next to each other?"
Answer: Notice, in the given word $ARRANGED$ there are total $8$ letters out of which $A$ & $R$ are repetitive letters hence, we have
Total number of linear arrangements of $ARRANGED$ $$=\frac{8!}{2!2!}$$
Number of linear arrangements when $N$ & $D$ are kept together $$=\frac{7!}{2!2!}\cdot 2!=\frac{7!}{2!}$$
Hence, the number of linear arrangements when $N$ & $D$ are not kept together
$$=\text{(total number of linear arrangements)}-\text{(number of linear arrangements when N & D are kept together)}$$
$$=\frac{8!}{2!2!}-\frac{7!}{2!}=\frac{3\cdot 7!}{2!}=\color{red}{7560}$$
Answer: The total number of words is $\binom82\cdot\binom62\cdot\binom41\cdot\binom31\cdot\binom21\cdot\binom11=10080$.
The number of words with ND is $\binom72\cdot\binom52\cdot\binom31\cdot\binom21\cdot\binom11=1260$.
The number of words with DN is $\binom72\cdot\binom52\cdot\binom31\cdot\binom21\cdot\binom11=1260$.
Hence the number of words with no ND and no DN is $10080-1260-1260=7560$.


type '(dynamic) => Column?' is not a subtype of type '(dynamic) => Widget' of 'f'

Question: I have a Column where i want to show DataTable() with one DataColumn where i want to show key data of header inside DataColumn() and then i want to show key data of title inside DataCell() and then below that i want to show a ExpandablePanel() to show long_text_type as header and description as collapsed data. I don't want to show description inside DataTable() because its too long so i want to expand or collapse it with ExandablePanel(). After that i want to grab the next map from the list data and repeat the proces of showing a DataTable() and ExpandablePanel() from next map.
This is the list of maps i grab:
"data": [
            {
              "header": "FAQ",
              "long_text_type": "description",
              "title": "Service fees",
              "description": "Information about fees and surcharges."

            },
            {
              "header": "FAQ",
              "long_text_type": "description",
              "title": "Returns & Refunds",
              "description": "How to return products and recieve refunds.."

            }

          ]

this is the way i grab the json file:
import 'dart:convert';

import 'package:flutter/services.dart';

class TestData {
  Future<Map<String, dynamic>> getTestData() async {
    String jsonData =
        await rootBundle.loadString('assets/test_json/test_json1.json');
    Map<String, dynamic> data = jsonDecode(jsonData);
    return data;
  }
}

And this is the way which i want to use to show list:
list.map<Widget>((object) {
                    if (object.containsKey("header")) {
                      return Column(
                        children: [
                          DataTable(
                            horizontalMargin: 0,
                            columnSpacing: 75,
                            columns: <DataColumn>[
                              DataColumn(
                                label: Container(
                                  padding: EdgeInsets.zero,
                                  child: Text(
                                    object["header"].toString(),
                                  ),
                                ),
                              ),
                            ],
                            rows: <DataRow>[
                              DataRow(
                                cells: <DataCell>[
                                  DataCell(Text(
                                    object['title'].toString(),
                                  )),
                                ],
                              ),
                            ],
                          ),
                          ExpandablePanel(
                              theme: const ExpandableThemeData(
                                iconColor: Colors.white,
                                iconPlacement:
                                ExpandablePanelIconPlacement.right,
                              ),
                              header: Padding(
                                padding:
                                const EdgeInsets.fromLTRB(20, 10, 20, 0),
                                child: Text(
                                  object["long_text_type"].toString(),
                                ),
                              ),
                              collapsed: Container(),
                              expanded: Text(
                                object["description"].toString(),

                              ))
                        ],
                      );
                    } else {
                      return Container();
                    }
                  })

But i get the following error on .map<Widget>:
type '(dynamic) => Column?' is not a subtype of type '(dynamic) => Widget' of 'f'

How do i resolve this type error?
EDIT
I have edited the error because i forgot to add return Column but i still get an error
Edit
I have added the function which grabs the json
Answer: You have not returned the widget due to this error occurring.
Add return to your widget.
                  list[index]['data'].containsKey("header") ? Column(
                    children: [
                      DataTable(
                        horizontalMargin: 0,
                        columnSpacing: 75,
                        columns: <DataColumn>[
                          DataColumn(
                            label: Container(
                              padding: EdgeInsets.zero,
                              child: Text(
                                list[index]['data']["header"].toString(),

                              ),
                            ),
                          ),
                        ],
                        rows: <DataRow>[
                          DataRow(
                            cells: <DataCell>[
                              DataCell(Text(list[index]['data']['title'].toString(),
                            )),
                            ],
                          ),
                        ],
                      ),
                      ExpandablePanel(
                          theme: const ExpandableThemeData(
                            iconColor: Colors.white,
                            iconPlacement:
                                ExpandablePanelIconPlacement.right,
                          ),
                          header: Padding(
                            padding:
                                const EdgeInsets.fromLTRB(20, 10, 20, 0),
                            child: Text(
                              list[index]['data']["long_text_type"].toString(),

                            ),
                          ),
                          collapsed: Container(),
                          expanded: Text(
                            list[index]['data']["description"].toString(),
                            )
                    ],
                  );
                  :
                 return Container();

Comment: instead of `null` i get now  `Column?`
Comment: Then just remove the type Widget form .map
Comment: but then i get `type 'List' is not a subtype of type 'Widget'
`
Comment: And if remove `toList()` i get : `type 'MappedListIterable' is not a subtype of type 'Widget'
`
Comment: Can you please share your full function or widget where you are using this? because I need to know where you are returning this what is the actual type of parent widget.
Comment: I have edited the answer can you do it like this? can you please try ? @StudentOfFlutter
Comment: now i get error : `Class 'List' has no instance method 'containsKey'.
Receiver: Instance(length:2) of '_GrowableList'
Tried calling: containsKey("header")`
Comment: I have edited my question and added the full code
Comment: Then use it like `(list[index]['data'] as Map).containsKey("header")`
Comment: i did but i get the error `Class 'List' has no instance method 'containsKey'. Receiver: Instance(length:2) of '_GrowableList' Tried calling: containsKey("header")`
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244127/discussion-between-kishan-busa-and-studentofflutter).
Comment: Future> getTestData() async {
String jsonData =
await rootBundle.loadString('assets/test_json/test_json1.json');
  List  data = jsonDecode(jsonData)['data'];
return data;
}
Comment: I run your code in IDE, and it works without any warning or error. Check the runtime type of your list variable.
```List> list = [
    {
      "header": "FAQ",
      "long_text_type": "description",
      "title": "Service fees",
      "description": "Information about fees and surcharges."
    },
    {
      "header": "FAQ",
      "long_text_type": "description",
      "title": "Returns & Refunds",
      "description": "How to return products and recieve refunds.."
    }
  ];```
Comment: But i get error when i use the variable you posted `Error: A value of type 'Iterable' can't be assigned to a variable of type 'Widget'.` @SuatÖzkaya
Comment: I can not understand at where exactly you are having trouble. Are you sure you can decode your data into a list of Maps? ```List>``` This is the first thing you should ensure.
Comment: @SuatÖzkaya what is the code you used which worked?
Comment: Here it is -> I think you are having problem to decode data as a List of Maps. I just created a list of map and you code works. Only removed ExpandableWidget and added toList to the end...
  https://dartpad.dev/?id=e3091cc2c3013d888859b2814a2a5fae
Comment: @SuatÖzkaya the link shows only a flutter demo page
Comment: Try again please I've just linked the gist code now.


Is there a nice relationship between $\dot{B}^{-1}_{p,1}$ and $\dot{B}^{0}_{p,1}$?

Question: In particular, I'm hoping there is an embedding/inequality relating elements of the two.
For background, I have a particular function, $f \in W^{\infty,p}(\mathbb{R}^2)$, for all $p \in [1,\infty]$, which is a solution to a particular PDE. I am currently investigating the decay properties fo rthis function, and have reached a point where I have the two norms:
$||f||_{\dot{B}^{-1}_{p,1}}$ and $||\nabla f||_{\dot{B}^{-1}_{p,1}}$
All I wish to do is show that these two norms are finite. As I am very new to Besov spaces, I am not sure how I can do this.
I have been given a hint that the norm should be finite for $p>2$, but I have no idea why this might be the case.
I am aware of the following embedding:
$ \dot{B}^{0}_{p,1} \subseteq L^p \subseteq \dot{B}^{0}_{p,\infty}  $
But I am completely unaware of what we can say for Besov spaces of the form $\dot{B}^{s}_{p,\infty}$ where $s < 0$.
The $\dot{B}^{s}_{p,q}$-norm is defined as follows:
$ ||f||_{\dot{B}^{s}_{p,q}} =  || \{ 2^{sj}||\phi_j \ast f||_{L^p(\mathbb{R}^2)} \} ||_{\mathcal{l}^q}$, where $\phi_j$ are defined as the inverse FT of terms from the Littlewood-Paley decomposition. That is:
$ \hat{\phi_j}(\xi) := \hat{\phi_0}(2^{-j}\xi)$,  $\ \ \text{Supp}(\hat{\phi_j}) \subseteq \{ \xi\in \mathbb{R}^2 \ | \ |2^{j-1}| \leq |\xi| \leq |2^{j+1}| \}$, $\ \ \Sigma_{j \in \mathbb{Z}} \hat{\phi_j}(\xi) = 1$, for all $\xi \neq 0.$
Thank you.
Comment: I always found these things easy to answer when I looked at the Littlewood-Paley formulas for these norms.
Comment: Note $\nabla f \in \dot B^{-1}_{p,1}$ is the same as $f \in \dot B^{0}_{p,1}$.
Comment: Thank you very much. That is indeed what I've been using to understand homogeneous Besov spaces. Unfortunately I just can't seem to work out a norm inequality that would give me anything like $W^{\infty,p} \subseteq \dot{B}^{-1}_{p,1} $. Are you aware of such an inequality?
Comment: If you can remind me what the Littlewood-Paley definitions are, I'm sure I could come up with something.  Also, $W^{\infty,p}$, is that infinitely many derivatives in $L^p$, or $p$ derivatives in $L^\infty$?
Comment: Infinitely many derivatives are $L^p$
Comment: I have added the def of homogeneous Besov norm, using Littlewood-Paley decomp
Comment: OK, I made an attempt at answering your question.  But I am a little confused as to what exactly the question is.  In the form you wrote in your last comment, I think it is false.
Comment: And being in $W^{\infty,p}$ just doesn't give you enough control over the low frequencies to be in $\dot B^0_{p,1}$.
Answer: Being in $W^{p,\infty}$, I assume this means having all derivatives in $L^p$, that is, for all $n \ge 0$ we have
$$ \left\|\left(\sum_{k=-\infty}^\infty |2^{kn} \Delta_k f|^2\right)^{1/2} \right\|_p < \infty ,$$
where $\hat \Delta_k f(\xi) = \varphi(2^{-k} \xi) \hat f(\xi)$, where $\varphi$ is a smooth function compactly supported in $\{\xi: \frac14  < |\xi| < 4\}$ satisfying $\sum_{k=-\infty}^\infty \varphi(2^k \xi) = 1_{\xi \ne 0}$.
Also
$$ {\|f\|}_{\dot{B}^{-1}_{p,1}} := \sum_{k=-\infty}^\infty 2^{-k} {\|\Delta_k f\|}_p .$$
This is how you do these kinds of arguments.
Let's first consider $1 \le p \le 2$.
Split it into two halves, and suppose $\epsilon>0$:
\begin{align} \sum_{k=0}^\infty 2^{-k} {\|\Delta_kf\|}_p
&\le
\left(\sum_{k=0}^\infty 2^{-\epsilon p/(p-1)}\right)^{(p-1)/p} \left(\sum_{k=0}^\infty 2^{-kp(1-\epsilon)} {\|\Delta_kf\|}_p^p \right)^{1/p}
\\ &\le C_1 \left\| \left(\sum_{k=0}^\infty 2^{-kp(1-\epsilon)} |\Delta_kf|^p \right)^{1/p} \right\|_p
\\ &\le C_1 \left(\sum_{k=0}^\infty 2^{-\epsilon 2p(2-p)}\right)^{(2-p)/(2p)} \left\| \left(\sum_{k=0}^\infty 2^{-2k(1-2\epsilon)} |\Delta_kf|^2 \right)^{1/2} \right\|_p
\\ &\le C_2 \left\| \left(\sum_{k=0}^\infty 2^{-2k(1-2\epsilon)} |\Delta_kf|^2 \right)^{1/2} \right\|_p
\\ &\le C_2 {\|f\|}_{W^{-1+2\epsilon, p}},
\end{align}
Do a similar thing for the other half, which will be bounded by a constant times ${\|f\|}_{W^{-1-2\epsilon, p}}$.
And a similar, but slightly simpler, argument works for $2 \le p < \infty$.
However, for the other half (the low frequencies), you don't get exactly what you need.  Because
$$ {\|f\|}_{\dot B^{-1}_{p,1}} \ge 2^{-k} {\|\Delta_k f\|}_p ,$$
and for $-k$ large, we simply don't have any kind of estimate coming from the Sobolev norm.
Answer: I think one of your questions is whether $W^{\infty,p} \subset \dot B^0_{p,2}$.  This would imply:
\begin{align}
\sum_{k=-\infty}^{-1} {\| \Delta_kf \|}_p
&\le C \left\| \left(\sum_{k=-\infty}^{-1} |\Delta_kf|^2 \right)^{1/2}\right\|_p
&(*)
\end{align}
This is definitely not the case if $p = 2$, because this would imply that $\ell^2 \subset \ell^1$.  Considering the case
$$ f(x) = \sum_{k=-\infty}^{-1} a_k 2^{-dk}\varphi(2^k x) , \quad x \in \mathbb R^d,$$
for suitable $a_k$ should work to show this is not true for any other $1<p<\infty$ either, because the left hand side of (*) will be approximately the $\ell^1$ norm of $(a_k)$, and the right hand side will be approximately the $\ell^p$ norm of $(a_k)$.