text:
Q: Radius of converge of $\sum_{n = 0}^{\infty}\frac{n}{n^{2}\sqrt{n} + 1}x^{n}$ I am supposed to find where the power series:
$$\sum_{n = 0}^{\infty}\frac{n}{n^{2}\sqrt{n} + 1}x^{n}$$ converge absolutely, converge conditionally and where it diverges. My book only shows how to find the radius of convergence by using the ratio test. So I tried it:
$$\lim_{n \to \infty}\left|\frac{a_{n + 1}}{a_n}\right| = \lim_{n \to \infty}\left|\frac{(n + 1)(n^{2}\sqrt{n} + 1)}{n((n + 1)^{\frac{5}{2}} + 1)}\right|$$
But I am stuck here, even expanding this more out, I don't know how to find this limit (although I know it is $1$, right?).
Another hint that I got for solving this problem was to use the result I found in the previous task, where I found that $\sum_{n = 0}^{\infty}\frac{n}{n^{2}\sqrt{n} + 1}$ diverges by using the comparison test: $\frac{n}{n^{2}\sqrt{n} + 1} < \frac{1}{n^{3 / 2}}$.
So, how can I find this radius of convergence? How can I use the result that I found?

A: The limit$$\lim_{n\to\infty}\frac{(n + 1)(n^{2}\sqrt{n} + 1)}{n((n + 1)^{\frac{5}{2}} + 1)}$$is equal to $1$, because it is basically the limit of $\frac{n^{7/2}}{n^{7/2}}$. Therefore, the radius of convergence is $1$.


text:
Q: OTP [firebase_auth/unknown] null I searched for days but couldn't find why am I getting this error.
E/FirebaseAuth(21984): [SmsRetrieverHelper] SMS verification code request failed: unknown status code: 17499 Error code:39
I/flutter (21984): [firebase_auth/unknown] null

i receive this exception when i use my country phone number(Sudan) but when i add another country phone number they receive the SMS verification code.
1.i enabled the Phone Sign-in method in my firebase console.
2.added SHA1 and SHA256 of google play console,signingReport and even key store in my firebase console and uploaded the new google services.json .
3.enabled the Android DeviceCheck API for my project in google cloud console.
4.enabled play integrity in app check.
any help!
thank you in advance.

A: It seems that there is no way around it, due to the sanctions exposed in Sudan firebase or in fact all google services will not work unless you use a VPN.
Try with sinch or twilio

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting truncation mode for UINavigation title text I want to configure the truncation mode for the text that appears in UINavigationItem.
I've come across a couple of different solutions of configuring the font size but not sure how to make use of the UILineBreakModeHeadTruncation that exists on NSString.
How I've been able to configure the font size:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
[label setFont:[UIFont boldSystemFontOfSize:16.0]];
[label setBackgroundColor:[UIColor clearColor]];
[label setTextColor:[UIColor whiteColor]];
[label setText:self.title];
[self.navigationController.navigationBar.topItem setTitleView:label];
[label release];

(Based on the recommendation from here)
If I call this in loadView or viewDidLoad, it seems to work but outside of that method, after the view has been loaded, it doesn't seem to work. Not sure why though.

A: What have you tried, and what's not working? You should be able to do:
label.lineBreakMode = UILineBreakModeHeadTruncation;

Or to wrap to multiple lines:
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0;


text:
Q: Number of Fibonacci numbers in a range The definition of the Fibonacci numbers is given by:
$$\begin{align}f_1 &= 1;\\ f_2 &= 2;\\
f_n &= f_{n-1} + f_{n-2},\qquad (n >= 3);
\end{align}$$
now we are given two numbers $a$ and $b$, and we have to calculate how many Fibonacci numbers are in the range $[a,b]$. How can we calculate it?

A: We know that $F_n\approx \frac {\phi^n}{\sqrt 5}$, so given $a$, the next larger Fibonacci number is $F_k$, where $k= \left \lceil\frac {\log (a\sqrt 5)}{\log \phi }\right \rceil$.  Similarly the $F_m$ below $b$ is  $m= \left \lfloor\frac {\log (b\sqrt 5)}{\log \phi }\right \rfloor$, then there are $m-k+1$ between $a$ and $b$.  You have to think about what you want if $a$ or $b$ are themselves Fibonacci numbers.

A: This question is asked in Skiena's programming challenges. Now, to find the $ n^{\text{th}} $ fibonacci number, we have the following closed form expression.
$$ \Large F(n) = \dfrac{1}{\sqrt{5}} \left( \left( \dfrac{1 + \sqrt{5}}{2}\right)^n - \left( \dfrac{1 - \sqrt{5}}{2} \right)^n\right) $$
Now, given $ F(n) $, we can find approximately the index of the closest fibonacci number to it. Therefore, we find one $ n_1 $ such that $ F(n_1) = a $ and another $n_2 $ such that $ F(n_2) = b $. Then our answer is $\mathsf{round(n_2)} - \mathsf{round(n_1)}$ where $ \mathsf{round(x)} $ find the nearest integer to $ x $.


text:
Q: Custom Bindings in MvvmCross Crosslight We're implementing our own cross platform framework using the binding capabilities of MvvmCross Core.
My question is how can custom bindings be registered within Mvx without the setup.
Custom binding used is an imeActionBinding similar to:
https://gist.github.com/slodge/8270923
attempted registration using:
Mvx.CallbackWhenRegistered<IMvxTargetBindingFactoryRegistry>(RegisterCustomBindings);

protected virtual void RegisterCustomBindings(IMvxTargetBindingFactoryRegistry registry)
    {
        EditTextImeActionBinding.Register(registry);
    }

Tried the same thing with project ChimpLight in the LightSetup:
  Mvx.RegisterSingleton<IMvxTargetBindingFactoryRegistry>(new MvxTargetBindingFactoryRegistry());
  var customBindingRegistry = Mvx.Resolve<IMvxTargetBindingFactoryRegistry>();
  EditTextImeActionBinding.Register(customBindingRegistry);

xaml:
 <EditText
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:hint="Search"
  android:inputType="text"
  android:imeOptions="actionSearch"
  local:MvxBind="Text LastName;ImeAction ResetCommand" />

no exceptions - but it seems the custom binding never gets loaded :|
what am I missing?

A: Thanks to Stuart for the simple answer: use the existing binding.
Using the N-30 Chimplight example code, the only added code to LightSetup class is:
        Mvx.CallbackWhenRegistered<IMvxTargetBindingFactoryRegistry>(registry =>
        {
            EditTextImeActionBinding.Register(registry);
        });


text:
Q: Drag and drop images on canvas I have drag and drop the images on canvas. I have fix the boundaries so that my images not drag out of canvas,but when I zoom-in and zoom-out the images then its boundaries changes,and it would not drag over whole canvas.I have try this till now.
         public void Btnedit_Click(object sender, RoutedEventArgs e)
         {
        var button = sender as Button;
        button.IsEnabled = false;
        CompositeTransform CT = new CompositeTransform();
        ImgeracOpen.ManipulationMode = ManipulationModes.All;
        //ImgeracOpen.ManipulationDelta += Drag_ManipulationDelta;
        ImgeracOpen.ManipulationDelta += Composite_ManipulationDelta;
        ImgeracOpen.RenderTransform = CT;
    }

   void Composite_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
    {
        // scale the image

        FrameworkElement Elem = sender as FrameworkElement;
        CompositeTransform CT = Elem.RenderTransform as CompositeTransform;
        if (CT != null)
        {
            CT.ScaleX *= e.Delta.Scale;
            CT.ScaleY *= e.Delta.Scale;
            CT.CenterX = Elem.ActualWidth / 2;
            CT.CenterY = Elem.ActualHeight / 2;
            if (CT.ScaleX < 0.25) CT.ScaleX = 0.25;
            if (CT.ScaleY < 0.25) CT.ScaleY = 0.25;
            if (CT.ScaleX > 1.15) CT.ScaleX = 1.15;
            if (CT.ScaleY > 1.15) CT.ScaleY = 1.15;

        }

        double Left = Canvas.GetLeft(Elem);
        double Top = Canvas.GetTop(Elem);
        Left += e.Delta.Translation.X;//Get x cordinate
        Top += e.Delta.Translation.Y;//Get y cordinate
        //check for bounds
        if (Left < 0)
        {
            Left = 0;
        }
        else if (Left > (my_canvas.ActualWidth - Elem.ActualWidth))
        {
            Left = my_canvas.ActualWidth - Elem.ActualWidth;
        }

        if (Top < 0)
        {
            Top = 0;
        }
        else if (Top > (my_canvas.ActualHeight - Elem.ActualHeight))
        {
            Top = my_canvas.ActualHeight - Elem.ActualHeight;
        }

        Canvas.SetLeft(Elem, Left);
        Canvas.SetTop(Elem, Top);

thanks in advance

A:
when I zoom-in and zoom-out the images then its boundaries changes,and it would not drag over whole canvas.

It's because when you scale the Image, the Image's ActualWidth and ActualHeight won't change and so is Left and Top that you get from Canvas.GetLeft and Canvas.GetTop.
To fix the problem, you need to calucate the Left and Top values when the image scales like below:

As you can see in the picture. When image scales, the Left Value should be Canvas.Width-Image.ActualWidth-xOffset when image hit the right boundary. And when it hit the left boundary Left should be equal to xOffset.
Through this logic, the codes in Composite_ManipulationDelta should be modified like below:
void Composite_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
    // scale the image
    FrameworkElement Elem = sender as FrameworkElement;
    CompositeTransform CT = Elem.RenderTransform as CompositeTransform;
    if (CT != null)
    {
        CT.ScaleX *= e.Delta.Scale;
        CT.ScaleY *= e.Delta.Scale;
        CT.CenterX = Elem.ActualWidth / 2;
        CT.CenterY = Elem.ActualHeight / 2;
        //if (CT.ScaleX < 0.25) CT.ScaleX = 0.25;
        //if (CT.ScaleY < 0.25) CT.ScaleY = 0.25;
        //if (CT.ScaleX > 1.15) CT.ScaleX = 1.15;
        //if (CT.ScaleY > 1.15) CT.ScaleY = 1.15;
    }
    double Left = Canvas.GetLeft(Elem);
    double Top = Canvas.GetTop(Elem);

    //output.Text = "Left:=" + Left + "  Top:=" + Top+"\nActualWidth:="+Elem.Width+"  ActualHeight"+Elem.Height;
    Left += e.Delta.Translation.X;//Get x cordinate
    Top += e.Delta.Translation.Y;//Get y cordinate
                                     //check for bounds
    double xOffset = Elem.ActualWidth * (CT.ScaleX-1) / 2;
    double yOffset = Elem.ActualHeight * (CT.ScaleY-1) / 2;
    if (Left-xOffset < 0)
    {
        Left = xOffset;
    }
    else if (Left > (my_canvas.ActualWidth - Elem.ActualWidth-xOffset))
    {
        Left = my_canvas.ActualWidth - Elem.ActualWidth-xOffset;
    }

    if (Top -yOffset<0 )
    {
        Top = yOffset;
    }
    else if (Top > (my_canvas.ActualHeight - Elem.ActualHeight-yOffset))
    {
        Top = my_canvas.ActualHeight - Elem.ActualHeight-yOffset;
    }

    Canvas.SetLeft(Elem, Left);
    Canvas.SetTop(Elem, Top);
}


text:
Q: How do I earn the Pacifist Achievement? There have been some extended discussions on what will or will not break your eligibility for the Pacifist achievement, but nothing conclusive as to what actually is taken into account.
What actions (either directly or indirectly) result in an ineligibility to earn the pacifist achievement?
Additionally, is there any way to check one's save game to see if they are still eligible for the achievement?

A: An unofficial, but popular Deus Ex wiki says the following:

"The aim is to complete the game without killing anyone directly, or someone dying as a result of an action taken by the player. The only exception to this is the Boss fights...killing anyone in the Prologue chapter will lock out this achievement

And currently, it appears there is no way to see if you are still eligible for the achievement at any time:

"Unfortunately if you lock out the achievement by accident, unless you aware that you did so and reload an old save, there is no indication that you have done so and may end up playing through the game and not get the achievement due killing a character earlier in the game."

This seems to be a fairly sought after feature though. Since the game has been so popular since its release (over two million units sold already), I would not be surprised if a patch is released soon resolving these complaints.

A: Actions which disqualify you for the Pacifist achievement:

*

*Killing a non-boss character directly (shooting them, lethal take down)

*Killing someone through a hacked turret or robot

*Killing anyone in the opening sequence of the game

Actions which will not disqualify you for the Pacifist achievement:

*

*Using an EMP on a robot

*Neutralizing an enemy through non-lethal means (stun gun, non-lethal take down, et cetear)

 It should also be pointed out that it is possible to defeat the final boss through non-lethal means, so using lethal means could also result in losing the Pacifist achievement. This answer covers how to do that.


text:
Q: T4 Template Could not load file or assembly 'System.Runtime, Version = 4.2.0.0' So I have a T4 Template I'm trying to run at design-time, but it keeps giving me the following error.
Running transformation: System.IO.FileNotFoundException: Could not load
file or assembly 'System.Runtime, Version=4.2.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system
cannot find the file specified.
File name: 'System.Runtime, Version=4.2.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'

My Visual Studios solution has 10 projects contained within it, all of which target .Net Core 2.0 framework. My T4 template presently looks as such:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="Services.Resources.DataTransferObjects.Infrastructures" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ assembly name="$(TargetDir)Services.dll" #>

<#@ output extension=".cs" #>
public class AdminDTO
{
        <#var editableObjs = Assembly
            .GetAssembly(typeof(GenericEditable<>))
            .GetTypes()
            .Where(p => p.BaseType != null && p.BaseType.IsGenericType && p.BaseType.GetGenericTypeDefinition() == (typeof(GenericEditable<>)))
            .ToList();
        #>
}

At the moment I only need the assembly I've referenced in the template, which is a .Net Core 2.0 class library project. I've tried adding the System.Runtime.dll reference in this particular library, but it doesn't appear to make any difference.
I've read several other issues similar to this, and it generally seems that .Net Core seems to have issues with T4 Templates, but it appeared most peoples' solutions were to target a .Net Standard library. I'm not sure this is applicable for me, as my entire solution only involves .Net Core projects.
EDIT
I changed all my projects to target .Net Standard 2.0 instead of .Net Core, and that fixed my initial problem, but now I see this error:
System.Reflection.ReflectionTypeLoadException: Unable to load one or
more of the requested types. Retrieve the LoaderExceptions property for
more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()

A: I found a workaround for the System.Runtime dll error.
Put this bindingRedirect inside the C:\Users\<user>\AppData\Local\Microsoft\VisualStudio\15.0_29f8d23a\devenv.exe.config inside <configuration> -> <runtime> -> <assemblyBinding> where are all the others bindingRedirect's
<dependentAssembly>
  <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
  <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0"/>
</dependentAssembly>

It's a bug in Visual Studio or T4 Template Engine: https://developercommunity.visualstudio.com/content/problem/358905/filenotfoundexception-systemruntime-version4210-wh.html


text:
Q: Adding a featured image to a foreach Wordpress loop I just found a clever piece of code on line which allows Wordpress posts to be displayed in side by side columns and works great with the title and post excerpt that I want to display.
However I would like also to display a specific featured image that I defined in the functions file in each post. Here is the code that works fine apart from a lack of output for the featured image. I'm guessing my syntax is incorrect at that point.
                <?php
                    // Custom loop that adds a clearing class to the first item in each row
                    $args = array('numberposts' => -1, 'order' => 'ASC', 'post_type' => 'treatments' ); //For this example I am setting the arguments to return all posts in reverse chronological order. Odds are this will be a different query for your project
                    $allposts = get_posts($args);
                    $numCol = 2; // Set number of columns

                    // Start Counter
                    $counter = 0;
                    foreach ($allposts as $post) {
                        $content = '
'; // Add class to the columns depending on if it is odd or even
                        $content .= '
';
                        $content .= '
';
                        $content .= 'the_post_thumbnail->small).'" />';
                        $content .= '
';
                        $content .= '
'.$post->post_title.'
';
                        $content .= $post->post_excerpt;
                        $content .= '
';
                        $content .= '
';
                        echo $content;
                        $counter ++;
                    }
                ?>

I'd like a fallback image if the user hasnt specified a featured image too. I'd guess an if else statement similar to the short hand used to add a class to the columns would be appropriate? Here is the featured image code that is in the functions file.
<?php
// add featured image
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 120, 120, true );
add_image_size( 'small', 120, 120, true );
add_image_size( 'medium', 330, 330, true );
add_image_size( 'front_page', 460, 350, true);
add_image_size( 'header', 660, 200, true);
add_image_size( 'large', 600, 390, true );
?>

A: This is the syntax problem:
$content .= 'the_post_thumbnail->small).'" />';

The the_post_thumbnail() function is not part of the $post object, and would print, rather than return, the post thumbnail, even if that method would work.
Try using get_the_post_thumbnail() instead:
$thumbnail = get_the_post_thumbnail( $post->ID, 'small' );

Note that this function returns the fully formed  tag markup, so you would need to adapt your code accordingly:
$content .= get_the_post_thumbnail( $post->ID, 'small' );

Edit
Note that 'small' is an image size already defined by WordPress, so you'll want to use a different name. I would use something location-descriptive, such as 'post-two-column':
add_image_size( 'post-two-column', 120, 120, true );

Then, reference accordingly in your loop:
$content .= get_the_post_thumbnail( $post->ID, 'post-two-column' );


text:
Q: How do I view joins in my raw sql in django? I have a model that stores raw sql in one of its fields like:
class MyModel(models.Model):
    raw_sql = models.TextField(blank=True)
    # other fields

Now I want to see that on tables is the join being applied. I am doing this to prevent unnecessary joins while executing these queries. Is there any way, I can see the models from the raw_sql?


text:
Q: Start X11 server on CentOS 7 without screen but with a graphics card I'd like to do OpenGL rendering from an application that talks to an X11 server. The application reads the value of the DISPLAY variable.
I have access to a CentOS 7 box that has a nice graphics card capable of doing 3D rendering, but I don't have a monitor plugged into it.
When I run xstart, to start the X11 server, I get the following error:
Fatal server error:
(EE) no screens found(EE)

How do I start an X11 server for rendering on a graphics card, without a physical display?
This box sits in a server room, so I can't plug a physical display into it.
Also, xvfb or software renderers are perhaps not useful for this task, because it does not handle instructions needed for rendering. I would need to use the graphics adapter.
Here are the graphics adapters available to me:
# lspci | egrep 'VGA|3D'
04:00.0 VGA compatible controller: NVIDIA Corporation GP104 [GeForce GTX 1080] (rev a1)
0a:00.0 VGA compatible controller: Matrox Electronics Systems Ltd. G200eR2 (rev 01)

Here is my xorg.conf file:
# more /etc/X11/xorg.conf
# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig:  version 375.20  (buildmeister@swio-display-x86-rhel47-06)  Tue Nov 15 17:49:44 PST 2016

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
EndSection

Section "Files"
    FontPath        "/usr/share/fonts/default/Type1"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/input/mice"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Unknown"
    HorizSync       28.0 - 33.0
    VertRefresh     43.0 - 72.0
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

I can post transcripts of any other useful logs. Thanks for any advice!

A: I've run into this problem before.  Unfortunately, the best answer I've been able to come up with is a hardware solution: trick the graphics card into thinking a monitor is installed by plugging a VGA terminator into the VGA output.  You can make one at home or buy one; googling for "VGA terminator" returns plenty of results for both.
Another option may be to run a VNC server on the headless system, but I'm not sure whether the graphics card can render to a VNC output.


text:
Q: Making a Message Appear if the Results of a Query Are Zero I have a variable called $uid, and I would like to print a message if the variable $uid is not contained in the "loginid" field of a MySQL table "tweets" on any row that has another variable, $submissionid.  I think my query $tweetquery is okay.  Basically, I would like the message to echo if the loginid variables pulled from "tweets" never equal $uid.
How can I do this?
Thanks in advance,
John
$tweetquery = "SELECT loginid
               FROM tweets
              WHERE submissionid = '$submissionid'";

   $tweetresult = mysql_query($tweetquery);

   if...

echo '
Message
';

A: Have a look at mysql_num_rows($result).
if ( mysql_num_rows($result) > 0 )
{
  // Do something
}
else
{
  echo 'No results';
}

A: Call me crazy, but using mysql_num_rows is not the way I'd do this. mysql_fetch_array does not do anything destructive if nothing is returned, so call that as normal.
$row = mysql_fetch_array( $resource );
if(!$row)
{
    //do what you would do if the query returned nothing
}
else
{
   do
   {
      // do what you would do with the row
   } while( $row = mysql_fetch_array( $resource ) );
}

The problem with mysql_num_rows is that it actually represents a call to the database asking for how many rows exist in the pointer. It is a, frankly, needless back-and-forth which can easily be avoided. So why not avoid it?

A: You can use mysql_num_rows:
if (mysql_num_rows($tweetresult) > 0)
     // results found

A: Use mysql_num_rows():
if (mysql_num_rows($tweetresult) == 0) {
    echo 'Message';
}

A: mysql_num_rows() returns the numbers of rows fetched from the database. If rows fetched are zero echo a message.
$tweetquery = "SELECT loginid
           FROM tweets
          WHERE submissionid = '$submissionid'";

$tweetresult = mysql_query($tweetquery);

if(mysql_num_rows($tweetresult) > 0){
    // your results here
} else {

    echo '
Message
';
}

A: if(mysql_num_rows($tweetresult) == 0)
    echo "
Message
";
else {
    //Do something if $uid was found
}


text:
Q: How to disable the buffer of windows ConPTY? Using ConPTY to spawn a python3 process.
The python process read one line and output the line length.
It should output 3001. But output 511 in cmd, output 2510 in MSYS2.
It looks like there is a line buffer limit in ConPTY. How to disable it?
package main

import (
    "bufio"
    "context"
    "fmt"
    "strings"

    "github.com/UserExistsError/conpty"
)

func main() {
    cpty, err := conpty.Start("python3 -c \"import sys; s = sys.stdin.readline(); print(len(s))\"")
    if err != nil {
        fmt.Printf("Failed to spawn a pty:  %v", err)
        return
    }
    defer cpty.Close()

    go func() {
        cpty.Write([]byte(strings.Repeat("A", 3000) + "\r\n"))

        scanner := bufio.NewScanner(cpty)
        for scanner.Scan() {
            // Should output 3001.
            // But output 511 in cmd, output 2510 in MSYS2.
            fmt.Printf("Output: %s\n", scanner.Text())
        }
        if err := scanner.Err(); err != nil {
            fmt.Println(err)
        }
    }()

    if _, err := cpty.Wait(context.Background()); err != nil {
        fmt.Printf("Error: %v", err)
    }
}


text:
Q: "Frame Rectangle" vs. "Layout Rectangle" in Xcode What's the difference of the two?
I haven't found any difference in my projects when using either one, but it's bothering me that I don't know what either is for.
Please advise!

A: The layout rectangle is the apparent visual size of the control. It is different from the actual frame, since there might be drop shadows or inset effects that are outside of the visually distinct portion of the control.
What's the difference between frame and layout in Interface builder's size inspector?


text:
Q: SharePoint equivalent of Application_Start in Global.asax Is there a SharePoint equivalent of the Application_Start method in a class that derives from HttpApplication, such as the default Global class that is created when you add a Global.asax to an ASP.NET project?
I want to run some code when the SharePoint Web Application starts. Or is there a different preferred way of doing this in SharePoint?
In this particular case, I would like to run some code that does some expensive calculations and caches them. So this code would run on all front-end servers in the farm.

A: Do you want the results in memory? or do you want to store them somewhere afterwards?
wouldnt mess with the Global handler approach as this is pretty complex to get right & is really hooking into the stack at the wrong level.
You want to hook in at the SharePoint Service App level by the sounds of it.  This way you dont have to muck about with setup on new servers you add to the Farm etc... and its all managed through the same tools as the rest of the farm services.

A: I would suggest you move your code into a Timer Job that executes at regular intervals, in the background. Running stuff when the application starts will only slow down it further (we all know that SharePoint is a bit tired in the morning). Timer Jobs can be set to execute at specific intervals or times and can be run on specific or all servers.
Check out AC's post on the topic: http://www.andrewconnell.com/blog/archive/2007/01/10/5704.aspx
(it's for MOSS 2007 but it's basically the same for 2010)

A: This will depend on what you want to achieve. One way would be to hook up a custom module.
Example http://www.sharepoint4arabs.com/AymanElHattab/Lists/Posts/Post.aspx?List=0b2c413e%2De6fb%2D4c60%2Da12f%2D9ae9bdbd48c8&ID=62


text:
Q: Why electric field and magnetic field are in phase in electromagnetic waves? I can understand in mathematics but could you please explain it's physical significance (such as from the energy perspective)?

A: First of all I should say that I am a bit wary of separating arguments as "mathematical" and "physical". Physics ${\it is}$ all about applying math to the actual world. Often when asking for a "physical" argument, people is fact ask for an analogy with something they already know.
That being being said, let me add my 50 cents to the discussion above. First of all, having energy density becoming zero at some points in space does not mean the energy is not conserved. In one comment you are asking "...where the energy goes when E and B comes zero?". The answer is that it flows away. Remember that energy is only conserved ${\it globally}$. Locally the energy density $\rho_E$ is just subject to the continuity equation
$$\frac{\partial \rho_E}{\partial t}+div \left(j_E \right)=0$$
So no paradox here.
Also, as pointed out several times above, there is nothing special or important in the fact that energy density is modulated in space. The most trivial example is the circularly polarized EM wave. The the magnitude of both E and B are always constant and the energy density is uniform throughout the space. You can think of the spatial and temporal distribution of field and energy in a linearly polarized EM wave as just a funny effect of interference between right- and left-hand polarized waves.

A: Not always true. For example, inside metals electric and magnetic field of the EM wave are out of phase: magnetic field lags behind.
In other cases is quite easy to understand. Changing magnetic field $(\frac{\partial B}{\partial t})$ creates a changing electric field and vice versa (Look at the two Maxwell equations involving curl of E and curl of B) .
Let's consider the electric field part of light: It has the form: $E=E_0 cos(kx-\omega t)$, we need to look at the change as time passes so let's just look at some particular value of x and see how $E$ changes at that point. For simplicity let's say the point we choose is $x=0$. Now the field at $x=0$ is $E_{x=0}=E_0 cos\omega t$. It's derivative w.r.t time will be zero when cosine is maximum(+1) or minimum(-1), at all these points in time $E$ is constant. $\therefore$ the corresponding $B$ should also be a constant in time at these same instants. i.e, the peaks and valleys of $E$ and $B$ should coincide in time. This should be true not only for $x=0$, but for every $x$.

A: The statement often used for electromagnetic waves "changing magnetic fields create changing electric fields" is to say the least misleading as far as electromagnetic radiation goes.

Electromagnetic waves can be imagined as a self-propagating transverse oscillating wave of electric and magnetic fields. This 3D animation shows a plane linearly polarized wave propagating from left to right. The electric and magnetic fields in such a wave are in-phase with each other, reaching minima and maxima together.

Images of the mathematics as above go against our conservation of energy instincts.
It is important to remember that the Maxwell theory which results in the above model for electromagnetic radiation, defines energy with the Poynting vector.

The rate of energy transport per unit area is described by the vector

$E_m$ is  the maximum of the plane wave,  in the above  case.
So in the mathematics of Maxwell's solution the energy is carried by the averages of the given mathematical form.
I keep insisting on "mathematics" because the figures as shown cannot be measured, they are fits to measured data in optics but itself.
The behavior of energy of a light beam becomes clear when the photon content of the beam is considered, where each photon carries energy $hν$ and our intuition of conservation of energy can be fulfilled.
See this classroom experiment to get a feeling of how photons build up the classical electromagnetic wave.

A: . . . . . but could you please explain it's physical significance (such as from the energy perspective)?
In the mathematical derivation to show that the electric field and the magnetic field for plane waves are in phase a number of assumptions are made.
One of them is that the medium is non-dispersive with no loss of energy due to absorption ie the refractive index of the medium is real.
In a dispersive absorbing medium, the refractive index n is complex and so when the wave passes through such a medium the phase between the electric and magnetic field is no longer zero.
The loss of energy from the wave as it passes through a medium is coupled with a phase shift between the electric and magnetic fields.
Other examples of the fields not being in phase are: standing waves where the phase difference is $\pi/2$, evanescent waves where the wave vector is no longer real even in a non-dispersive medium, the near field around an antenna, . . . . .


text:
Q: How to extend tt_address I created my first extbase extension which works fine. Now i want to enter address informations into my extension, like city, zip code and street.
I preffer to create a relation to "tt_address". My aim is to create a 1:N relation from "tt_address" to my extension.
But the extension "tt_address" is based on "pi_base", how can i handle this issue? How must my "tca" look?
How can i create a record form my "createAction" into the "tt_address" table, should i need the object manager?
Is there a example on web?
Update, i extend my model with street, zip and city:
   /**
     * street
     *
     * @var string
     */
    protected $street;

    /**
     * street
     *
     * @var string
     */
    protected $zip;

    /**
     * street
     *
     * @var string
     */
    protected $city;

    public function setStreet($street)
    {
        $this->street = $street;
    }

    public function getStreet()
    {
        return $this->street;
    }

    public function setCity($city)
    {
        $this->city = $city;
    }

    public function getCity()
    {
        return $this->city;
    }

    public function setZip($zip)
    {
        $this->zip = $zip;
    }

    public function getZip()
    {
        return $this->zip;
    }

After this i extend my typoscript setup.txt
plugin.tx_oaevents {
    view {
        templateRootPath = {$plugin.tx_oaevents.view.templateRootPath}
        partialRootPath = {$plugin.tx_oaevents.view.partialRootPath}
        layoutRootPath = {$plugin.tx_oaevents.view.layoutRootPath}
    }
    persistence {
    storagePid = {$plugin.tx_oaevents.persistence.storagePid},148
    classes {
        Mab\Oavents\Domain\Model\Events {
            mapping {
                        tablename = tx_nnaddress_domain_model_address
                        columns {
                            zip.mapOnProperty = zip
                            street.mapOnProperty = street
                            city.mapOnProperty = city
                        }
                    }
        }

    }
}

And in last step i extend my extension TCA.
address' => array(
            'exclude' => 1,
            'label' => 'Events',
            'config' => array(
                'type' => 'select',
                'foreign_table' => 'tt_address',
                'minitems' => 0,
                'maxitems' => 1,
            ),
        ),

A: You need to create a model and map it in TS to table tt_address. In this mapping you need to set each field from your model to a column in table that you want to map. When you will have model and mapping everything else is the same. You create controller and repository for your model and you can create createAction that will insert something to table tt_address


text:
Q: A question about merged Poisson process Question here:
Iwana Passe is taking a multiple-choice exam. You may assume that the number of questions is infinite. Simultaneously, but independently, her conscious and subconscious faculties are generating answers for her, each in a Poisson manner. (Her conscious andsubconscious are always working on different questions.) Conscious responses are generated at the rate $λ_c$ responses per minute. Subconscious responses are generated at the rate $λ_s$ responses per minute. Assume $λ_c \neq λ_s$. Each conscious response is an independent Bernoulli trial with probability $p_c$ of being
 correct. Similarly, each subconscious response is an independent Bernoulli trial with probability $p_s$ of being correct. Iwana responds only once to each question, and you can assume that her time for recording these conscious and subconscious responses is negligible.
All my solutions are based on the fact that conscious and subconscious responses form the merged Poisson process.
(a)
If we pick an interval of T minutes, what is the probability that in that interval Iwana will make exactly $r$ conscious responses and $s$ subconscious responses?
My solution: Because this is the merged Poisson process, so the probability when conscious happens    is $\frac{\lambda_c}{\lambda_c+\lambda_s} $ , similar for the subconscious. Thus the probability is $$ \binom{r+s}{r} \frac{(\lambda_c)^r(\lambda_s)^s}{(\lambda_c+\lambda_s)^{s+r}} $$
But the given answer is:
Since the conscious and subconscious responses are generated independently,
P($r$ conscious responses and s subconscious responses in interval $T$)
= P($r$ conscious responses in $T$)P($s$ unconscious responses in $T$) = $$ \frac{(\lambda_cT)^re^{-\lambda_cT}}{r!}\cdot \frac{(\lambda_sT)^se^{-\lambda_sT}}{s!}$$
I think that the total events are given, the interval T is not in the business.
Appreciate  if you help! Thanks!
A similar question:

A: What you wrote is $\textsf{Pr}(R=r\land S=s\mid R+S=r+s)$. What they wrote (and what the question asked for) is $\textsf{Pr}(R=r\land S=s)$. The latter depends on the interval, the former doesn't.


text:
Q: Contents of title field "all lowercase" for BibTeX entry? Online resources like this:
@MISC{Google:AppEngine:Datastore:Java:API,
  author = {Google},
  year = {2012},
  month = "April",
  title = {Google App Engine Datastore Java API},
  url = "https://developers.google.com/appengine/docs/java/datastore/",
  note = "[Accessed: June 2012]"
}

have an "all lowercase" title in my bibliography. Non-@MISC resources display just fine.
Example: (the above is displayed as follows)
Google (2012), `Google app engine datastore java api'. [Accessed: June 2012].
URL: https://developers.google.com/appengine/docs/java/datastore/
I am using:
\usepackage[round]{natbib}
\usepackage{multibib}
\bibliographystylereferencedonline{agsm}
\bibliographyreferencedonline{robottinosino}

and quoting without citation:
\nocitereferencedonline{Google:AppEngine:Datastore:Java:API}

Any ideas as to why?
Also, could I have the [Accessed: Month Year] block appear after the nicely formatted URL?

A: You pose two questions. First, to keep the words in the title field -- other than the first one, viz., "Google" --  from becoming set in all-lowercase, encase the publication's title in a second pair of curly braces. I.e., set up the field as
title = {{Google App Engine Datastore Java API}},

The second question is about how to change the ordering of the output of the fields url and note, given that you're using the agsm bibliography style. The problem with this request is that the ordering of fields of various entry types (article, book, techreport, ...) is currently consistent across all of these entry types in the agsm style. It might look downright weird to your readers if the ordering were changed for some entry types only. I would therefore advise against fiddling with the ordering of the fields in the function misc of the file agsm.bst. If you do decide to edit that file, be sure to save it under a new name (say, myagsm.bst) rather than overwriting the existing file.


text:
Q: Javascript error on mobile only I'm working on getting a slideshow mobile friendly, but am running into a problem. I'm pretty sure it's javascript related because pages without the slideshow load fine. The site has a lot of images all categorized in the NextGen Gallery plugin, so I installed a slideshow plugin that would work with the existing setup.
It works fine on desktop without any console errors, but when it's loaded on my phone I get an error stating, "A problem occurred with this webpage so it was reloaded." It tries a few more times, then gives up.
I've never run into this with anything I've ever made, so I'm not sure where to start to try and fix it since I don't have any errors to go off of. Is there a way to fix this? Or is there a similar plugin that can integrate with NextGen Gallery as well?
An example can be seen here: example slideshow
Slideshow plugin: NextGen Galleryview


text:
Q: When compiling Gatsby, I get an error, and if I reset VS Code, the error disappears I'm new to Gatsby, I find that every time I need to compile, for some reason I had to cancel the current compilation, I always get an error:
Failed to remove .cache files. EPERM: operation not permitted, unlink 'C:\madvikinggames\gatsby\gatsby-styled-components\gatsby-starter-styled-components\.cache\_this_is_virtual_fs_path_\$virtual'

And all I have to do is to kill that terminal, leave VS Code, re-enter VS Code, open a new terminal, and npm run start again
Some other times the error is related to copying some files
It seems to be some kind of permission I have to give VS Code, but I don't know what

A: It seems that the VS Code terminal doesn't have enough permissions to remove the .cache and the /public folder, something that you should have in the develop command along with other actions that you are not allowed to perform.
Try opening the VS Code with administrator rights:  Visual studio code terminal, how to run a command with administrator rights?


text:
Q: Previously Declared Variable Is Not Passing Values I am having to create a calculator that has dynamic rates. I am having problems at around line 65 and 66 (search for $("span.25X60sqftPrice").text(mmwtsq[0]*2.29); ) running a simple a calculation with a previously declared variable (works if you swap the variable for a number). I have tried parseFloating and parseInt to make sure that a numeric value is passed but still get nothing. Tracing the value of the variable mmwtsq[0] via console.log gives me 0.

//---------------------global helper functions

function getFloatValue(className) {
 var val = parseFloat($('input.' + className).val());
 if(val == NaN)
  val = 0;
 return val;
}

function setMMWCVars() {
 //---------------------Window Count Variables
 mmwc[0] = getFloatValue("25X60");
 mmwc[1] = getFloatValue("35X60");
 mmwc[2] = getFloatValue("60X48");
 mmwc[3] = getFloatValue("60X60");
 mmwc[4] = getFloatValue("30X84");
 mmwc[5] = getFloatValue("72X60");
 mmwc[6] = getFloatValue("24X72");
 mmwc[7] = getFloatValue("96X60");
 mmwc[8] = getFloatValue("96X72");
 mmwc[9] = getFloatValue("48X84");
}

function setMMWTSQVars() {
 mmwtsq[0] = (25*60*mmwc[0])/12;
 mmwtsq[1] = (35*60*mmwc[1])/12;
 mmwtsq[2] = (60*48*mmwc[2])/12;
 mmwtsq[3] = (60*60*mmwc[3])/12;
 mmwtsq[4] = (30*84*mmwc[4])/12;
 mmwtsq[5] = (72*60*mmwc[5])/12;
 mmwtsq[6] = (24*72*mmwc[6])/12;
 mmwtsq[7] = (96*60*mmwc[7])/12;
 mmwtsq[8] = (96*72*mmwc[8])/12;
 mmwtsq[9] = (48*84*mmwc[9])/12;
}

//---------------------Window Count Variables
var mmwc = [10];
var mmwtsq = [10];

//----------------------Window Total SqFt Variables

$(document).ready(function(){

 function updateVars() {
  setMMWCVars();
  setMMWTSQVars();
//Get window & sqft totals
  $("span.totalWindowSqFt").text(mmwtsq[0] + mmwtsq[1] + mmwtsq[2] + mmwtsq[3] + mmwtsq[4] + mmwtsq[5] + mmwtsq[6] + mmwtsq[7] + mmwtsq[8] + mmwtsq[9]);
  $("span.totalWindowCount").text(mmwc[0] + mmwc[1] + mmwc[2] + mmwc[3] + mmwc[4] + mmwc[5] + mmwc[6] + mmwc[7] + mmwc[8] + mmwc[9]);

//show sqft & install price [header table and total prices]
  var totalSquareFootage = parseFloat($("span.totalWindowSqFt").text());
  var totalWindowCount = parseFloat($("span.totalWindowCount").text());

  if(totalSquareFootage < 99){
   $("span.25X60sqftPrice").text(mmwtsq[0]*2.29);
 //also tired something dirty to see if it would work like $("span.25X60sqftPrice").text(parseFloat($("span.total25X60").text())*2.29);
  }else{
   $("span.SqftRate").text(2.00);
  }

 }

 updateVars();

//calc total of sqft for window sizes & get total count / sq ft measurements of all window sizes;
 $("input.25X60").change(
  function(){
   updateVars();
   $("span.total25X60").text( mmwtsq[0] );
  });
});

<title>SqFt Blinds Calculator - 1" Metal Mini</title>

Window Width
Window Height
Blind Count
Total Sq Ft
Price Per Sq Ft
2.29
Install
16.95

25
60
<input class="25X60" value="0">
0
0
0

35
60
<input class="35X60" value="0">
0
0
0

60
48
<input class="60X48" value="0">
0
0
0

60
60
<input class="60X60" value="0">
0
0
0

30
84
<input class="30X84" value="0">
0
0
0

72
60
<input class="72X60" value="0">
0
0
0

24
72
<input class="24X72" value="0">
0
0
0

96
60
<input class="96X60" value="0">
0
0
0

96
72
<input class="96X72" value="0">
0
0
0

48
84
<input class="48X84" value="0">
0
0
0

0
0
0
0

A: Some potential improvements you can perform:

//---------------------global helper functions

function getFloatValue(className) {
  var val = parseFloat($('input.' + className).val());
  if (val == NaN)
    val = 0;
  return val;
}

function setMMWCVars() {
  //---------------------Window Count Variables
  mmwc[0] = getFloatValue("25X60");
  mmwc[1] = getFloatValue("35X60");
  mmwc[2] = getFloatValue("60X48");
  mmwc[3] = getFloatValue("60X60");
  mmwc[4] = getFloatValue("30X84");
  mmwc[5] = getFloatValue("72X60");
  mmwc[6] = getFloatValue("24X72");
  mmwc[7] = getFloatValue("96X60");
  mmwc[8] = getFloatValue("96X72");
  mmwc[9] = getFloatValue("48X84");
}

function setMMWTSQVars() {
  mmwtsq[0] = (25 * 60 * mmwc[0]) / 12;
  mmwtsq[1] = (35 * 60 * mmwc[1]) / 12;
  mmwtsq[2] = (60 * 48 * mmwc[2]) / 12;
  mmwtsq[3] = (60 * 60 * mmwc[3]) / 12;
  mmwtsq[4] = (30 * 84 * mmwc[4]) / 12;
  mmwtsq[5] = (72 * 60 * mmwc[5]) / 12;
  mmwtsq[6] = (24 * 72 * mmwc[6]) / 12;
  mmwtsq[7] = (96 * 60 * mmwc[7]) / 12;
  mmwtsq[8] = (96 * 72 * mmwc[8]) / 12;
  mmwtsq[9] = (48 * 84 * mmwc[9]) / 12;
}

function updatePrices(sqft, price) {
  $("thead span.SqftRate").html(sqft);
  $("thead span.installPrice").html(price);
}

function calcTotal(q, c) {
  return t = q * c || 0;
}

function getTotals() {
  var c = 0,
    sqft = 0,
    p = 0,
    i = 0,
    cls;
  $("tbody tr:not(:last)").each(function() {
    cls = $("input", this).attr("class");
    if ($("input", this).val() != "0") {
      c = c + parseInt($("input", this).val());
      sqft = sqft + parseInt($(".total" + cls, this).text().trim());
      p = p + parseFloat($("." + cls + "sqftPrice", this).text().trim());
      i = i + parseFloat($("." + cls + "Install", this).text().trim());
    }
    console.log("Totals", cls, c, sqft, p, i);
  });
  $(".totalWindowCount").html(c);
  $(".totalWindowSqFt").html(sqft);
  $(".totalBlindCost").html(p);
  $(".totalInstallCost").html(i);
}

//---------------------Window Count Variables
var mmwc = [10];
var mmwtsq = [10];

//----------------------Window Total SqFt Variables

$(function() {
  function updateVars() {
    setMMWCVars();
    setMMWTSQVars();

    $("tbody tr").each(function(i, el) {
      var c = $("input", el).attr("class");
      var t = mmwtsq[i];
      var p = 0;
      switch (true) {
        case t < 99:
          p = t * 2.29;
          break;
        case t < 999:
          p = t * 2.29;
          break;
        case t < 9999:
          p = t * 2.29;
          break;
      }
      var install = (p == 0 ? 0 : p + 16.95);
      $(".total" + c, el).html(t);
      $("." + c + "sqftPrice", el).html(p);
      $("." + c + "Install", el).html(install);
    });
    getTotals();
  }

  updateVars();

  //calc total of sqft for window sizes & get total count / sq ft measurements of all window sizes;

  $("input").change(function() {
    var c = $(this).attr("class");
    var i = $(this).parents("tr").index();
    console.log(c, i);
    updateVars();
    $("span.total" + c).text(mmwtsq[i]);
  });
});
table tbody input {
  width: 4em;
}

      Window Width
      Window Height
      Blind Count
      Total Sq Ft
      Price Per Sq Ft
2.29
      Install
16.95

      25
      60
      <input class="25X60" value="0">
      0
      0
      0

      35
      60
      <input class="35X60" value="0">
      0
      0
      0

      60
      48
      <input class="60X48" value="0">
      0
      0
      0

      60
      60
      <input class="60X60" value="0">
      0
      0
      0

      30
      84
      <input class="30X84" value="0">
      0
      0
      0

      72
      60
      <input class="72X60" value="0">
      0
      0
      0

      24
      72
      <input class="24X72" value="0">
      0
      0
      0

      96
      60
      <input class="96X60" value="0">
      0
      0
      0

      96
      72
      <input class="96X72" value="0">
      0
      0
      0

      48
      84
      <input class="48X84" value="0">
      0
      0
      0

      0
      0
      0
      0

I suspect you're making this far more complex than it needs to be.
Hope that helps.


text:
Q: Fill an area with as few rectangles as possible Saying I have shapes like these (made of a finite number of elementary 1cm*1cm squares):

Is there any algorithm to apply so I can fill these shapes with the least amount fo rectangles (besides listing all the fillings I could do and take the one with less rectangles)?
And what if the shape as holes in it?
All I found so far are just "be smart", but I would like to be able to let a computer do that. Thanks for the tips!
Image from http://static.studyladder.com/cdn/course/b3/2b1e1e9d0ed0.jpg

A: Not really an answer (or maybe yes), but too long for a comment.
It is important the filling to be minimal? If not, you can do the following.

*

*Begin at any tile of the figure. Consider this a rectangle of size 1.

*For each direction (N, S, E, W) enlarge the rectangle in that direction.

*If the new rectangle is contained in the figure, keep the change. Otherwise, discard it and try other direction.

*If the rectangle can't be enlarged anymore in any direction, remove it from the figure and append the data of the rectangle in some array to store it. Otherwise return to step 2.

*Repeat from 1 until the figure is totally removed.

I have tried some examples (by hand) and the results seems good.

A: This section of the "Polygon covering" page in Wikipedia
implies that brute-force trial and error
(generating all the partitions into rectangles and taking the one
with the fewest rectangles)
is the best you can do in general.
The problem I think you're describing is $NP$-hard.
But the $NP$-hardness of a problem often describes only the
worst-case times due to some pathological cases.
The figures you gave as examples look relatively "nice."
You could use some heuristics to make the algorithm try large rectangles
in cases such as these, which would often lead it to find the minimal
covering quickly; you then might use some "branch and bound" method
to quickly rule out all other possible coverings.
For example, once you have found a covering with $n$ rectangles,
when you are searching for another covering and have already put
$n-1$ rectangles in the covering without completing it, you can
rule out all the coverings that include those $n-1$ rectangles.
This could very quickly eliminate large portions of your search space.


text:
Q: How to populate a fragment with an entity from a Room Database? On navigation to a fragment I'm passing an ID of a Room DB entity. I'm now trying to set the text of a textview to an attribute of this entity.
This is what I'm currently trying, but it doesn't seem to work:
I have a ViewModel called editPlanViewModel in my Fragment. This is the ViewModel:
class EditPlanViewModel(
private val trainingPlanKey: Long = 0L,
val database: TrainingPlannerDatabaseDao) : ViewModel() {

private val viewModelJob = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)

private val _plan = MutableLiveData<TrainingPlan>()
val plan: LiveData<TrainingPlan>
    get() = _plan

init {
    uiScope.launch {
        withContext(Dispatchers.IO) {
            Log.d("DEBUG", "Before get")
            _plan.value = database.get(trainingPlanKey) ?: return@withContext
            Log.d("DEBUG", "After get")
        }
    }
}

override fun onCleared() {
    super.onCleared()
    viewModelJob.cancel()
}

In TrainingPlannerDatabaseDao:
@Query("SELECT * FROM training_plan_table WHERE planId = :key")
fun get(key: Long): TrainingPlan?

The plan LiveData should be changed so in my Fragment I set up an observer:
editPlanViewModel.plan.observe(viewLifecycleOwner, { plan ->
    Log.d("DEBUG", "In observer")
    if (plan != null) {
        binding.planName.text = plan.name
    }
})

It seems that the observer is never triggered. I added three logs, but only the "Before get" is triggered.
Does anyone know why the observer is not triggered or have another way to achieve the same result?

A: If you're not reaching past this line with no exceptions:
_plan.value = database.get(trainingPlanKey) ?: return@withContext

then it can only be that database.get(trainingPlanKey) was null and everything is working as intended.


text:
Q: how to convert the flex date object to MySQL date and time? how to convert flex date objec to sql date and time,
i am using AMFPHP to connect with mysql
need help
cheers

A: actually the date to string of flex will give you the format like
Day Mon Date HH:MM:SS TZD YYYY
but sql is like
2010-12-14 00:00:00
so what you do is make a string of the sql format and just pass as object to AMFPHP that will save it to sql
and sql will accept it as date time
private function dateToString(date:Date):String
        {
            var dateString:String = date.fullYear+"-"+(date.month+1)+"-"+date.date+" "+date.hours+":"+date.minutes+":"+date.seconds;
            return dateString;
        }//end function

cheers....

A: I suppose, the date is sent as string. In that case, use mysql function STR_TO_DATE()


text:
Q: Expect script execution status In the following expect script how to  get the exit status of rsync in the expect script
if [$? -eq 0]  throws an error as
         invalid command name "$?"
         while executing
         "$? -eq 0 "
         invoked from within
        "if [ $? -eq 0 ]"
       (file "./tmp544.sh" line 7)

    #!/usr/bin/expect -f

    eval spawn ssh -l root 174.54.87.12 rsync /root/project /usr/project
    expect "root@174.54.87.12's password: $"
    send "\xxxxxxx\n"
    expect "\\$ $"
    if [ $? -eq 0 ]
    then
      echo "11"
    else
      echo "22"
    fi

A: if [$? -eq 0]

is a shell construction, and you are in an expect script.
I think you should separate the rsync part from the ssh part, and use the remote shell to evaluate rsync status :
eval spawn ssh -l root 174.54.87.12
expect "root@174.54.87.12's password: $"
send "\xxxxxxx\n"
expect "\\$ $"
send "rsync /root/project /usr/project"
expect "\\$ $"
send "echo $?"
# Examine the output of $?

$? is available on interactive shell, not only in scripts, you can use it on the command line, and it looks like a good occasion to do so !
I am not familiar with expect, but I guess expect "\$ $" is waiting for the shell prompt, so I blindly copy pasted it.


text:
Q: How to manage file in Jedox with groovy/java(or natively) without java.nio or java.io librairies? I have to manipulate file in Jedox on cloud instance and they brutaly blocked java.io and java.nio libraries.
I want to create a simple directory/create file/move file and I can't.
Is there any other library or just native function that handle this type of task in java/groovy ?
Is it possible to do it natively in jedox if you can't do it by coding anymore ?


text:
Q: Ansible when conditional with variable and item I'm having hard time trying to figure it out what I'm doing wrong with my Ansible playbook.
I've got a bunch of tasks, which define or not some variables according to context, depending of the result, some task will be ignored or not.
For this specific case, I check if a VlanID already exists, if it doesn't then I create one, and retrieve the new VlanID from the result.
Here is the playbook :
---
#Tasks for portGroup_add
- name: Get all portgroups in dvswitch vDS
  community.vmware.vmware_dvs_portgroup_find:
    hostname: "{{ vcenter_server }}"
    username: "{{ vcenter_user }}"
    password: "{{ vcenter_pass }}"
    dvswitch: "{{ vcenter_dvSwitch }}"
    validate_certs: False
  register: portGroup_infos
  when: (OLD_VLANID is not defined) or (OLD_VLANID|length < 1)

  #Get last VLAN ID for HDS client, and set VLANID + 1
- name: get portGroup_infos
  set_fact:
    VLANID: "{{ item.vlan_id }}"
  with_items: "{{ portGroup_infos.dvs_portgroups}}"
  when:
    - (portGroup_infos is defined) and (portGroup_infos|length > 0)
    - item.name | regex_search("\(HDS :\s*")

While everything is working pretty well for most of the tasks, this one fires the following error :
The conditional check 'item.name | regex_search("\(HDS :\s*")' failed.
The error was: error while evaluating conditional (item.name | regex_search("\(HDS :\s*")): 'item' is undefined

Which is pretty obvious, because the dict portGroup_infos, is not defined.
In order to get the new VlanID, I'm using a "when" conditionnal , which check if in the item, the value "(HDS :" , is present.
But I don't want the task to launch if the portGroup_infos variable defined above is not set, I though I'd should use nested "when", but can't succeed.
Ansible version : 2.10.7
python version : 3.7.3
Thank you for your help.

A: Put both tasks into a block, e.g.
- block:
    - name: Get all portgroups in dvswitch vDS

      ...

    - name: get portGroup_infos

      ...

  when: OLD_VLANID|default('')|length == 0


text:
Q: Wifi adapter not found or recognized on 18.04 Wi-Fi adapter Intel WM3945ABG. Though this info doesn't even appear in output when lspci -knn | grep Net -A2 is run. I have tried rfkill list all and there is no software or hardware block on Bluetooth but doesn't even mention Wi-Fi. When I press hardware switch airplane mode comes on.
Update: I ran the command: dmesg | grep iwl and it said [619.465539] iwl3945: hw_scan is disabled. Anyone know what that means and how to fix it?


text:
Q: "T extends Component" in JSDoc get_components<T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[]
{
    return this.components.filter(component => component instanceof component_type_to_return)
}

Here is an example of a method I wrote in TypeScript, what I am trying to do is make an equivalent version but with JSDoc.
** FINAL SOLUTION **
/**
 * Returns the components of type if the Doodad has one attached.
 * @template    {Component} T
 * @param       {{ new (doodad: Doodad): T }}   type    The component type to return
 * @return      {T[]}                                   All components of given type attached to the Doodad
 */
get_components(type)
{
    return this.components.filter(component => component instanceof type)
}

A: The following should do the trick:
Solution 1
/**
 * @type {{
 *   <T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[]
 * }}
 */
get_components(component_type_to_return)
{
    return this.components
      .filter(component => component instanceof component_type_to_return)
}

Solution 2
/**
 * @template {Component} T
 * @param {{ new (doodad: Doodad): T }} component_type_to_return
 * @returns {T[]}
 */
get_components(component_type_to_return)
{
    return this.components
      .filter(component => component instanceof component_type_to_return)
}


text:
Q: Questions on Dictionary Data myd = {"abc":11, "def":8, "ghi":10, "jkl":3, "mno":12,
"pqr":9, "stu":11, "wvxyz":15}

I need help on these 3 questions:

*

*Write a code that will print the item and the value such that value is the smallest in myd.

*Write a code that will print the item and the value such that value is the largest in myd.

*Make two new dictionaries myd1 and myd2 such that myd1 contains the items whose value is less than and equal to 10, and myd2 contains the rest.

A: here is some hint you can use:
>>> myd = {"abc":11, "def":8, "ghi":10, "jkl":3, "mno":12, "pqr":9, "stu":11,   "wvxyz":15}
>>> myd_key = myd.keys()       # will give you list of keys
>>> myd_key
['jkl', 'stu', 'pqr', 'abc', 'mno', 'wvxyz', 'ghi', 'def']
>>> myd_value = myd.values()  # will give you list of values
>>> myd_value
[3, 11, 9, 11, 12, 15, 10, 8]
>>> sorted(myd_value)              # sort the list
[3, 8, 9, 10, 11, 11, 12, 15]
>>> myd_key = sorted(myd_key,key = lambda x: myd[x])   #sort the key on value
>>> myd_key
['jkl', 'def', 'pqr', 'ghi', 'stu', 'abc', 'mno', 'wvxyz']
>>> print myd_key[0],myd[myd_key[0]]
jkl 3
>>> print myd_key[-1],myd[myd_key[-1]]
wvxyz 15

try last of your own

A: Here are the functions:
def max_dict(_dict):
    temp = {y:x for x,y in _dict.iteritems()} #Reverse the dict
    return temp[max(_dict.values())] #Return the max using the built-in max function

def min_dict(_dict):
    temp = {y:x for x,y in _dict.iteritems()} #Reverse the dict
    return temp[min(_dict.values())] #Return the min using the built-in min function

def new_dicts(_dict):
    _dict1 = {item:value for item, value in _dict.iteritems() if value <= 10} #Dict comprehension
    _dict2 = {item:value for item, value in _dict.iteritems() if value > 10} #Dict comprehension
    return _dict1, _dict2

Which work as:
>>> myd = {"abc":11, "def":8, "ghi":10, "jkl":3, "mno":12,
... "pqr":9, "stu":11, "wvxyz":15}
>>> max_dict(myd)
'wvxyz'
>>> min_dict(myd)
'jkl'
>>> new_dicts(myd)
({'jkl': 3, 'pqr': 9, 'ghi': 10, 'def': 8}, {'wvxyz': 15, 'stu': 11, 'abc': 11, 'mno': 12})
>>>


text:
Q: Complex number - round angle $T_{\alpha}$ will be the round of the complex plane with the angle $\alpha$.
calculate - $T_{\frac{3\pi}{2}}(2-3i)$
I think it's an easy question but I'm not sure how to solve it properly

A: By definition
$$T_{\frac{3\pi}{2}}(2-3i) = (2-3i)e^{3i\pi/2}=(2-3i)(\cos(3\pi/2)+i\sin(3\pi/2)) = (2-3i)(-i)=-3-2i.$$


text:
Q: Do you know if he didn't go to the party? Is this question correct? I was wondering if this question is correct or not? and if not, why not?

Do you know if he didn't go to the party?

It sounds kind of strange. I feel

'Do you know if he went to the party?'

is better... but i'm not sure why.
Can anyone help me?

A: Do you know if he didn't go to the party? can be rephrased to:
Do you know if he was absent from/absented himself from the party?
It might be used when everybody around you thinks he was present at the party, but you are the only one who is not sure and you want to ask someone what you want to know.
I don't think it is incorrect, but at the same, you don't have to ask that way for a simple question of whether he was present at the party.
I would say it might be quite unusual to ask that way.

A: It is correct, for "I know that he didn't go to the party".
WS2's comment explains neatly why it is strange, but also why such a question might be constructed.


text:
Q: Python kwargs taking value from other args I would like to make a function that derives 'default' values for kwargs based on the non-kwargs that are passed to it. For example:
numbers= [1,2,3,4,5]

def someMath(lst, divideBy = len(lst)):
    return sum(lst)/divideBy

In this example, I'd like the default return value of the function to be the sum of the passed numbers list divided by the length of the list.
someMath(numbers) # returns 3

However I still want the option to change what the divideBy value is:
someMath(numbers, divideBy=5) # returns 5

Is this possible and how?

A: I think the way Python programmers would usually write this is to do the following:
def someMath(lst, divideBy=None):
    if divideBy is None:
        return sum(lst)/len(lst)
    return sum(lst)/divideBy


text:
Q: Change Button function once clicked? I made a button click that I want to open/close my side menu.
I did this:
$("#middleleftopenclose").click(function() {
     $("#middleleft").css("width", 0);
     $("#middleleftopenclose").css("opacity", 1);
     $("#middleright").css("margin-left", 15);
});

How would I go about making the same button click open the menu back as well?
Thanks

A: Well as a simple solution, you could have a boolean flag storing the current state of the sidebar and test against it every time the button is clicked.
var sidebarVisible = false;

$("#middleleftopenclose").click(function() {
  if (sidebarVisible){
    // close sidebar
  }else{
    // open sidebar
  }
  // toggle boolean flag each time button is clicked
  sidebarVisible = !sidebarVisible;
});

I see you are actually altering the css properties of the element within the function... Perhaps it would be better to create classes with the appropriate properties for each state and simply swap the classes when the button is clicked. Meliborn mentions this in a comment.

A: You can use the jQuery :visible selector to see if the side menu is visible or not. If it's is visible then hide, if not visible, then show.
http://api.jquery.com/visible-selector/
$("#middleleftopenclose").click(function() {

     var visible = $("#SIDEMENU").is(":visible");

     if(!visible){

        // NOT VISIBLE - SO SHOW
        $("#middleleft").css("width", 0);
        $("#middleleftopenclose").css("opacity", 1);
        $("#middleright").css("margin-left", 15);

     }else{
        // VISIBLE - SO HIDE IT
        // WRITE YOUR CODE TO HIDE HERE
     }
});

A: Just add your CSS to classes, for example .closedMenuLeft, .closedMenuLeftOpenClose, .closedMenuRight, then toggle it on and off on click, like so:
$("#middleleftopenclose").click(function() {
    $("#middleleft").toggleClass("closedMenuLeft");
    $("#middleleftopenclose").toggleClass("closedMenuLeftOpenClose");
    $("#middleright").toggleClass("closedMenuRight");
})

A: Even though, .toggleClass() would be the perfect way to go. It lacks flexibility for more complex operations.
/* Aggregate in one CSS class, .active. */
.active #middleleft { width: 0; }
.active #middleleftopenclose { opacity: 1; }
.active #middleright { margin-left: 15; }

$("#middleleftopenclose").click(function() {
  $("#middle").toggleClass("active");
});

Considering #middle as the parent node of these elements.
Alternatively, you can make use of the .toggle() event. (Don't mistake with .toggle() animation.)
$("#middleleftopenclose").toggle(function() {
   // Show the element!
}, function(){
   // Hide the element!
});

These two functions will alternate execution between clicks. This is a built-in jQuery function.


text:
Q: Trying to work out the pinout of an RJ10 (or RJ 11) RS232 port, New here so please bear with me ;-)
I have a salt chlorination system for my pool, which includes a unit that tests the water for Chlorine and PH. It has an 'RS-232' port on it, which is supposed to be for external data capture. I then want to collect the data for my home automation system.
Unfortunately there is NO documentation for any of this, except that the User Doco for the device says 'For external Data capture' on the system diagram. The port is labeled as RS-232.
I am trying to work out the pinout (GND, RX, TX) and voltages of the 4 ping RJ-10 (or RJ-11) interface.
What I have found so far is:
+--------------+------------------+---------------+-------------+
: pin          : Direct to Ground : V to ground   : Assumption  :
: (wire color) : (BEEP from MM)   : when ON       :             :
+--------------+------------------+---------------+-------------+
: 1 (YELLOW)   :      YES         : 0v            : GND         :
: 2 (RED)      :      NO          : 0v-0.004v     : RX          :
: 3 (GREEN)    :      NO          : 9.54v         : TX          :
: 4 (BLACK)    :      YES         : 0v            : GND         :
+--------------+------------------+---------------+-------------+

Are my assumptions correct?
I really only want to receive data, as I believe it only sends data over the port, not receive commands. I am assuming the presence of the 9.5V on Pin 3 means this is the transmit pin?
I assume also I need to connect the ground from the device to the ground of the ESP8266 and can use with PIN 1 or 4 as the connector?
I want to use an ESP8266 to read the RS232, but it only takes 3.3v so will need to use a voltage divider to bring it down to 3.3v? (like described here https://electronics.stackexchange.com/a/186182/245164) Is that correct? And ground the bridge to the common ground (as described above?
Thanks in advance for your responses.
G./

A: Standard RS-232 uses both positive and negative voltages, usually in the ballpark of +/- 10V. Because generating high voltages and negative voltages requires some extra circuitry, a lot of devices today use the RS-232 signaling with standard logic levels instead, like the 0V/+3.3V of your ESP8266.
Since you're measuring +10V from your sensor, that suggests that it's standard RS-232 and will also output -10V. If you have a scope, watch it when it's sending data and confirm the two levels that it toggles between. It should be idling at the negative voltage, so it's a bit unusual to be measuring a positive voltage like that unless it's sending a lot of zeros.
If you're only receiving data from the sensor, you could probably get away with a voltage divider and diode to keep the signal between 0-3.3V, followed by an inverter (as the negative voltage corresponds to a logic 1 and positive is 0). If for some reason you end up needing to send data, you'll need an RS-232 transceiver to convert the 0-3.3V to the higher positive and negative voltages needed by standard RS-232.
Another option is to find the RS-232 transceiver chip on your sensor. If it's using 0-3.3V on the logic side, you could potentially remove the chip and connect the logic levels directly to your ESP if they're not too far away from each other.
One other thing to consider is that if the sensor has the ability to receive commands over that port, you should tie off its input to something to prevent the floating pin from triggering random input data. Ideally this would be to the negative voltage, but if that's not available you might have to figure something else out.
And one final suggestion to confirm the pinout and basic functionality: connect it to a USB-serial adapter on a computer, start up a terminal app, and make sure you can see the incoming data.


text:
Q: Scaling an ASP.NET application This is a very broad question, but hopefully I can get useful tips. Currently I have an ASP.NET application that runs on a single server. I now need to scale out to accommodate increasing customer loads. So my plan is to:
1) Scale out the ASP.NET and web component onto five servers.
2) Move the database onto a farm.
I don't believe I will have an issue with the database, as it's just a single IP address as far as the application is concerned. However, I am now concerns about the ASP.NET and web tier. Some issues I am already worried about:

*

*Is the easiest model to implement just a load balancer that will farm out requests to each of the five servers in a round-robin fashion?

*Is there any problem with HTTPS and SSL connections, now that they can terminate on different physical servers each time a request is made? (for example, performance?)

*Is there any concern with regards to session maintanence (logon) via cookies? My guess is no, but can't quite explain why... ;-)

*Is there any concern with session data itself (stored server side)? Obviously I will need to replicate session state between servers, or somehow force a request to only go to a single server. Either way, I see a problem here...

A: As David notes, much of this question is really more of an Administrative thing, and may be useful on ServerFault. The link he posts has good info to pore over.
For your Session questions: You will want to look at either the Session State Service (comes with IIS as a separate service that maintains the state in common between multiple servers) and/or storing asp.net session state in a SQL database. Both are options you can find at David Stratton's link, I'm sure.
Largely speaking, once you set up your out-of-process session state, it is otherwise transparent. It does require that you store Serializable objects in Session, though.

Round-Robin DNS is the simplest way to load-balance in this situation, yes. It does not take into account the actual load on each server, and also does not have any provision for when one server may be down for maintenance; anyone who got that particular IP would see the site as being 'down', even though four other servers may be running.
Load balancing and handling SSL connections might both benefit from a reverse proxy type of situation; where the proxy handles all the connections coming in, but all it's doing is encryption and balancing the actual request load to the web servers. (these issues are more on the Administration end, of course, but...)

Cookies will not be a problem provided all the web servers are advertising themselves as being the same web site (via the host headers, etc). Each server will gladly accept the cookies set by any other server using the same domain name, without knowing or caring what server sent it; It's based on the host name of the server the web browser is connecting to when it gets a cookie value.

A: That's a pretty broad question and hard to answer fully in a forum such as this.  I'm not even sure if the question belongs here, or if it should be at serverfault.com.  However....
Microsoft offers plenty of guidance on the subject.  The first result for "scaling asp.net applications" from BING comes up to this.
http://msdn.microsoft.com/en-us/magazine/cc500561.aspx

A: I just want to bring up areas you should be concerned about with the database.
First off, most data models built with only a single database server in mind require massive changes in order to support a database farm in a multimaster mode.
If you used auto incrementing integers for your primary keys (which most people do) then you're basically screwed out of the gate.  There are a couple ways to temporarily mitigate this but even those are going to require a lot of guesswork and have a high potential of collision.  One mitigation involves setting the seed value on each server to a sufficiently high number to reduce the likelihood of a collision...  This will usually work, for awhile.
Of course you have to figure out how to partition users across servers...
My point is that this area shouldn't be brushed off lightly and is almost always more difficult to accomplish than simply scaling "up" the database server by putting it on bigger hardware.
If you purposely built the data model with a multi-master role in mind then kindly ignore. ;)
Regarding sessions: Don't trust "sticky" sessions, sticky is not a guarantee.  Quite frankly, our stuff is usually deployed to server farms so we completely disable session state from the get go.  Once you move to a farm there is almost no reason to use session state as the data has to be retrieved from the state server, deserialized, serialized, and stored back to the state server on every single page load.
Considering the DB and network traffic from just and that their purpose was to reduce db and network traffic then you'll understand how they don't buy you anything anymore.

A: I have seen some issues related to round robin http/https sessions.  We used to use in process sessions and told the load balancers to make the sessions sticky.  (I think they use a cookie for this).
It let us avoid SQL sessions but meant that when we switched from http to https, our F5 boxes couldn't keep the stickiness.  We ended up changing to SQL sessions.
You could investigate pushing the encryption up to the load balancer.  I remember that was a possible solution for our problem, but alas, not one we investigated.

A: The session database on an SQL server can be easily scaled out with little code & configuration changes. You can stick asp.net sessions to a session database and irrespective of which web server in your farm serves the request, your session-id based sql state server mapping works flawless. This is probably one of the best ways to scale out the ASP.NET Session state using SQL server. For more information, read the link True Scaleout model for session state


text:
Q: A survey of classical results/theorems for mathematical biology and biomathematics. I am looking for some source that gathers most of the major results of mathematical biology before 2000. I have found various books that contains small subset of this, for examples, "Mathematical models in population biology and epidemiology" by Fred Brauer and Castillo-Chavez, and "Mathematics in population biology" by Horst Thieme.
To be specific, I am looking for more of theoretical and general results (applicable to all mathematical biology - not specific to one of its subfields). Something along the line of "Convergence results and a Poincaré-Bendixson trichotomy for asymptotically autonomous differential equations" by Thieme, H.R. J. Math. Biol. (1992) 30: 755. doi:10.1007/BF00173267.


text:
Q: Excel VBA - remove unmerged rows Having asked a question about deleting rows with merged cells, I've got the answer below. It generated an error: Runtime error 1004: Cannot use that command on overlapping selections.
It was suggested that I should unmerge delete columns and unmerge cells and that I should start a new questions for that.  I've added the commands to delete columns and unmerge cells below. The unmerging works fine but then I get the same 1004 error again.
Sub DeleteRows()

    Dim x           As Range
    Dim rngDelete   As Range

    For Each x In ActiveSheet.UsedRange
        If x.MergeCells Then
            If rngDelete Is Nothing Then
                Set rngDelete = x
            Else
                Set rngDelete = Union(rngDelete, x)
            End If

        End If
    Next

    If Not rngDelete Is Nothing Then
        rngDelete.UnMerge
        rngDelete.EntireColumn.Delete
        rngDelete.EntireRow.Delete
    End If

End Sub


text:
Q: Representing inductive types I implemented dependently typed lambda calculus in the spirit of this article: http://www.andres-loeh.de/LambdaPi/LambdaPi.pdf The calculus, works and I experimented with it and extended with several things: many universes, hardcoded induction axioms. However, I want to add inductive types to do more complex stuff.
I am thinking about two ways of doing so

*

*Introduce Fin-N, Product and W-types and represent inductive types with them.

*Generate induction and recursion axioms.

I like neither of the ways. The first one is too low level and requires substantial effort for converting from high-level language to the core language. The second way is quite work intensive, and error prone, since generation of recursion principles of complicated inductive types have many corner cases, i.e. positive/negative occurences.
How this can be done? How the types are implemented in existing systems such as Coq, Agda and Idris?

A: Sorry, but I don't know about Idris.
For Agda, I recommend Ulf Norell Phd Thesis as a starting point, but the system evolved since.
Coq introduces a third bullet in your list: automatically generated predicates.
Each inductive type comes with 3 (1 in some special cases) induction schemes that are automatically defined for the user, and named your_type_rect, your_type_rec and your_type_ind (only the latter one in the special cases). These are actual terms of the languages, generated automatically for the user, and used by the induction tactic (I'm not 100% sure about that last one), and not axioms.
In fact you can shut down this automatic generation and write your induction schemes yourself.
Some documentation about induction can be found here. I advises that you ask your question on the Coq mailing-list, where devs might give you more insight about the internals of Coq.
Best,
V.


text:
Q: Unexpected end of file error in bash script (Makefile) nested for-loop I have the code fragment you can see below in my Makefile I'm trying to write
When I run it, it gives me an unexpected end of file error on the first "do"
I've tried to remove the backslashes, remove as many spaces as I can, etc but I still can't seem to get it to work. Responses to most questions like this here involved people either forgetting to include a "done" or having kerning issues. That doesn't seem to be the case in my code
for i in 1 10 25 50 100 1000 10000;\
do\
    for j in 1 10 25 50 100 1000 10000;\
    do\
        ./myprogram --threads=j iterations=i>>myfile.csv;\
    done\
done

It's supposed to execute the test script above and append the answers to myfile.csv
Instead, I'm getting the following error:
/bin/sh: -c: line 7: syntax error: unexpected end of file
make: *** [tests] Error 1

Thanks!

A: This is a possible duplication of: How to write loop in a Makefile?
I could not get your error running your code, but I did notice you did not refer the variables correctly. In order to get the value of variable i, you should write $$i in a Makefile script.
In your case:
Makefile
target:
        for i in 1 10 25 50 100 1000 10000; \
        do \
                for j in 1 10 25 50 100 1000 10000; \
                do \
                        ./myprogram --threads=$$j iterations=$$i>>myfile.csv; \
                done ; \
        done


text:
Q: Show $\dim(U) = d_1^2 + d_2^2 + \cdots + d_k^2$, where $U$ is the set of matrices that commute with a diagonalizable matrix $A$ I asked this question last night, but I have made some additional progress where I have another question.

Let $A$ be an $n \times n$ diagonalizable matrix with distinct eigenvalues $\lambda_1, \ldots, \lambda_k$ with corresponding multiplicities $d_1, \ldots, d_k$. Show that $$\dim(U) = d_1^2 + d_2^2 + \cdots + d_k^2,$$ where $U = \{B \in M_n \,|\, AB = BA \}$.

PROOF: Let $A$ be an $n \times n$ diagonalizable matrix with eigenvalues $\lambda_1, \ldots, \lambda_k$ and respective multiplicities $d_1, \ldots, d_k$. Since $A$ is diagonalizable, $D = P^{-1}AP$ is a diagonal matrix.
Observe that for any $B \in U$, $$P^{-1}AP = D \implies P^{-1}ABP = D(P^{-1}BP)$$ and likewise $$P^{-1}BAP = (P^{-1}BP)D.$$ This implies that we need only determine matrices $C$ such that $CD = DC$.
Let $$D = \begin{pmatrix}\lambda_1I_1 & & & \\ & \lambda_2I_2 & & \\ & & \ddots & \\ & & & \lambda_kI_k\end{pmatrix}.$$ Note that $I_i$ is the identity matrix of size $d_i \times d_i$. Partition $C$ as such: $$C = \begin{pmatrix}C_{11} & C_{12} & \cdots & C_{1k} \\ C_{21} & C_{22} & & C_{2k} \\ \vdots & \vdots & \ddots & \vdots \\ C_{k1} & C_{k2} & \cdots & C_{kk}\end{pmatrix}$$ Because $C$ and $D$ should commute, $CD = DC$ and so for any $i, j = 1, \ldots, k$, we have $$\lambda_iC_{ij} = C_{ij}\lambda_j \implies (\lambda_i - \lambda_j)C_{ij} = O.$$
Because each eigenvalue is distinct, it is not possible that $\lambda_i - \lambda_j = 0$ (for $i = j$), which leaves that $C_{ij} = O$ where $i \ne j$. So $C$ is block diagonal.
Here's where I'm stuck. I'm not sure what comes next to deduce $\dim(U)$. I think I need to find the dimension of each $C_{ii}$. How can I find the dimension of each $C_{ii}$? Surely it isn't as easy as saying that each $C_{ii}$ is $d_i \times d_i$, is it?

A: It is surely that easy. Each diagonal block $C_{ii}$ interacts only with the $\lambda_iI_i$ part of $D$, both when calculating $CD$ and when calculating $DC$, and that part of the product clearly commutes without any restrictions on the entries of $C_{ii}$. The shape of  the $C_{ii}$ block is $d_i\times d_i$, and thus it contributes a term $d_i^2$ to the dimension of $U$.


text:
Q: How to count the number of requests for each method I need to count the number of requests for each of the methods - GET, POST, PUT, DELETE, HEAD from Apache access.log.
An example of an entry from the access.log:
83.167.113.100 - - [12/Dec/2015:18:31:25 +0100] "POST /administrator/index.php HTTP/1.1" 200 4494 "http://almhuette-raith.at/administrator/" "Mozilla/5.0 (Windows NT 6.0; rv:34.0) Gecko/20100101 Firefox/34.0" 8566

And here is the code:
    regul_ip = (r"^(?P<ips>.*?)")
    regul_method = (r"\"(?P<request_method>GET|POST|PUT|DELETE|HEAD)")

    dict_m = defaultdict(lambda: {"GET": 0, "POST": 0, "PUT": 0, "DELETE": 0, "HEAD": 0})
    with open(args.logfile) as file:
         for index, line in enumerate(file.readlines()):
            try:
                  ip = re.search(reg_ip, line).group()
                  method = re.search(reg_meth, line).groups()[0]
            except AttributeError:
                  pass
            dict_m[ip][method] += 1
    print(json.dumps(dict_m, indent=4))

The output is:
  },
    "107.173.213.131": {
        "GET": 1,
        "POST": 0,
        "PUT": 0,
        "DELETE": 0,
        "HEAD": 0
    },
    "5.152.203.98": {
        "GET": 1,
        "POST": 0,
        "PUT": 0,
        "DELETE": 0,
        "POST": 3,
        "PUT": 0,
        "DELETE": 0,
        "HEAD": 0
    },
    "5.141.199.97": {
        "GET": 9,
        "POST": 9,
        "PUT": 0,
        "DELETE":

But I need the following:
{
    "GET": 2248007,
    "POST": 918924,
    "PUT": 75,
    "DELETE": 1,
    "HEAD": 49973
}

How can I fix the code?

A: Based on the log file, each request will have keyword (POST, GET, DELETE, PUT) once. So you can simply count the occurrences of each keyword.
dict_m = dict()
with open(args.logfile) as file:
    data = file.read()
    dict_m["GET"] = data.count("GET")
    dict_m["POST"] = data.count("POST")
    dict_m["DELETE"] = data.count("DELETE")
    dict_m["PUT"] = data.count("PUT")


text:
Q: Why IS NULL not working in SQL? I have a category table where there are some entries. I want to show those category names which don't have any mpid , spid and pid. I don't know what I did wrong, but my IS NULL statement is not working in here. My sql:
function select_all_main_category_info() {
        require 'db_connect_temp.php';
        $sql="SELECT * FROM tbl_category WHERE mpid IS NULL AND spid IS NULL AND pid IS NULL AND deletion_status=1";
        if (mysqli_query($db_connect, $sql)) {
            $query_result=mysqli_query($db_connect, $sql);
            return $query_result;
        } else {
            die("Query Problem". mysqli_error($db_connect));
        }
    }

My PHP code to display category names:
<?php

include_once 'applications.php';

$res=select_all_main_category_info();

while($info=mysqli_fetch_assoc($res)) {
    echo $info['category_name'];
    echo '<br>';
}

The category table:

Can anyone please help?

A: My issue is resolved. I wasn't aware of the IS NULL and empty statement. Here's the SQL which fixed the issue:
$sql="SELECT * FROM tbl_category WHERE mpid ='' AND spid ='' AND pid='' AND deletion_status=1";


text:
Q: Calculate x,y line terminiating point of section of a circle I have a Cartesian plane running from -41 to 41 on the x and y axes and a circle centered on 0,0 with a radius of 41 divided up into a number of sections of different areas.  I know the percentage area of each section (ie: section 1 is 16.1% of the total area of the circle, section 2 is 13% of the total circle, etc -- think pie chart).
I need to calculate the x and y coordinates of the circumference points for each of the dividing lines of the section.
I am trying to programatically draw a 'pie chart' by dividing the circle into a number of points on he circumference from 0,0.
Here is my calculated data:

A: The angle represented by each percentage is just that percentage multiplied by $2 \pi$.  So if the first sector starts at $(41,0)$, horizontal to the left, and we go clockwise, the terminating point for that sector is $(41 \cos (0.161\cdot 2 \pi), -41 \sin (0.161\cdot 2 \pi)) \approx (21.75,-34.75)$, where the minus sign comes from going clockwise instead of counterclockwise.  The total angle of sectors $1$ and $2$ is then $0.291$ of the circle, so the ending point will be $(41 \cos (0.291\cdot 2 \pi), -41 \sin (0.291\cdot 2 \pi))\approx(-10.45,-39.58)$


text:
Q: dnsmasq forwards local request despite domain-needed From a new Debian 11 installation, I use the following dnsmasq configuration
domain-needed
log-queries
no-resolv
no-hosts
server=8.8.8.8

So Dnsmasq should not forward a no-full qualified request to the server.
But when I run host nowhere, /var/log/syslog shows the following lines
Mar 11 20:52:42 gateway dnsmasq[3904]: query[A] nowhere from 127.0.0.1
Mar 11 20:52:42 gateway dnsmasq[3904]: config nowhere is NODATA-IPv4
Mar 11 20:52:42 gateway dnsmasq[3904]: query[AAAA] nowhere from 127.0.0.1
Mar 11 20:52:42 gateway dnsmasq[3904]: config nowhere is NODATA-IPv6
Mar 11 20:52:42 gateway dnsmasq[3904]: query[MX] nowhere from 127.0.0.1
Mar 11 20:52:42 gateway dnsmasq[3904]: forwarded nowhere to 8.8.8.8

So the request is forward to 8.8.8.8.
Is it a bug ?

A: domain-needed is only for A and AAAA queries. Your log shows only MX query forwarding.

-D, --domain-needed
Tells dnsmasq to never forward A or AAAA queries for plain names, without dots or domain parts, to upstream nameservers. If the name
is not known from /etc/hosts or DHCP then a "not found" answer is returned.


text:
Q: Depth Testing isn't working when rendering into an FBO I am trying to render a 3d pyramid inside a frame buffer to display it in ImGui window. But the depth testing fails and I get this:

Here's what I have:
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(mainwin))
{
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);

    ImGui_ImplOpenGL3_NewFrame();
    ImGui_ImplGlfw_NewFrame();
    ImGui::NewFrame();

    glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    fbo.bind();//framebufferobject bind

    glClearColor(0.8f, 0.8f, 0.8f, 1.0f);

    glEnable(GL_DEPTH_TEST);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    /* Render here */
    defaultshader.Activate();

    // Handles camera inputs
    camera1.Inputs(mainwin);
    // Updates and exports the camera matrix to the Vertex Shader
    camera1.Matrix(45.0f, 0.1f, 100.0f, defaultshader, "camMatrix");

    tex1.Bind();
    VAO1.Bind();
    // Draw primitives, number of indices, datatype of indices, index of indices
    glDrawElements(GL_TRIANGLES, sizeof(indices) / sizeof(int), GL_UNSIGNED_INT, 0);
    //---------------------------------------------------------------------------------------------------------------------------
    fbo.unbind();

    ImGui::Begin("Viewport");

    AppImguiAddImage(fbtex.FBtexID);//adds image to imgui drawlist

    ImGui::End();

    AppImguiFrameEnd();

    /* Swap front and back buffers */
    glfwSwapBuffers(mainwin);

    /* Poll for and process events */
    glfwPollEvents();

}

Note:
I got AppImguiAddImage() and Clear() originally from:
https://gamedev.stackexchange.com/questions/150214/render-in-a-imgui-window
I have tried different combinations of color clear and depth clear for the two Clear() funtions in the while loop to get the same result.
What is going wrong?

A:
Does your FBO have a depth buffer attachment?
no, ...

That's your problem. If your FBO doesn't have a GL_DEPTH_ATTACHMENT then the depth test will be disabled when you render to that FBO.
To set a GL_DEPTH_ATTACHMENT on an FBO, you can attach either a renderbuffer (using glFramebufferRenderbuffer) or a texture (using glFramebufferTexture). These renderbuffer/texture would need to be in one of the depth formats.


text:
Q: How do I write a generic groupByKey for a Traversable[(K, V)] in scala <= 2.12 It's pretty easy to write a function from List[(K, V)] to Map[K, List[V]]:
def groupByKey[K, V](
  pairs: List[(K, V)]
): Map[K, List[V]] =
  pairs
    .groupBy(_._1)
    .mapValues(_.map(_._2))

but it seems a shame it's collection type specific.
I can generalise it of course to
def groupByKey[K, V](
  pairs: Traversable[(K, V)]
): Map[K, Traversable[V]] =
  pairs
    .groupBy(_._1)
    .mapValues(_.map(_._2))

but now I've got a Traversable back and I'd quite like the same type I put in, since groupBy does that for me.

A: Worked it out.
As a method:
def groupByKey[K, V, Repr <: TraversableLike[(K, V), Repr], That <: TraversableLike[V, That]](
  pairs: TraversableLike[(K, V), Repr]
)(implicit
  bf: CanBuildFrom[Repr, V, That]
): Map[K, That] = pairs
  .groupBy(_._1)
  .mapValues(_.map(_._2))

As an implicit class:
implicit class GroupByKey[K, +V, +Repr <: TraversableLike[(K, V), Repr], +That <: TraversableLike[V, That]](
  decorated: TraversableLike[(K, V), Repr]
)(implicit
  bf: CanBuildFrom[Repr, V, That]
) {
  def groupByKey: Map[K, That] = decorated
    .groupBy(_._1)
    .mapValues(_.map(_._2))
}


text:
Q: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Facebook;
using Newtonsoft.Json;

namespace facebook
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new FacebookClient(acc_ess);
            dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
            string jsonstring = JsonConvert.SerializeObject(result);

            //jsonstring {"data":[{"target_id":9503123,"target_type":"user"}]}
            List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);
        }

        public class Datum
        {
            public Int64 target_id { get; set; }
            public string target_type { get; set; }
        }

        public class RootObject
        {
            public List<Datum> data { get; set; }
        }
    }
}

Cannot deserialize the current JSON object (e.g. {"name":"value"})
  into type
  'System.Collections.Generic.List`1[facebook.Program+RootObject]'
  because the type requires a JSON array (e.g. [1,2,3]) to deserialize
  correctly. To fix this error either change the JSON to a JSON array
  (e.g. [1,2,3]) or change the deserialized type so that it is a normal
  .NET type (e.g. not a primitive type like integer, not a collection
  type like an array or List) that can be

I looked at other posts.
My json looks like this:
{"data":[{"target_id":9503123,"target_type":"user"}]}

A: To make it clear, in addition to @SLaks' answer, that meant you need to change this line :
List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);

to something like this :
RootObject datalist = JsonConvert.DeserializeObject<RootObject>(jsonstring);

A: Can you try to change your json without data key like below?
[{"target_id":9503123,"target_type":"user"}]

A: That happened to me too, because I was trying to get an IEnumerable but the response had a single value. Please try to make sure it's a list of data in your response. The lines I used (for api url get) to solve the problem are like these:
HttpResponseMessage response = await client.GetAsync("api/yourUrl");

if (response.IsSuccessStatusCode)
{
    IEnumerable<RootObject> rootObjects =
        awaitresponse.Content.ReadAsAsync<IEnumerable<RootObject>>();

    foreach (var rootObject in rootObjects)
    {
        Console.WriteLine(
            "{0}\t${1}\t{2}",
            rootObject.Data1, rootObject.Data2, rootObject.Data3);
    }

    Console.ReadLine();
}

Hope It helps.

A: As the error message is trying very hard to tell you, you can't deserialize a single object into a collection (List<>).
You want to deserialize into a single RootObject.

A: The real problem is that you are using dynamic return type in the FacebookClient Get method. And although you use a method for serializing, the JSON converter cannot deserialize this Object after that.
Use insted of:
dynamic result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"});
string jsonstring = JsonConvert.SerializeObject(result);

something like that:
string result = client.Get("fql", new { q = "select target_id,target_type from connection where source_id = me()"}).ToString();

Then you can use DeserializeObject method:
var datalist = JsonConvert.DeserializeObject<List<RootObject>>(result);

Hope this helps.

A: public partial class tree
{
    public int id { get; set; }
    public string name { get; set; }
    public string sciencename { get; set; }
    public int familyid { get; set; }
}

private async void PopulateDataGridView()
{
    //For Single object response
    tree treeobj = new tree();
    treeobj = JsonConvert.DeserializeObject<tree>(Response);
    //For list of object response
    List<tree> treelistobj = new List<tree>();
    treelistobj = JsonConvert.DeserializeObject<List<tree>>(Response);
    //done
}