text:
Q: Android Navigation Component pop to transition issue I have 2 actions
Action1
 <action
        android:id="@+id/actionBaseFragmentToAskForLocation"
        app:destination="@+id/introAskForLocationFragment"
        app:enterAnim="@anim/slide_in_right"
        app:exitAnim="@anim/slide_out_left"
        app:popEnterAnim="@anim/slide_in_left"
        app:popExitAnim="@anim/slide_out_right" />

Action2
<action
        android:id="@+id/actionIntroAskLocationToLogin"
        app:destination="@id/loginFragment"
        app:enterAnim="@anim/slide_in_right"
        app:exitAnim="@anim/slide_out_left"
        app:popEnterAnim="@anim/slide_in_right"
        app:popExitAnim="@anim/fade_out"
        app:popUpTo="@+id/app_main_navigation" />

What i want is when the second action is triggered i want to clear the back stack and set only loginFragment to remain in the stack.
just one problem is when i perform the Action2, 'slide_out_right' is performed as exit animation
I understand that if we pop the fragment from the stack the 'popExitAnim' of action1 will be triggered instead of 'exitAnim' of action2.
but i want to know how can I make the fragment perform slide_out_left animation for exiting and also pop it out of the stack.

A: This is bit of a tough one to solve due to NavOptions being internally handled by the convenience methods used in binding your drawer to the navigation graph. I originally tested this solution with the settings menu and onOptionsItemSelected but the basic idea should work here as well.
First, make sure your menu item IDs correspond to those of your navigation fragments:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    ...

    <item android:id="@+id/example_id" ... />
</menu>

<navigation xmlns:android="http://schemas.android.com/apk/res/android" ... >

    ...

    <fragment android:id="@+id/example_id" ... />
</navigation>

Now, rather than using the ready-made methods for connecting the drawer to your NavController Implement NavigationView.OnNavigationItemSelectedListener in your NavHost activity and override the method onNavigationItemSelected like so:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    NavHost navHost = Navigation.findNavController(this, R.id.your_nav_host_fragment);
    return NavigationUI.onNavDestinationSelected(item, navHost);
}

This will forward the selection as a navigation in your graph. Replace your_nav_host_fragment with the fragment ID on which you set app:defaultNavHost="true".
You will notice that while this works, it still defaults to the slide animations. This is because the NavigationUI call internally creates its own NavOptions with these settings:
NavOptions.Builder builder = new NavOptions.Builder()
                .setLaunchSingleTop(true)
                .setEnterAnim(R.anim.nav_default_enter_anim)
                .setExitAnim(R.anim.nav_default_exit_anim)
                .setPopEnterAnim(R.anim.nav_default_pop_enter_anim)
                .setPopExitAnim(R.anim.nav_default_pop_exit_anim);

Unfortunately the method does not yet take a NavOptions.Builder as an argument, but you can create an utility class based on the Android source code to mimic the functionality:
public class NavigationUIHelper {
    public static boolean onNavDestinationSelected(@NonNull MenuItem item,
                                                   @NonNull NavController navController,
                                                   @NonNull NavOptions.Builder builder) {
        if ((item.getOrder() & Menu.CATEGORY_SECONDARY) == 0) {
            NavDestination destination = findStartDestination(navController.getGraph());
            builder.setPopUpTo(destination.getId(), false);
        }
        NavOptions options = builder.build();
        try {
            navController.navigate(item.getItemId(), null, options);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }

    // Need to copy this private method as well
    private static NavDestination findStartDestination(@NonNull NavGraph graph) {
        NavDestination startDestination = graph;
        while (startDestination instanceof NavGraph) {
            NavGraph parent = (NavGraph) startDestination;
            startDestination = parent.findNode(parent.getStartDestination());
        }
        return startDestination;
    }
}

Finally, in your activity you can now replace the call to NavigationUI with the one implemented in NavigationUIHelper:
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    NavHost navHost = Navigation.findNavController(this, R.id.your_nav_host_fragment);
    NavOptions.Builder builder = new NavOptions.Builder()
                .setLaunchSingleTop(true)
                .setEnterAnim(R.anim.custom_enter)
                .setExitAnim(R.anim.custom_exit)
                .setPopEnterAnim(R.anim.custom_pop_enter)
                .setPopExitAnim(R.anim.custom_pop_exit);
    return NavigationUIHelper.onNavDestinationSelected(item, navHost, builder);
}

This should allow you to change the drawer transition animations according to your liking without having to replace the Navigation component.

A: I ended up overriding onCreateAnimation in the fragment that calls navigate. This exemple shows how to navigate through nested nav graphs by ID and replace the pop exit animation (or popExitAnim) conditionnally.
override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
    val navController = findNavController()
    val graph = navController.graph.findNode(R.id.onboardingGraph) as NavGraph
    val dest = graph.findNode(R.id.confirmationFragment)
    if (!enter && dest != null && navController.currentDestination?.id == dest.id) {
        return AnimationUtils.loadAnimation(requireContext(), R.anim.slide_out_left)
    }
    return super.onCreateAnimation(transit, enter, nextAnim)
}

Note that this particular situation is partly due to the directional nature of slide animations.


text:
Q: Using Asynctask to check if Internet is Accessible I have this Class to check if Internet is accessible:
public class NetworkAvailability extends AsyncTask<Context, Boolean, Boolean> {

Context mContext;

private static boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) ListViewActivity.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    if (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting()) {
        Log.i("Netzwerkstatus: ", "Netzwerk-Verbindung verfügbar");
        return true;
    }
    return false;

}

public NetworkAvailability(Context mContext) {
    this.mContext = mContext;
}

public NetworkAvailability() {
}

@Override
protected Boolean doInBackground(Context... params) {
    if (isNetworkAvailable()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.de").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            try {
                urlc.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //i ist 200 bei Internetverbindung
            int i = urlc.getResponseCode();
            return (i == 200);
        } catch (IOException e) {
            Log.e("IsInternetAccessible: ", "Konnte Internetverbindung nicht prüfen");
        }
    } else {
        Log.d("IsInternetAccessible:", "Internet nicht verfügbar");
    }
    return false;
}

Now i want to check if internet is accessible BEFORE parsing a xml.
Here is the snippet where i want to use this class.
if (networkAvailability.execute()) {
            XMLParser parser = new XMLParser();
            String xml = parser.getXMLFromUrl("http://XXXXXX.de/XX.xml");
            Document doc = parser.getDomElement(xml);

            NodeList nl = doc.getElementsByTagName(KEY_SYSTEM);

            for (int i = 0; i < nl.getLength(); i++) {

                // Neue HashMap erstellen
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);

                // Jedes Kind-Knoten zur HashMap
                map.put(KEY_UUID, parser.getValue(e, KEY_UUID));
                map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
                map.put(KEY_JOBTITLE, parser.getValue(e, KEY_JOBTITLE));
                map.put(KEY_JOBINFO, parser.getValue(e, KEY_JOBINFO));
                map.put(KEY_IMAGE, parser.getValue(e, KEY_IMAGE));

                //Hashmap zur ArrayList hinzufügen
                menuItems.add(map);
            }
        } else {
            Log.i("doInBackground:", "Keine Internet-Verbindung");
            return null;
        }

how can i use the result of my NetworkAvailability class in my if loop as condition?

A: what you can do is to create a seperate class to check internet connection and then create object of that class and the call the function this will also clean your code.
public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
    this._context = context;
    }

    public boolean isConnectingToInternet(){
       ConnectivityManager connectivity = (ConnectivityManager)  _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
   }
}

and then create object for that ConnectionDetector in your activity globaly like
ConnectionDetector cd=new ConnectionDetector(this);

and then where ever you want to use that function just call
if(cd.isConnectingToInternet()){

     //internet available
}else{

     //internet not available
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do my Bootstrap cards not line up vertically like the examples on their website? I am creating a web based chat application and I have some images stored in an Amazon S3 bucket. I loop through my servers which are stored in a MongoDB database and fetch all the servers which have been created. The servers each have their own unique image that is displayed in a server list, and they are inconsistent in height and width.
When I try to display them using Bootstrap's card-deck class I was under the impression they should all be displayed the same height and width but this isn't the case for me.
Here is the loop I run to fetch and display the servers:
<% _.forEach(chunks, function(val){ %>

                            <% _.forEach(val, function(val2) { %>

                                <form action="/home" method="post" id="fav" class="text-center m-0">
                                    <a href="/servers/<%= val2.name.replace(/ /g, "-") %>">
                                        <img src="www.amazondatabase.com/<%= val2.image %>" class="card-img-top img-fluid" alt="">

<%= val2.name %> (<%= val2.members.length %>)

                                        <input type="hidden" name="serverId" id="id" value="<%= val2._id %>">
                                        <input type="hidden" name="serverName" id="server_name"
                                               value="<%= val2.name %>">
                                        <button class="btn btn-outline-info btn-block mt-2">Join Server</button>

                                </form>

                            <% }) %>

            <% }) %>

When I run this code I get this output:

As you can see the cards aren't the same height and the footer's don't line up. How would I achieve similar results to the example on their website found here?: https://getbootstrap.com/docs/4.4/components/card/#card-decks
I have already tried using Bootstrap's card-group class, as well as giving the cards a h-100 class to make the height of the cards 100% but I still have variable height cards. I've also tried adding a class to the images to make them responsive but that doesn't work either.


text:
Q: How to implement Hold in Listbox? If hold the listbox, I want to get listbox index.
This is my code:
<ListBox Margin="0,0,-12,0"
         Hold="holdlistbox"
         x:Name="listbox"
         SelectionChanged="listbox_SelectionChanged"
         SelectedIndex="-1">
</ListBox>

private void holdlistbox(object sender, System.Windows.Input.GestureEventArgs e)
{
    //How to get ListBox index here
}

If anyone knows help me to do this.

A: e.OriginalSource will get you the actual control that was held (the top-most control directly under your finger). Depending on your ItemTemplate and where you hold then this could be any of the controls in the item. You can then check the DataContext of this control to get the object that is bound to that item (going by your comment this will be an ItemViewModel object):
FrameworkElement element = (FrameworkElement)e.OriginalSource;
ItemViewModel item = (ItemViewModel)element.DataContext;

You can then get the index of this item in the items collection:
int index = _items.IndexOf(item);

If you want to get the ListBoxItem itself you will need to use the VisualHelper class to search the parent heirarchy. Here is an enxtension method that I use to do this:
public static T FindVisualParent<T>(this DependencyObject obj) where T : DependencyObject
{
    DependencyObject parent = VisualTreeHelper.GetParent(obj);
    while (parent != null)
    {
        T t = parent as T;
        if (t != null)
        {
            return t;
        }
        parent = VisualTreeHelper.GetParent(parent);
    }
    return null;
}

I'm not sure if you need this (I couldn't be sure from your comment) but you can then do the following to get the context menu:
FrameworkElement element = (FrameworkElement)e.OriginalSource;
ListBoxItem listItem = element.FindVisualParent<ListBoxItem>();
ContextMenu contextMenu = ContextMenuService.GetContextMenu(listItem);

This assumes that the ContextMenu is attached to the ListBoxItem, if not then you need to search for a different control in the parent heirarchy.

A: var selectedIndex = (sender as ListBox).SelectedIndex;


text:
Q: Does .net compact framework application can run on windows 8 Can I install application developed in .NET compact framework (windows Mobile 6.5) or Windows CE to run on latest windows 8 phones or tablet?

A: No.  Windows 8 and Windows Phone 8 both have their own runtime and API.  If you want your application to run on Windows Phone 8 or on Windows 8 RT, you will need to develop specifically for those platforms.
Luckily, they do support a richer programming model than the .NET CF, so the port of the logic portion of your application should be fairly smooth.  The UI uses a completely different model, as it's now completely XAML based, and will likely need to be completely rewritten.


text:
Q: I can't figure out why this code does not display an Image in Android I am following very closely to the sample codes in the resources for TicTacToeLib as well as an example of how to display a bitmap in a book titled Android Application Development. I am doing all the same things they are doing, the only difference is I am using a SurfaceView instead of a view.  Can anyone tell me what I am doing wrong? The end goal is to display the preview image of the camera manually as well as display an image over top of it.
Sorry I forgot to include what the problem was. The onDraw method is not being called ever. and I was under the impression it should be called by the invalidate method. Secondly the lockCanvas() method is returning a NULL canvas. Even after I fixed the code to not use the PUSH_BUFFER constant from SurfaceHolder (I have edited the code for this correction).
package com.test.combine;

import android.content.res.XmlResourceParser;
import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import java.io.IOException;
import android.util.Log;
import java.util.List;

public class CombineTestActivity extends Activity
{
private Preview mPreview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Hide the window title.
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    // Create our Preview view and set it as the content of our activity.
    mPreview = new Preview(this);
    setContentView(mPreview);
}

 }

// ----------------------------------------------------------------------

class Preview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private Paint mPaint;
private Canvas canvas;
private Bitmap currentprev;
private Picture mPicture;

private Camera.PreviewCallback mPrevCallback = new Camera.PreviewCallback()
{
        public void onPreviewFrame( byte[] data, Camera Cam ) {
                Log.d("CombineTestActivity", "Preview registered");
                Log.d("CombineTestActivity", "Data length = "
                        + data.length );
               // currentprev = BitmapFactory.decodeByteArray( data, 0,
               //       data.length );

               currentprev = BitmapFactory.decodeResource( getResources(),
                   R.drawable.creature00 );
               if( currentprev == null )
                   Log.d("CombineTestActivity", "currentprev is null" );

                Log.d("CombineTestActivity", "Preview Finished" );
                invalidate();
        }
};

private OnTouchListener mCorkyListener = new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent me) {
                Log.d("CombineTestActivity", "touch registered" );
                mCamera.takePicture( null, null, mPicCallback );
                return false;
        }
};

private Camera.PictureCallback mPicCallback = new Camera.PictureCallback() {
        public void onPictureTaken( byte[] data, Camera mCamera ) {

                Log.d("CombineTestActivity", "picture method run" );
        }
};

Preview(Context context) {
    super(context);

    // Install a SurfaceHolder.Callback so we get notified when the
    // underlying surface is created and destroyed.
mPicture = new Picture();
    mHolder = getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    canvas = mHolder.lockCanvas();
    if(canvas==null)
        Log.d( "CombineTestActivity", "canvas is null in constructor");

this.setOnTouchListener( mCorkyListener );

invalidate();

}

@Override
protected void onDraw( Canvas mCanvas ) {

        if( mCanvas == null )
                Log.e("CombineTestActivity", "canvas is null" );
        if( currentprev == null ) {
                Log.e("CombineTestActivity", "currentprev is null" );
                return;
        }

        mCanvas.drawBitmap( currentprev, 0.0f, 0.0f, mPaint );

        Log.d("CombineTestActivity", "exiting onDraw" );

}

public void surfaceCreated(SurfaceHolder holder) {
    // The Surface has been created, acquire the camera and tell it where
    // to draw.

    mCamera = Camera.open();
    mCamera.setPreviewCallback( mPrevCallback );

    /*
    try {
       mCamera.setPreviewDisplay(holder);
    } catch (IOException exception) {
        mCamera.release();
        mCamera = null;
        // TODO: add more exception handling logic here
    }
    */

}

public void surfaceDestroyed(SurfaceHolder holder) {
    // Surface will be destroyed when we return, so stop the preview.
    // Because the CameraDevice object is not a shared resource, it's very
    // important to release it when the activity is paused.
    mCamera.stopPreview();
   mCamera.release();
    mCamera = null;
}

private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.05;
    double targetRatio = (double) w / h;
    if (sizes == null) return null;

    Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    // Try to find an size match aspect ratio and size
    for (Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    // Cannot find the one match the aspect ratio, ignore the requirement
    if (optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }
    return optimalSize;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // Now that the size is known, set up the camera parameters and begin
    // the preview.
    Camera.Parameters parameters = mCamera.getParameters();

    List<Size> sizes = parameters.getSupportedPreviewSizes();
    if( sizes.isEmpty() )
        Log.d( "CameraTestActivity", "sizes null");
    else
        Log.d( "CameraTestActivity", "sizes not null");

    Size optimalSize = getOptimalPreviewSize(sizes, w, h);
    if( optimalSize == null )
        Log.d( "CameraTestActivity", "optimalSize null");
    else
        Log.d( "CameraTestActivity", "optimalSize not null");

    parameters.setPreviewSize(optimalSize.width, optimalSize.height);

if( parameters == null )
    Log.d( "CameraTestActivity", "parameters null" );
else
    Log.d( "CameraTestActivity", "parameters not null" );

    mCamera.setParameters(parameters);
    mCamera.startPreview();
}

}

A: I apparently found a solution. although SurfaceView inherits from View, it does not call onDraw like View does. As for why lockCanvas wasn't working, I still do not know.


text:
Q: Replacing NaN with pandas series.map(dict) I'm following a pandas tutorial that shows replacing values in columns by passing a dictionary to the series.map method. Here's a snippet from the tutorial:

However when I try this:
cols = star_wars.columns[3:9]

# Booleans for column values
answers = {
        "Star Wars: Episode I  The Phantom Menace":True,
        "Star Wars: Episode II  Attack of the Clones":True,
        "Star Wars: Episode III  Revenge of the Sith":True,
        "Star Wars: Episode IV  A New Hope":True,
        "Star Wars: Episode V  The Empire Strikes Back":True,
        "Star Wars: Episode VI  Return of the Jedi":True,
        NaN:False
        }

for c in cols:
    star_wars[c] = star_wars[c].map(answers)

I get NameError: name 'NaN' is not defined
So what am I doing wrong?
edit: To explain my goal a little better, I have columns that look like this:
And I'm trying to replace the NaNs with False and the non-NaNs with True.
edit 2: Here's an image of the problem I'm still facing after changing NaN to np.NaN:

Then if I rerun the mapping cell and display the output again, all the False and NaN values flip-flop.

A: Quite simply, Python doesn't have a built-in NaN name. NumPy does, however, and so you could get your mapping to not thrown an error with np.nan. There is also math.nan which is equal to float('nan') as Jon pointed out.
answers = {
        "Star Wars: Episode I  The Phantom Menace":True,
        "Star Wars: Episode II  Attack of the Clones":True,
        "Star Wars: Episode III  Revenge of the Sith":True,
        "Star Wars: Episode IV  A New Hope":True,
        "Star Wars: Episode V  The Empire Strikes Back":True,
        "Star Wars: Episode VI  Return of the Jedi":True,
        np.nan:False
        }

Don't stop here though, because that won't work.
The other tricky thing is that nan doesn't technically equal anything so using it in a mapping like this won't be effective.
>>> np.nan == np.nan
False

Thus, the NaN values in your DataFrame won't be picked up by np.nan as a key anyways, and remain NaN. For a further explanation of this, see NaNs as key in dictionaries. Furthermore, I would wager that your nan values are actually the string nan.
Minimal Demo
>>> df
                                          0                                  1
0  Star Wars: Episode I  The Phantom Menace                                nan
1         Star Wars: Episode IV  A New Hope                                nan
2         Star Wars: Episode IV  A New Hope  Star Wars: Episode IV  A New Hope

>>> for c in df.columns:
        df[c] = df[c].map(answers)

>>> df
      0     1
0  True   NaN
1  True   NaN
2  True  True

# notice we're still stuck with NaN, as our nan strings weren't picked up

Better solution
With that being said, this doesn't seem like a good use for a dict or map - you could just define the Star Wars strings in a set, then use isin on your whole section of columns of interest.
answers = {
        "Star Wars: Episode I  The Phantom Menace",
        "Star Wars: Episode II  Attack of the Clones"
        "Star Wars: Episode III  Revenge of the Sith",
        "Star Wars: Episode IV  A New Hope",
        "Star Wars: Episode V  The Empire Strikes Back",
        "Star Wars: Episode VI  Return of the Jedi",
        }

starwars.iloc[:, 3:9].isin(answers)

Minimal Demo
>>> answers = {
            "Star Wars: Episode I  The Phantom Menace",
            "Star Wars: Episode II  Attack of the Clones"
            "Star Wars: Episode III  Revenge of the Sith",
            "Star Wars: Episode IV  A New Hope",
            "Star Wars: Episode V  The Empire Strikes Back",
            "Star Wars: Episode VI  Return of the Jedi",
            }

>>> df
                                          0                                  1
0  Star Wars: Episode I  The Phantom Menace                                nan
1         Star Wars: Episode IV  A New Hope                                nan
2         Star Wars: Episode IV  A New Hope  Star Wars: Episode IV  A New Hope

>>> df.isin(answers)

      0      1
0  True  False
1  True  False
2  True   True

A: So the problem I had with the other solution is that, because of how it works, the code will not operate in the same way after the first time it is ran. I'm working in a Jupyter notebook so I want something I can run multiple times. I'm only a Python beginner, but the following code seems to be able to run multiple times and only change the values the first time it is ran:
cols = star_wars.columns[3:9]

# Booleans for column values
answers = {
        "Star Wars: Episode I  The Phantom Menace":True,
        "Star Wars: Episode II  Attack of the Clones":True,
        "Star Wars: Episode III  Revenge of the Sith":True,
        "Star Wars: Episode IV  A New Hope":True,
        "Star Wars: Episode V The Empire Strikes Back":True,
        "Star Wars: Episode VI Return of the Jedi":True,
        True:True,
        False:False,
        np.nan:False
        }

for c in cols:
    star_wars[c] = star_wars[c].map(answers)


text:
Q: Prove that $\displaystyle\tanh^{-1}(x)=\frac{1}{2}\ln\left(\frac{1+x}{1-x}\right)$ for $-1Prove that $\displaystyle\tanh^{-1}(x)=\frac{1}{2}\ln\left(\frac{1+x}{1-x}\right)$ for $-1<x<1$.
So far I have got $y=\tanh^{-1}(x)\Longleftrightarrow\tanh(y)=x$ .
Differentiating, $\displaystyle\tanh^{-1}(y)=x \Rightarrow \text{sech}^2(y)\cdot y'=1\Rightarrow y'=\frac{1}{\text{sech}^2(y)}=\frac{1}{\tanh^2(y)-1}=\frac{1}{x^2-1}$.
Stucked here.

A: The hyperbolic arctangent of $x$, $y=\operatorname{arctanh} x$, is the solution of $\tanh y=x$, i.e.
$$ \tanh y=\frac{e^y-e^{-y}}{e^y+e^{-y}}=\frac{e^{2y}-1}{e^{2y}+1}=x,\tag{1}$$
leading to:
$$ e^{2y} = \frac{x+1}{x-1}\tag{2}$$
so that:
$$\operatorname{arctanh} x = y = \frac{1}{2}\log e^{2y} = \frac{1}{2}\,\log\left(\frac{1+x}{1-x}\right).\tag{3}$$
As an alternative, since the hyperbolic arctangent is the inverse function of the hyperbolic tangent,
$$\frac{d}{dz}\operatorname{arctanh} z = \frac{1}{1-z^2} = \frac{1}{2}\left(\frac{1}{1+z}+\frac{1}{1-z}\right)=\frac{1}{2}\frac{d}{dz}\log\left(\frac{1+z}{1-z}\right) \tag{4}$$
and we just have to check that the RHS and LHS of $(3)$ match in $x=0$.


text:
Q: Initializer fails to determine size of character array Whenever I run the code below (Yes that's all the code) the compiler gives me an error:
error: initializer fails to determine size of 'path'
What I want to do is copy the contents of argv[0], which is the path of the application as a character array, into the path variable.
int main(int argc, char** argv) {
    int offset = 0;
    int pathSize = 0;
    while(argv[0][pathSize] != '\0')
        pathSize++;

    char path[] = new char[pathSize];
    delete &path;
    return 0;
}

A: First, char path[] should be char* path. Second, its delete[] path;. If you new[] you delete[] if you new you delete.
There is an extension for gcc (which is not standard mind you) which allows you to do this:
int main(int argc, char* argv[])
{
    int size = 34;
    char path[size];

    return 0;
}

However this will work only in gcc as this is a gcc extension.

A: Your error is in the below part of your code:
char path[] = new char[pathSize];
delete &path;

Change it to...
char *path = new char[pathSize];
delete[] path;

A: You should use a dynamic array.
char* path = new char[pathSize];

and as others have mentioned delete is only needed for new, therefore you do need it, but the way your code was written is not how you would normally want to use delete


text:
Q: synonym api Ajax call return Have struggled with this call for a while now but i can't get it to work. dataToReturn still returns Error and not the called data. What am i doing wrong?
function get_translation(search) {
    search = search.replace(/(<([^>]+)>)/ig, "").toLowerCase();
    original = search;
    google.language.translate( original ,  'en', 'sv',
    function(result) {
        translated = result.translation;
        $("#results").html('
'+ translated + '
')
    });
};

function get_synonyms(items) {

var dataToReturn = "Error";

$.ajax({
    url: 'http://words.bighugelabs.com/api/1/xxx/' + items+ '/json',
    type: 'GET',
    dataType: 'jsonp',
    async: false,
    cache: false,
    success: function(data) {

       dataToReturn = data;
    }
});

return dataToReturn;

}

$('#results').delegate("li", "tap", function(){
    myDate = new Date();
    displayDate = myDate.getDate() + "/" + myDate.getMonth()+1 + "/" + myDate.getFullYear();
    id = myDate.getTime();

    var wordObject = {'id' : id, 'date': displayDate, 'translated': translated, 'original': original, 'nmbr': "0", 'syn': get_synonyms('hello')};
    save_terms(wordObject);
    loopItems() ;
    $("#results").html("");
    $("#addField").val("");
    // location.reload(true);
});

A: It's because the return dataToReturn line is being executed before the AJAX call is complete. When you call $.ajax, the browser says, "Okay, I'll just move on to the next thing while I'm waiting for that to get back to me."
The simplest way to fix this would be to change the success function to actually do whatever it is you're trying to do with dataToReturn. But if that's not really feasible, then more context would help come up with a better answer.


text:
Q: C++ Passing a reference to an anonymous structure - can you? Using the structure shown below, I can use it like this for example.
NMEADecodedSentence s;
auto & gga = s.GGA;
auto alt = gga.Alt;

But is it possible to pass a reference to an anonymous structure to a function such as:
SomeFunc(gga);

If so, what would the function signature look like?  My thoughts are no you cant without naming the structures but I just wanted to know if there was some clever way of doing it that I didn't know!
struct NMEADecodedSentence
    {
        GNSSSentenceType Type;
        GNSSTalkerId TalkerId;
        union
        {
            struct
            {
                char Time[10];          // UTC time - hhmmss.ss
                char Lat[13];           // Latitude (degrees & minutes) - ddmm.mmmmm
                char NS;                // North/South indicator
                char Long[14];          // Longitude (degrees & minutes) - dddmm.mmmmm
                char EW;                // East/West indicator
                uint8_t Quality;        // Quality indicator for position fix
                uint8_t NumSV;          // Number of satellites used (0-12)
                float HDOP;             // Horizontal Dilution of Precision
                float Alt;              // Altitude above mean sea level - meters
            }GGA;
            struct // Recommended minimum data
            {
                char Time[10];          // UTC time - hhmmss.ss
                char Status;            // Status, V = Navigation receiver warning, A = Data valid
                char Lat[13];           // Latitude (degrees & minutes) - ddmm.mmmmm
                char NS;                // North/South indicator
                char Long[14];          // Longitude (degrees & minutes) - dddmm.mmmmm
                char EW;                // East/West indicator
                float Spd;              // Speed over ground - knots
                float COG;              // Course over ground - degrees
                char Date[7];           // UTC Date - ddmmyy
            }RMC;
            struct // Course over ground and ground speed
            {
                float COGT;             // Course over ground (true) - degrees
                float COGM;             // Course over ground (magnetic) - degrees
                float Kph;              // Speed over ground - kph
            }VTG;
        };
    };

A: You can do this, if compiler supports decltype feature (part of standard, but we all know how it goes..)
char foo2(decltype (NMEADecodedSentence::GGA) & param)
{
     return param.EW;
}

decltype is very useful for template building. NMEADecodedSentence::GGA as a name of non-static member of class is usable in this case.
Open template is usable, but is type unsafe, because you may try to offer anything that contains same fields used in function instead of NMEADecodedSentence::GGA.That can be a feature or a misfeature of architecture.
You can protect template like this:
#include <type_traits>

template<typename T>
char foo( T &a )
{
  static_assert(std::is_same<T,decltype (NMEADecodedSentence::GGA)>::value ||
                std::is_same<T,decltype (NMEADecodedSentence::RMC)>::value,
                "Wrong type of foo() argument" );
  return a.EW;
}

static_assert would produce a compile time error (that's why it is "static"), if you provide foo with argument of different type: std::is_same<>::value would be false.
Note, that you can do this as well:
struct  GGAType : public decltype (NMEADecodedSentence::GGA)
{
};

but aforementioned template will not accept argument of this type without a fix  to the static_assert expression. foo2() would work.

A: This should work:
void f(decltype(NMEADecodedSentence::GGA)& gga)
{
    ...
}


text:
Q: How to iterate over an object and get the correct keys with jQuery I have the following object:
{
  "1":{
    "ProductType":"car",
    "ProductId":"1",
    "Brand":"Tesla",
  },
  "2":{
    "ProductType":"car",
    "ProductId":"2",
    "Brand":"Ferrari",
  }
  etc...
}

Now i need to create a loop that iterates through the object, and i need the product id and the brand and display those. How do i do that?
I have looked at dozens of stack overflow questions and i don't find any that are about exactly my use case.

A: If you want to do this using jQuery, you're looking for jQuery.each().

var data = {
  "1":{
    "ProductType":"car",
    "ProductId":"1",
    "Brand":"Tesla",
  },
  "2":{
    "ProductType":"car",
    "ProductId":"2",
    "Brand":"Ferrari",
  }
}

$.each(data, function(i, obj) {
  console.log(i+': '+obj.ProductType+' | '+obj.ProductId+' | '+obj.Brand);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: Why won't the output be 4 in this case? #include <stdio.h>
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    int *p = arr;
    ++*p;
    p += 2;
    printf("%d", *p);
    return 0;
}

The precedence of prefix ++ is greater than dereferencing, and hence, p should now point to the second element. And therefore, when we add 2 to it, it should point to the 4th element and answer should be 4. But, the answer is 3, why is that?

A: In the expression like ++*p precedence does not play any role at all. In this expression the inner operator applies to p (* in this case). The outer operator (++) applies to the result of the inner operator.
If you swap them around to obtain *++p, then ++ will apply to p, while * will apply to the result of ++p.
Every time you have a bunch of unary/postfix operators sitting together on the same side of the operand, they apply in the inside-out order.
For a right-hand side example, in p++[i] operator ++ applies to p and [i] applies to the result of p++. Meanwhile, in p[i]++ operator [i] applies to p and ++ applies to the result of p[i].
Precedence begins to play its role in "ambiguous" cases like:

*

*Unary/postfix operator vs. binary operator, e.g.
*p + 2

In the above case unary * has higher precedence than binary +, resulting in (*p) + 2.
p->i / 5

Here postfix -> has higher precedence than binary /, resulting in (p->i) / 5.
And in general unary/postfix operators have higher precedence than binary operators.

*Unary vs. postfix operator, i.e. operators on both sides of the operand, e.g.
*p++

In the above case postfix ++ has greater precedence than unary *, resulting in *(p++).
&p->i

Here postfix -> has greater precedence than unary &, resulting in &(p->i).
And in general postfix operators have higher precedence than unary operators.

*Various more "exotic" cases like ?: operator...

A: There is no issue with precedence in the expression ++*p because there is no ambiguity to resolve. The operators are applied outwards from the operand. That is to say, *p is applied first, and ++ is applied to the result of that expression. The language doesn't allow for one operator to leapfrog in front of another.
Precedence rules would matter in the case where both operators could apply to the same operand, for example
*p++

This is not the case in your example.
Concerning the result, the increment does not affect p, which remains pointing to the first element of arr until you increment it with p += 2;. That makes p point to arr[2], which has value 3.

A: p starts off pointing to the first element, arr[0].
In the prefix-++ operation, the element that p points at (*p, or arr[0]) is incremented, arr[0] now contains 2 instead of 1. The pointer itself doesn't change.
p (the pointer, not the element that it points to) is then incremented by 2, so p points to arr[2]... which has a value of... 3.

A: Because the first operation first dereference and then increments the one.
The other operation increments the index from 0 to 2.
If you output arr[0] you see that the value was incremented.
See the precendence of the operator ++(prefix) and *(dereference).
They have the same precendence and are in the same cell. Regarding to the
Right-to-Left associativity. They are evaluated like this:
++(*p)

Operators that are in the same cell (there may be several rows of
  operators listed in a cell) are evaluated with the same precedence, in
  the given direction. For example, the expression a=b=c is parsed as
  a=(b=c), and not as (a=b)=c because of right-to-left associativity.

Working Example:
#include <stdio.h>
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    int *p = arr;
    ++*p;
    p += 2;
    printf("%d", *p);
    printf("%d", arr[0]);
    return 0;
}

Output:
32

http://ideone.com/6Xlt5N

A: Let me put the answer down:
++*p

first dereferences then increments value
*++p

increments pointer address then dereferences.

A: If you change the program to a bit more verbose mode :
#include <stdio.h>

int main()
    {
      int arr[] = {1, 2, 3, 4, 5};
      int *p = arr;
      printf("\n1- %p",p);
      ++*p;
      printf("\n2- %d",arr[0]);
      printf("\n3- %p",p);
      p += 2;
      printf("\n4- %p",p);
      printf("\n5- %d", *p);
      return 0;
    }

You will get the following output :
1- 0x7fff9fc53e30
2- 2     // changed the value pointer points to
2- 0x7fff9fc53e30  // pointer stays the same
3- 0x7fff9fc53e38
4- 3

A: Precednce resolves the operation order when two operatos can associate to the same operand. For example in 2*x+7 the precedence of * over + resolves the order of calculation as multiplication before addition: (2*x)+7.
In your case only one operator applies to p, and it is a dereference operator: *p. The pre-increment operator works on the dereferenced l-value: ++(*p) so precedence has nothing to do here.

A: About your question, the code ++*p is the value *p+1, not the address which p point to. The correct code is ++p. I hope this can help you.


text:
Q: SQL: Turning a single set of results into a table I've created a T-SQL query which counts all of the students who are at a lesson at specific times, for each day of the week (below).  Is there a way of taking this query(which gives a snapshot) and displaying results for a variety of different '@time' variables so I can get a table which looks something like:
Day 09:00  09:30..... etc
1   300    455
2   43     467
3   21     312

The increment in time along the columns would be constant - and ideally adjustable, but if that's needlessly complex, every 30 mins would probably be optimum.
Query:
DECLARE @time AS VARCHAR(5)

SELECT @time = '09:00'

SELECT A.day_of_week,
    A.Sum(count_student) AS Students
FROM (
        SELECT sttrgprf.register_id,
    sttrgprf.day_of_week,
    CONVERT(VARCHAR(5), start_time, 108) AS start_time,
    CONVERT(VARCHAR(5), end_time, 108) AS end_time,
    Count(DISTINCT Student_ID) AS count_student
FROM qlsdat.dbo.Stthstud
    INNER JOIN qlsdat.dbo.Sttrgprf AS Sttrgprf
        ON Stthstud.register_id = Sttrgprf.register_ID
            AND Stthstud.register_group = Sttrgprf.register_group
            AND Stthstud.acad_period = Sttrgprf.acad_period
WHERE sttrgprf.Acad_period = ''14/15''
GROUP BY sttrgprf.register_id,
    sttrgprf.day_of_week,
    sttrgprf.start_time,
    sttrgprf.end_time
    ) AS A
WHERE Start_time <= @time
    AND End_time > @time
GROUP BY day_of_week
ORDER BY day_of_week


text:
Q: Google Mock Return a live element using ON_CALL I read through Google Mock: Return() a list of values and found out how to return a single element from a vector on each EXPECT_CALL, as such I wrote the following code which works:
    {
      testing::InSequence s1;
        for (auto anElem:myVecCollection) {
          EXPECT_CALL(myMockInstance, execute())
              .WillOnce(testing::Return(anElem));
        }
    }

so far so good...
Now I read not to use EXPECT_CALL unless you need to. https://groups.google.com/forum/#!topic/googlemock/pRyZwyWmrRE
My use case, myMockInstance is really a stub providing data to the SUT(software under test).
However, a simple EXPECT_CALL to ON_CALL replacement will not work(??), since ON_CALL with WillByDefault only calculates the return type only once(??)
As such I tried setting up an ACTION.
ACTION_P(IncrementAndReturnPointee, p)
{
    return (p)++;
}

ON_CALL(myMockInstance, execute())
        .WillByDefault(testing::Return
         (*(IncrementAndReturnPointee(myVecCollection.cbegin()))));

Clang gives
error: expected expression   'ACTION_P(IncrementAndReturnPointee, p)'

Then I tried setting up a functor and use the Invoke method on it.
    struct Funct
    {
      Funct() : i(0){}

      myClass mockFunc(std::vector<myClass>  &aVecOfMyclass)
      {
        return aVecOfMyclass[i++];
      }

      int i;
    };

    Funct functor;
    ON_CALL(myMockInstance, execute())
        .WillByDefault(testing::Return(testing::Invoke(&functor, functor.mockFunc(myVecCollection))));

Clang gives
no matching function for call to 'ImplicitCast_'
        : value_(::testing::internal::ImplicitCast_<Result>(value)) {}

Now , I am fairly new to google-mock but have used google-test extensively.
I am a bit lost with the Google-Mock doc. I wanted to know, whether I am on the right path, in terms of what I needed.
If one of you could point to me , which approach is the correct one; or whether I am even close to the right approach, I can take it from there and debug the "close to right approach" further.
Thanks

A: testing::Return is an action. Your code should look like:
ACTION_P(IncrementAndReturnPointee, p)
{
    return *(p++);
}

ON_CALL(myMockInstance, execute())
     .WillByDefault(IncrementAndReturnPointee(myVecCollection.cbegin()));

As a side note, it doesn't look like a good idea to use a finite collection myVecCollection. You will probably get a more robust test if you figure out an implementation of the action that creates a new element to return on the fly.


text:
Q: Simultaneous substitutions with s/// in Perl 6 Is there a way to do simultaneous substitutions with s///? For instance, if I have a string with a number of 1s, 2s, 3s, etc, and I want to substitute 1 with "tom", and 2 with "mary", and 3, with "jane", etc?
my $a = "13231313231313231";
say $a ~~ s:g/1/tom/;
say $a ~~ s:g/2/mary/;
say $a ~~ s:g/3/jane/;

Is there a good way to do all three steps at once?

A: The simplest way it probably to make a Map of your substitutions and then reference it.
my $a = "123123";
my $map = Map.new(1 => "tom", 2 => "mary", 3 => "jane");
$a ~~ s:g/\d/$map{$/}/;
say $a
"tomemaryjanetommaryjane"

If you only want to map certain values you can update your match of course :
my $a = "12341234";
my $map = Map.new(1 => "tom", 2 => "mary", 3 => "jane");
$a ~~ s:g/1 || 2 || 3/$map{$/}/;
say $a
"tomemrayjane4tommaryjane4"

A: For replacements like your example, you can use trans.  Provide a list of what to search for and a list of replacements:
my $a = "13231313231313231";
$a .= trans(['1','2','3'] => ['tom', 'mary', 'jane']);
say $a;
tomjanemaryjanetomjanetomjanemaryjanetomjanetomjanemaryjanetom

For simple strings, you can simplify with word quoting:
$a .= trans(<1 2 3> => <tom mary jane>);


text:
Q: Uploaded file integrity check with Azure Datalake Gen1 WE are uploading a lot of files to Azure Datalake Gen1.
and one question came up that how do we check if the file is not corrupted or hampered during upload.
how do i check the file i uploaded is the same file that has been added into datalake?
are there any libraries to do this integrity chek?
or is ADLUploader provides any thing for this?
is there any other way to achieve the same thing?


text:
Q: Postgres compound index effectiveness with a given column list Let's say I have a compound index involving these 3 columns.
(name, email, phone)

Is this index still will be used for these queries? The first query involves just 2 of indexed fields and the second index using more then all of the fields. By the way, which index type is most suitable for this?
SELECT * FROM person WHERE emails = 'xxx@email.com' AND phone = '012645678'

and
SELECT * FROM person WHERE name = 'dude' AND emails = 'xxx@email.com' AND phone = '012645678' AND title = 'CEO'

A: For a typical b-tree index should be used for the second query (perhaps depending on table statistics).  In general, indexes are used from "left to right", with equality conditions in the where.  The first query has no condition on name.
No single index is optimal for both queries, but a an index on (emails, name) would probably do well.
Note also that phone numbers are usually stored as strings.  Your comparison is to a number.  Type conversions can affect the use of indexes.


text:
Q: Unable to use onClickListener inside fragment I am trying to fire an OnclickListener inside the fragment to perform some task in the parent activity. But for some reason, the code inside the listener method has no effect. Neither toast nor Log is displaying. I am not quite sure how to attach the listener to the button so when implementing the View.OnclickListener interface so maybe I missed something there. Please help.
Parent Activity:
package app2.tarun.com.fragments2;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AdminPanel extends AppCompatActivity implements
FragmentChangePassword.OnButtonClickedListener{

private String password, c_password;
EditText et_password, et_c_password;
DataBaseHelper db;
Button btn_change_password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    setContentView (R.layout.admin_panel);
    btn_change_password = findViewById (R.id.btn_changePassword);
    et_password =  findViewById (R.id.admin_input_password);
    et_c_password =  findViewById (R.id.admin_input_reEnterPassword);
    db=  new DataBaseHelper (this);

}

public void changeFragment(View view) {
    Fragment fragment;

    if (view == findViewById (R.id.register)) {
        fragment = new FragmentRegisterUser ();
        FragmentManager fm = getSupportFragmentManager ();
        FragmentTransaction ft = fm.beginTransaction ();
        ft.replace (R.id.fragment, fragment);
        ft.commit ();
    }

    if (view == findViewById (R.id.change_password)) {

        Log.e("mmmmmmmmmm","ssssssssss");
        Toast.makeText (this, "Hello", Toast.LENGTH_LONG).show ();

        fragment = new FragmentChangePassword ();
        FragmentManager fm = getSupportFragmentManager ();
        FragmentTransaction ft = fm.beginTransaction ();
        ft.replace (R.id.fragment, fragment);
        ft.commit ();
    }

}

@Override
public void onButtonClicked() {
    Log.e("mmmmmmmmmm","ssssssssss");
    Toast.makeText (this, "vdsfds", Toast.LENGTH_LONG).show ();
    password = et_password.getText ().toString ();
    c_password = et_c_password.getText ().toString ();
    if (password.equals (c_password)) {
        db.changePassword (password);
        finish ();
    } else
        Toast.makeText (this, "vdsfds", Toast.LENGTH_LONG).show ();
}

}
Fragment Activity:
package app2.tarun.com.fragments2;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class FragmentChangePassword extends Fragment implements View.OnClickListener {

OnButtonClickedListener mCallback;
Button btn_change_password;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    return inflater.inflate(R.layout.fragment_fragment_change_password, container, false);

}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated (view, savedInstanceState);

    mCallback = (OnButtonClickedListener) getActivity ();
    btn_change_password = getActivity ().findViewById (R.id.btn_changePassword);

}

@Override
public void onClick(View view) {
    Log.e("mmmmmmmmmm","ssssssssss");
    if(view.getId ()==R.id.btn_changePassword) {
        mCallback.onButtonClicked ();
    }
}

public interface OnButtonClickedListener {
    void onButtonClicked();
}

}

A:
I am not quite sure how to attach the listener to the button so when implementing the View.OnclickListener interface so maybe I missed something there

When you're implementing the View.OnclickListener on the Fragment, you also need to set the listener to the View.
You need to do something like this:
btn_change_password.setOnClickListener(this);

this is referring the the Fragment which is already implementing the View.OnclickListener
In case of your Activity, I suspect that you're using android:onClick in the XML for the Activity. So, when you have something like this in your XML:
<Button
    ...
    android:onClick="changeFragment">

</Button>

Your click will work because you have the following method in your Activity:
public void changeFragment(View view) {
  ...
}


text:
Q: A style intended for type 'MenuItem' cannot be applied to type 'Separator' I'm working on WPF Window Application which uses ContextMenu.
My ContextMenu in XAML (in Window.Resources):
<ContextMenu x:Key="menuList" Placement="Bottom" >
    <ContextMenu.ItemContainerStyle>
        <Style TargetType="{x:Type MenuItem}">
            <Setter Property="Header" Value="{Binding Name}"/>
            <EventSetter Event="Click" Handler="cm_RefreshChannelNotification"/>
            <Setter Property="IsChecked" Value="{Binding CFiltered}" />
            <Setter Property="IsCheckable" Value="True"/>
            <Setter Property="StaysOpenOnClick" Value="True"/>
        </Style>
    </ContextMenu.ItemContainerStyle>
</ContextMenu>

When I try to add Separator to the ContextMenu I receive error:

System.InvalidOperationException was unhandled
    Message="A style intended for type 'MenuItem' cannot be applied to type 'Separator'.

In this way I must add a new separator:
ContextMenu cm = this.FindResource("menuList") as ContextMenu;
Separator separator = new Separator();
separator.SnapsToDevicePixels = true;
cm.Items.Add(separator);

What should I change/add in ContextMenu definition to make it work?

A: You can move the style to the ContextMenu.Resources, this applies it implicitly to the menu items which will not conflict with the Separators.

An alternative may be to drop the TargetType and qualify the properties, non-applying properties might be ignored. Never did this myself though:
<Style>
    <Setter Property="MenuItem.Header" Value="{Binding Name}"/>

A: One Adition to H.B.'s answer. Both ways are working for me.
However, setting MenuItem.Header property will result in an binding error in output window, which you could ignore of course.

So in my opinion move the style to the ContextMenu.Resources is the better option.
Sorry I can't write this as comment yet.

A: You might need to use an ItemContainerStyleSelector. You have multiple types in your ContextMenu both MenuItem and Separator. Although one would expect WPF to apply it to the  TargetType only and be able to supply multiple styles one for each targettype.
I encountered a similar issue with derived container types and needed to override GetContainerForItemOverride and IsItemItsOwnContainerOverride.


text:
Q: Bayesian Estimation of CDF i'm getting pretty confused by the following problem, hope anyone can clarify my mind:
Using a  bayesian approach obtain a posteriori and interval estimations for $\mathbf{F}_{X}(x)$ using a Uniform(0,1) prior distribution for the parameter $\theta$(x) for a given sample $x_1,x_2, \cdots, x_n$
I have knowledge of Bayesian Statistics, and i know that the CDF is actually a Uniform(0,1) random variable.
But still this kinda confusing for me, given that a point estimate for the $F_X(x)$ under the frequentist aproach would be the Empirical Distribution $F_N(x)=\frac{1}{N}\sum_{i=1}^NI(X_i \leq x)$, but it´s obvious that this would no be the case for bayesian approach.
And even what does it could mean have the same prior distribution that the one from the model (both prior and $F_X(x)$ are $U$~$(0,1)$
After all is just a product of the Likelihood and the prior (over the integral that makes this integrate one)
\begin{align}
p(\theta\mid X)&\propto p(X\mid\theta)p(\theta) \\
\end{align}
So are my thoughts correct about   $p(X\mid\theta)$ being the likelihood of an $U$~$(0,1)$? And it´s not kinda silly take the same distribution as prior?

A: The random variables $Z_i:=\mathbb{1}_{\{X_i\,\in\,B\}}$ for $i\in\{1,\ldots,n\}$ are i.i.d $\text{Bernoulli}$ with unknown parameter $\theta=\mathbb{P}(X\in B).$ Using a $\text{Uniform}(0,1)$ non-informative prior distribution for $\theta$ the posterior distribution is $\text{Beta}(1+nT_n(B),1+n(1-T_n(B))).$ Under a quadratic loss penalization, the bayesian point estimate for $\theta=\mathbb{P}(X\in B)$ is the posterior expected value which is the following:
$$\theta^* \,=\, \frac{1+nT_n(B)}{2+n}$$


text:
Q: Need help creating a tree diagram from with world problem. Can someone create a tree diagram to model this chance process,
Morris kidneys are dialing and he is awaiting a kidney transplant. His doctor gives him the following information for patients in his condition that survive the transplant. The transplant succeeds 75% of the time, and the other 25% do not have successful transplant, 90% that survive the next 5 years. Of those with an unsuccessful transplant and are on dialysis, 55% survive the next 5 years.


text:
Q: scripting system preference display settings How to set System Preferences-> Display -> Scaled -> More Space with the help of AppleScript?
I got till:
    tell application "System Events"
        tell process "System Preferences"
            set frontmost to true
            click button "Displays" of scroll area 1 of window "System Preferences"
            click radio button "Scaled" of radio group 1 of tab group 1 of window "Built-in Retina Display"

But not sure how to set the " More Space" option?
TIA

A: try this:
tell application "System Preferences"
     reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
end tell

tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
    click radio button "Display" of tab group 1
    click radio button "Scaled" of radio group 1 of tab group 1
    click radio button 4 of radio group 1 of group 2 of tab group 1
end tell
quit application "System Preferences"

A: A small command line script to change screen resolutions on macOs Sierra
#!/usr/bin/osascript
tell application "System Preferences"
        reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
    end tell

    tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
        click radio button "Display" of first tab group
        click radio button "Scaled" of first radio group of first tab group
        tell first radio group of second group of first tab group
            set isDefault to get value of second radio button
        end tell
        if isDefault then
            click last radio button of first radio group of second group of first tab group
        else
            click second radio button of first radio group of second group of first tab group
        end if
    end tell

    tell application "System Preferences"
        quit
    end tell


text:
Q: Update TFS Sprint Burndown Chart Retroactively Can I update the TFS chart retroactively?
Assume it is Wednesday, and I want to update TFS Work Item (Eg. the remaining hours) for Monday and Tuesday and the TFS Scrum Burndown Chart to reflect this.
Is there a way how to do that? Either from within Visual Studio, TFS Web Access or at least programmatically through TFS API?

A: No, this is not possible and if you achieve that, it is not officially supported. I have not find any way to modify it using VS, Web, Excel, Project nor API.
Time-machine
It is possible to change date of server where TFS is running and then manipulate Work Items.  I was able to increase the curve (useful when preparing demo data).

*

*Backup.

*You may need to stop sync of clock.

*Change a date on TFS server.

*Manage work items (e.g. using Web Access).

*

*You will find that system doesn't allow you to change values of "work items from future", so you will need to create new work items.

Drity SQL job
For sure, it is possible to change data directly in SQL.

*

*Backup. Don't work directly on production because you can hurt TFS a lot.

*Connect to TFS SQL database and look around a dbo.WorkItemsWere table.

*Ensure you really want to get database into unsupported state. (See Michael Ruminer's answer.)

API
It is not possible to influence Burn-down chart retroactively using TFS API.
Event if it is possible to modify field "System.CreatedDate" of work item, it is not possible to change "Microsoft.VSTS.Scheduling.StartDate" and "System.AuthorizedDate" which seems to be used for calculation of graph (work item field reference).
More information you can find in Tarun Arora's post and Richard Hundhausen's blog.


text:
Q: How to set X-Frame-Options header without a custom server in Next.js? I have a NextJS app that I need to set X-Frame-Options on, but I'm not sure how to do this. With Express, I would use helmetjs, but I want to avoid creating a custom server because:

Before deciding to use a custom server please keep in mind that it
should only be used when the integrated router of Next.js can't meet
your app requirements. A custom server will remove important
performance optimizations, like serverless functions and Automatic
Static Optimization.

Source: https://nextjs.org/docs/advanced-features/custom-server
Clearly, there are some drawbacks to using a custom server, and the page handler provided by Next works for me.

A: Without a custom server, this could be achieved by using custom headers in your next.config.js.
// next.config.js
module.exports = {
    async headers() {
        return [
            {
                source: '/(.*)?', // Matches all pages
                headers: [
                    {
                        key: 'X-Frame-Options',
                        value: 'DENY',
                    }
                ]
            }
        ]
    }
}


text:
Q: Use TPM for signing on Windows without taking ownership I have a follow-up question of sorts to this question: How to encrypt bytes using the TPM (Trusted Platform Module)
I am using Windows 10 for an embedded solution. I would like to use the TPM to store signing keys and perform signatures. However, I do not want to interrupt Windows' ability to using the TPM for secure booting...therefore, I am hesitant to take ownership of the TPM. I have played around with the TSS.NET code samples, and have gotten the TPM to sign data with a blank AuthValue (with a real TPM, not a simulator). But I am not sure what the limitations are here. The TSS.NET sample code has a comment:

If running on a real TPM, which has been provisioned by Windows, this value will be different. An administrator can retrieve the owner authorization value from the registry.

So my question is in two parts:

*

*When provisioning, am I correct that changing the TPM owner password is ill advised?

*Is it possible to obtain the password in code?

*If I don't have the owner authorization when deploying a device, will I be able to install signing keys?

*If don't have the owner authorization at run time, will I be able to use the TPM for signing?


text:
Q: inline svg: make image width fit its content Consider the code below. Am I able to make the two inline svg's fit their respective text content? I.e. "Teststring. Lorem." should be longer and "foo" shorter. I need two identical svg's with the content text being the only difference. Currently they have a static width of 50px.
I know that I could achieve this easily via HTML+CSS, but in my real world scenario I need SMIL animations behind a text and this is the easiest way to do it. I already have (more complicated) alternatives, so that is not what I want. I just want to know if this is possible and if so how. So "it cannot work at all, try something different" would be a valid answer. (Although not something I hope for.)

<svg width="50" height="20" viewBox="0 0 50 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
 <foreignObject x="0" y="0" width="50" height="20">

   Teststring. Lorem.

 </foreignObject>
 <rect x="0" y="0" width="50" height="20" fill="rgba(0,0,0,.3)"></rect>
</svg>

<svg width="50" height="20" viewBox="0 0 50 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
 <foreignObject x="0" y="0" width="50" height="20">

   foo

 </foreignObject>
 <rect x="0" y="0" width="50" height="20" fill="rgba(0,0,0,.3)"></rect>
</svg>

A: I'm not sure if the following is the right way to do this, but it works.
Explanation of the solution
The text inside the svg is wrapped in a span tag. In the onload event the width of the svg tag is set to the width of that span element that is measured via javascript. Unfortunately you have to set an individual id for the svg tag and adjust the id string in the first line of the javascript code accordingly.
Setting the new width
Also you need to set the new width to all relevant elements in the svg. Which could become a bit ugly if you have lots of elements.
A possible shortcut could be a group element whose transform attribute is manipulated. This would scale the group's content to the correct size while preserving the propertions. Something like the following:
//javascript
thisSvg.getElementsByClassName('group')[0].setAttribute(
    'transform', 'scale('+textWidth/50+')');

<g class="group">
    <rect x="0" y="0" width="50" height="20" fill="rgba(0,0,0,.3)"></rect>
    <rect x="0" y="0" width="25" height="20" fill="rgba(1,0,0,.3)"></rect>
</g>

The actual solution

<svg id="custom-id-1" width="50" height="20" viewBox="0 0 50 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="
  var thisSvg = document.getElementById('custom-id-1');
  var box = thisSvg.getElementsByClassName('text')[0].getBoundingClientRect();
  var textWidth = box.right-box.left;
  thisSvg.setAttribute('viewBox', '0 0 '+textWidth+' 20');
  thisSvg.setAttribute('width', textWidth);
  thisSvg.getElementsByClassName('foreign')[0].setAttribute('width', textWidth);
  thisSvg.getElementsByClassName('rect')[0].setAttribute('width', textWidth);
">
 <foreignObject class="foreign" x="0" y="0" width="50" height="20">

   Teststring. Lorem.

 </foreignObject>
 <rect class="rect" x="0" y="0" width="50" height="20" fill="rgba(0,0,0,.3)"></rect>
</svg>

<svg id="custom-id-2" width="50" height="20" viewBox="0 0 50 20" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="
  var thisSvg = document.getElementById('custom-id-2');
  var box = thisSvg.getElementsByClassName('text')[0].getBoundingClientRect();
  var textWidth = box.right-box.left;
  thisSvg.setAttribute('viewBox', '0 0 '+textWidth+' 20');
  thisSvg.setAttribute('width', textWidth);
  thisSvg.getElementsByClassName('foreign')[0].setAttribute('width', textWidth);
  thisSvg.getElementsByClassName('rect')[0].setAttribute('width', textWidth);
">
 <foreignObject class="foreign" x="0" y="0" width="50" height="20">

   foo

 </foreignObject>
 <rect class="rect" x="0" y="0" width="50" height="20" fill="rgba(0,0,0,.3)"></rect>
</svg>


text:
Q: jQuery mousewheel detect scroll up and down I have a few sections (each of size 100% x 100% - Fullscreen), which are fixed and overlapped on top of one another using z-index. I want to detect the mouse scroll and display respective sections using jQuery (Basically, something like fullpage.js but I will have different animations). I read many questions and tried the following code, but doesn't work.
Javascript:
$(document).ready(function(){
    sections=["intro","features","gallery","contact"]
    cs=0;
    $(window).on('mousewheel DOMMouseScroll', function(e){
        if(e.originalEvent.detail > 0) {
            //scroll down - Show next section
            if(cs < (sections.length-1)){
                $("#"+sections[cs]).fadeOut();
                cs+=1;
                $("#"+sections[cs]).fadeIn();
            }
        }
        else{
            //scroll up - Show previous section
            if(cs > 0){
                $("#"+sections[cs]).fadeOut();
                cs-=1;
                $("#"+sections[cs]).fadeIn();
            }
        }
        return false;
    });
});

HTML:

Intro

Features

Gallery

Contact Us

To see the whole code, in case you need it, visit github

A: So I checked the behaviour in a jsfiddle https://jsfiddle.net/oobmky4n/ and basically your problem seems to be that
e.originalEvent.detail

is always 0 and instead you want to use
e.originalEvent.deltaY

I only tested it in safari for now but it seems to work. Also seems to be reflected by https://developer.mozilla.org/en-US/docs/Web/Events/wheel
Addition to stop during a continuous scroll:
A possible solution is a flag with a timeout. I updated my original here: https://jsfiddle.net/oobmky4n/2/
As you can see we set isScrolling once a successful scroll happened. After 250ms of not scrolling while the flag is set we revert back to a non-scrolling state.
 if(isScrolling) {
    clearTimeout(resetScroll)
    resetScroll = setTimeout(function() {
        isScrolling = false
    }, 250);
  }


text:
Q: shuffle two consecutive blocks of data I have data file (php) with 24 blocks of data, structured as below.
//ts1
$P[] = [0];
$S[] = [[1,95.8172406762736],[2,104.97526726371],[3,112.03839938973],[4,101.70457396977],];
$F[] = [];
$FB[] = [];
//ts2
$P[] = [0];
$S[] = [[1,103.190939795922],[2,105.297198378469],[3,105.829786652111]];
$F[] = [];
$FB[] = [];
//ts3
$P[] = [0];
$S[] = [[1,107.285278217373],[2,103.557795069809],[3,105.686758569246],[4,103.748341353355]];
$F[] = [];
$FB[] = [];

I need to shuffle the first 12 blocks and then shuffle block 13-24. The code I have does not appear to work as it still shuffles all 24 blocks at once. I'm not sure how it should be written otherwise..
// DATA INITIALISATION
// - Reads all data sets from server
// - Generates list of objects
// - Randomises list of objects
function DataInit1()
{
    SeriesList = [];
    CurrentGraph.Series = 0;

    // load all the data sets from server
    $.getJSON("datademo.php",
        function(Data1)
        {
            for(var i=0; i<Data1.length; i+=4)
            {
                var P = Data1[i+0];
                var S = Data1[i+1];
                var F = Data1[i+2];
                var FB = Data1[i+3];
                var NewSeries = new SeriesClass(P,S,F,FB);
                NewSeries.SeriesNumber = (i/4)+1;
                SeriesList.push(NewSeries);
            }
        }
    );
// shuffle each of the series lists to a random order
    s1 = SeriesList.length/2;
    s2 = SeriesList.length;
    for(var i=0; i<s1; i++)
    {
           var j = Math.floor(Math.random() * (i+1));
           var x = SeriesList[i];
           SeriesList[i] = SeriesList[j];
           SeriesList[j] = x;
         }
    for(var i=s1; i<s2; i++)
    {
           var j = Math.floor(Math.random() * (i+1));
           var x = SeriesList[i];
           SeriesList[i] = SeriesList[j];
           SeriesList[j] = x;
         }
    }

edit: I've changed it now to the following (not pretty but I don't have time to tidy it). Now it randomizes series 1-12, but series 13-24 is now not randomized. I don't code that often and I can't see why it would work in the first bit but not the second one.
// shuffle the series list to a random order
    for(var i=SeriesList.length-13; i>0; i--)
    {
        var j = Math.floor(Math.random() * (i+1));
        var x = SeriesList[i];
        SeriesList[i] = SeriesList[j];
        SeriesList[j] = x;
    }
        for(var i={from: 12, to: 23}; i>0; i--)
    {
        var j = Math.floor(Math.random() * (i+1));
        var x = SeriesList[i];
        SeriesList[i] = SeriesList[j];
        SeriesList[j] = x;
    }

A: I think the easiest way is to break it into two arrays, shuffle them separately, then push them back together. I've used the shuffle method from this question: How can I shuffle an array?, and the method of joining arrays from How to extend an existing JavaScript array with another array, without creating a new array?
See the fiddle at https://jsfiddle.net/u25ta64x/1/
var SeriesList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26];

var firstHalf = SeriesList.slice(0,13);
var secondHalf = SeriesList.slice(13,26);

function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

shuffle(firstHalf);
shuffle(secondHalf)
var shuffledList = firstHalf;
Array.prototype.push.apply(shuffledList, secondHalf);

console.log(shuffledList);


text:
Q: 'Supposed to' sentence structure
He was not supposed to do that.

'Supposed' is a Participial Adjective then how 'to do that' Infinitive clause is working here.
It doesn't look like a catenative structure too.
And how is 'supposed' a Participial Adjective not a passive structure of simple past Tense?

A: He was not supposed to do that.

Q 1. 'Supposed' is a Participial Adjective then how 'to do that' Infinitive clause is working here. It doesn't look like a catenative structure too.

Q 2. And how is 'supposed' a Participial Adjective not a passive structure of simple past Tense?

A 1. I think you will find you are splitting the words in the wrong way.
He was not (Intended/expected) to,(Perform) that

In this case the adjective "supposed to" is used to indicate what something is likely or intended to do.Grammarly

Supposed to is part of a modal verb phrase. "To be supposed to do something implies" that the subject is obligated and expected to do the main verb's action, although there is a possibility it won't happen.
To be supposed to is a common phrase that functions the same way a modal verb does. Modal verbs, also called auxiliary or helping verbs, add meaning to the main verb in a sentence by expressing possibility, ability, permission, or obligation. Supposed to, like have to, can fall into the "obligation" category.

It can also be used to indicate what a person (or thing) is likely to do or is reputed to do. Whenever it is used in either of these senses, supposed to will be preceded by a form of to be and followed by a verb.

do; verb; did | done: do verb (PERFORM) to** perform, take part in, or achieve something**: Ref CED
Example

"That was a really stupid thing to do"

Note In this case "that" is used as a pronoun.

And how is 'supposed' a Participial Adjective not a passive structure of simple past Tense?

A 2. It is Past tense. He did something in the past and "that" is the result and we are talking about "that" in the present. However 'be supposed to' the modal verb phrase can be used in past present and future tenses.
Examples

Present / Future - We are supposed to meet them here.

PAST - We were supposed to meet here.

Also Note

The confusion over using multiple verb tenses in one sentence probably arises because we have heard that we need to maintain verb tense consistency. These two things are different.

Tense Consistency – We do not switch one tense to another unless the timing of the action demands that we do. We do not switch tenses when there is no time change for the actions.
Ref Use of multiple tenses

References

supposed adjective (INTENDED); be supposed to; to be intended to: Ref CED

These batteries are supposed to last for a year.

do; verb; did | done: do verb (PERFORM) to perform, take part in, or achieve something: Ref CED

A:
He was not [supposed to do that].

The important thing here is that "supposed" is not a verb but an adjective with the infinitival clause "to do that" as its complement. The whole AdjP "supposed to do that" is then predicative complement of "was".
The fact that "supposed" is not a verb rules out a passive interpretation, as well as this being a catenative construction.
Notes:

*

*the participial adjective "supposed" has developed a specialised meaning expressing medium deontic modality.

*the negative marker "not" is part of the matrix clause (not the subordinate one), where it is interpreted as marking internal negation.
Below is a simplified tree diagram.


text:
Q: Sublime Text Package Control - Get More Information Is it possible to get more information about the plugin/extension in the Package Control in Sublime Text?
I use the shortcut ctrl + shift + p to bring package control and Install Packages. The information is about two lines per package. Is it possible to get more information so that I can know  before I install it?

A: Use the Package Control website. You can search for packages in a number of ways, and view their associated README documents. Other information provided includes version compatibility, links to source on Github or other repositories, links to issues, the ability to donate to the author, package popularity information, including a graph of the number of recent installs, and other details.


text:
Q: Learning openGL on the mac: GLUT or native windowing system? I'm starting to learn openGL on the mac, and being a cocoa developer already I find the native windowing system to be very appealing.
The books I'm reading all mentions the use of GLUT. Now, I'm wondering what the majority of people use for developing opengl programs, or if it's just a matter of taste.

A: Generally (Free)GLUT is not used for developing actual applications. It's used for demoing effects or simple things, which is why so many online materials use it. It takes all the cross-platform stuff and shoves it into a corner, thus focusing the user's attention on OpenGL.
GLUT owns the message processing loop. For simple applications, that's fine. But for most real programs, you will need to control message processing on your own. So GLUT fails. Also, GLUT doesn't really mesh well with the rest of the UI; it has no facilities for creating GUI controls (except for context menus).
If you're learning OpenGL, then you should be focused on learning OpenGL, not GUI programming. So use what makes sense for the task in question.


text:
Q: c# .net Request.Param i think i know the answer to this question, but it never hurts to ask...
our .net application needs to store things like names in the database.
we just discovered some fields with leading spaces.
1) i could go thru every single field we store in the database and trim each value before it goes in. but i really would like to avoid having to do that and forgetting the next time a field is added.
2) another way would be to trim all the request params before they are processed into objects in my controller action parameter list. this seems cleanest to me because it would cover any eventuality. however it looks like the request parameters are read only at run time, even though if i write code, the compiler is happy to let me put a param on the lhs.
3) finally, i could trim all the values before they are transmitted to the server. i can do this very easily b/c i'm using extjs and can add a global 'getRawValue()' that trims the string when extracting it from a form field. this is less appealing, more on philosophical grounds: the front end should not have to perform tasks to ensure the database is in good shape.
--
it looks like (3) is the best option (for me). comments?

A: It sounds like you're using MVC. You could use a custom model binder that trims string values when binding the parameters to your action parameters.
The model binder is the service that transforms the Request parameters into actual objects that get passed into your controller actions. See this link for a good explanation.
While I haven't done this myself, it appears that something like this ought to work:
public class MyModelBinder : DefaultModelBinder
{
    protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
    {
        var valString = value as string;
        if(valString != null)
        {
            value = valString.Trim();
        }
        base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
    }
}

You basically just override the default behavior to trim any string value before setting it as the value of an action parameter or a property on an action's parameter.
I haven't figured out how to register this as your default model binder with ASP.NET MVC: that may actually depend on your IoC container.


text:
Q: Is it possible to test scroll in using Gemini by Yandex? Does anyone use Gemini by Yandex for testing css regression?
I faced with the following problem: need to test scroll in some page, but as I know, gemini capture whole page and show only that part which you set by adding .setCaptureElements('someElement').
E.g. I set capture element as html (which has 100% height) and my content is very huge, but gemini screenshot show up only cut over part of page without possibility to scroll cause page hasn't scroll as such...
Maybe some of you faced with same problem and have cool solution?
Thanks!

A: I had the necessity to make a screenshot of the page that has scrolling. I need the screenshot of the whole page and made changes which let me did it:

*

*Used .setCaptureElements only for the element where is scrolling exist (not the whole body).

*Added line compositeImage: true in configuration file.

A: gemini.suite('App-Name', function(test) {
        test.setUrl('/')
            .setCaptureElements('body')
            .capture('Full Page', (actions) => actions.wait(2000))
    });

//You can also use
.setCaptureElements('html') , if .setCaptureElements('body') is not working perfect for you.

You need to add this code in .gemini.js
browsers: {
        'chrome-desktop': {
            desiredCapabilities: {
                browserName: 'chrome',
                compositeImage: true,
                screenshotMode: 'fullpage',
            }
        }


text:
Q: thumbnail returns null on android above version 4.0 I am getting the samethis
issue
public class MainActivity extends Activity
{

    ImageView imgVie;

    Bitmap bmp,extBmp;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imgVie = (ImageView)findViewById(R.id.imageView1);
        String path =   "http://202.65.154.108:8080/VODStream/lokesh.stream.mp4";
        bmp = ThumbnailUtils.createVideoThumbnail(path, Thumbnails.FULL_SCREEN_KIND);

        if(bmp!=null)
        {

            extBmp =    ThumbnailUtils.extractThumbnail(bmp, 300, 300);
            imgVie.setImageBitmap(extBmp);
        }

        if(bmp==null)
        {
            Toast.makeText(getApplicationContext(), "Sorry your bitmap returns null", Toast.LENGTH_LONG).show();
        }
    }

}

when run this application in nexus4s its entering into if condition.In all other phones it moving to else.
do you have any suggestions.

A: If your video is on the external storage requires permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

A: 1)- Sometime if video quality is poor , video is corrupt or format is not supported it returns null bitmap.
2)- createVideoThumbnail(String filePath, int kind) supports MINI_KIND or MICRO_KIND as kind only in      4.0+.
see http://developer.android.com/reference/android/media/ThumbnailUtils.html.
try one of those...
3)- Some devices can't play and can't create thumbnails for videos, that placed on internal memory. Check it, and move your video to SD Card before thumbnails creating.
4)Check your path of the file.


text:
Q: Unique color for zero values in pyplot TwoSlopeNorm LinearSegmentedColormap I'd like to use a custom (blue) color on a plot where the data is zero. I have tried the set_under method, but failed. The desired output would be a blue line at the bottom and a two blue square at the upper part of the graph. Any help is appreciated.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap,TwoSlopeNorm

# TwoSlopeNorm see:
# https://matplotlib.org/devdocs/tutorials/colors/colormapnorms.html#sphx-glr-tutorials-colors-colormapnorms-py
red2orange = np.array([np.linspace(1, 1, 256),
                       np.linspace(0, 165/256, 256),
                       np.linspace(0, 0, 256),
                       np.ones(256)]).T
grey2black = np.array([np.linspace(0.75, 0.25, 256),
                       np.linspace(0.75, 0.25, 256),
                       np.linspace(0.75, 0.25, 256),
                       np.ones(256)]).T
all_colors = np.vstack((grey2black,red2orange))
cmap = LinearSegmentedColormap.from_list('two_slope_cmap', all_colors)
divnorm = TwoSlopeNorm(vmin=1, vcenter=400, vmax=1000)

# seting bad and under
cmap.set_bad('mediumspringgreen')
cmap.set_under('blue')

#fake data
data = np.arange(1400)[:,None]* np.ones(200)
data[ 1100:1150, 50:150] = np.nan # bad data
data[ 1200:1250, 50:150] = 0 # zero data
data[ 1300:1350, 50:150] = -1 # under data

# plot
f,a = plt.subplots()
raster = a.pcolormesh(data,cmap=cmap, norm=divnorm)
cbar = f.colorbar(raster,ax=a, extend='both')

A: For some unknown reason, TwoSlopeNorm doesn't seem to honor the under nor over colors. Changing the code to use plt.Normalize() instead of TwoSlopeNorm() indicates that for that norm, the under color works as expected.
A workaround is to draw the pcolormesh a second time, only for the under color. A drawback is that the under color isn't shown in the colorbar extension.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, ListedColormap, TwoSlopeNorm

red2orange = np.array([np.linspace(1, 1, 256),
                       np.linspace(0, 165 / 256, 256),
                       np.linspace(0, 0, 256),
                       np.ones(256)]).T
grey2black = np.array([np.linspace(0.75, 0.25, 256),
                       np.linspace(0.75, 0.25, 256),
                       np.linspace(0.75, 0.25, 256),
                       np.ones(256)]).T
all_colors = np.vstack((grey2black, red2orange))
cmap = LinearSegmentedColormap.from_list('two_slope_cmap', all_colors)
divnorm = TwoSlopeNorm(vmin=1, vcenter=400, vmax=1000)

# seting bad and under
cmap.set_bad('mediumspringgreen')
cmap.set_under('dodgerblue')  # this doesn't seem to be used with a TwoSlopeNorm

# fake data
data = np.arange(1400)[:, None] * np.ones(200)
data[1100:1150, 50:150] = np.nan  # bad data
data[1200:1250, 50:150] = 0  # zero data
data[1300:1350, 50:150] = -1  # under data

# plot
f, a = plt.subplots()
raster = a.pcolormesh(data, cmap=cmap, norm=divnorm)
cbar = f.colorbar(raster, ax=a, extend='both')

# draw the mesh a second time, only for the under color
a.pcolormesh(np.where(data < 1, 0, np.nan), cmap=ListedColormap([cmap.get_under()]))

plt.show()

Another workaround is to change the colormap itself, setting the lowest color to the desired under color. A drawback is that vmin needs to move a bit. (The distance seems to be 1/127 of the distance between vmin and vcenter. Internally, the colormap maintains 256 colors, with the color for vcenter at position 128.)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm, to_rgba

red2orange = np.array([np.linspace(1, 1, 256),
                       np.linspace(0, 165 / 256, 256),
                       np.linspace(0, 0, 256),
                       np.ones(256)]).T
grey2black = np.array([np.linspace(0.75, 0.25, 256),
                       np.linspace(0.75, 0.25, 256),
                       np.linspace(0.75, 0.25, 256),
                       np.ones(256)]).T
all_colors = np.vstack((grey2black, red2orange))
all_colors[0, :] = to_rgba('dodgerblue')
cmap = LinearSegmentedColormap.from_list('two_slope_cmap', all_colors)
vmin = 1
vcenter = 400
vmax = 1000
divnorm = TwoSlopeNorm(vmin=vmin-(vcenter-vmin)/127, vcenter=vcenter, vmax=vmax)

# seting bad and under
cmap.set_bad('mediumspringgreen')
cmap.set_under('red')  # this doesn't seem to be used with a TwoSlopeNorm

# fake data
data = np.arange(1400)[:, None] * np.ones(200)
data[1100:1150, 50:150] = np.nan  # bad data
data[1200:1250, 50:150] = 0  # zero data
data[1300:1350, 50:150] = -1  # under data

# plot
f, a = plt.subplots()
raster = a.pcolormesh(data, cmap=cmap, norm=divnorm)
cbar = f.colorbar(raster, ax=a, extend='both')
plt.show()

PS: The following code tries to visualize how the two norms treat the under color differently:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import TwoSlopeNorm

fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 3))

data = np.arange(0, 100)[:, None]
cmap = plt.get_cmap('viridis').copy()
cmap.set_under('crimson')
cmap.set_over('skyblue')

norm1 = plt.Normalize(20, 80)
im1 = ax1.imshow(data, cmap=cmap, norm=norm1, aspect='auto', origin='lower', interpolation='nearest')
plt.colorbar(im1, ax=ax1, extend='both')
ax1.set_title('using plt.Normalize()')

norm2 = TwoSlopeNorm(vmin=20, vcenter=30, vmax=80)
im2 = ax2.imshow(data, cmap=cmap, norm=norm2, aspect='auto', origin='lower', interpolation='nearest')
plt.colorbar(im2, ax=ax2, extend='both')
ax2.set_title('using TwoSlopeNorm')

plt.show()

PPS: Looking into the source of TwoSlopeNorm at github, the problem seems to be solved for the next version of matplotlib (current version is 3.4.3). So, you could try to install the development version. (The change involves adding left=-np.inf, right=np.inf as parameter to np.interp in the __call__ method of the TwoSlopeNorm class in colors.py.


text:
Q: Multiple updates and re-sequence rows Hi Guys I need your help with multiple updates:
I have a table with 3 columns:
Start date, seqID,  Name
07/07/2013  1       Name1
07/09/2013  2       Name2
07/11/2013  3       Name3
07/15/2013  4       Name4
07/20/2013  5       Name5

If start date 07/15/2013 is changed to 07/10/2013 then seq ID 4 becomes 3 and the row becomes after 07/09/2013, seq ID 2
If Start Date 07/09/2013 is changed to 07/16/2013 then the row is re-sequenced as number 4 and moved to above 07/20/2013:
The update would be as follows:
Start date, seqID,  Name
07/07/2013  1       Name1
07/11/2013  2       Name3
07/15/2013  3       Name4
07/16/2013  4       Name2
07/20/2013  5       Name5

How can I re-sequence the seqID when date is updated?
Thanks

A: It depends on your RDBMS but mostly your sequence will be dynamic on the output.
SQL Server 2005 + & Oracle (and maybe others) have  ROW_NUMBER() function which you'd use to establish the sequence number as you select the data you need based on the ordering criteria.


text:
Q: Is there a JavaScript technique to check for type equality in >,<,>=,<= operations? If I have if(Object.keys(obj) < 2) then I have a bug that might slip past my tests if I don't test it with objects with property counts below and at/above 2. i.e. it should have .length.
If my linter were to check for type on either side of <,>,<=,>= then it could warn about this.
Alternatively, how else could you catch this? I already know that more high quality tests would catch this. The problem with that is you never know when you have enough high quality tests. If a linter or other tool had the ability to warn of types in this situation then this would be automatically caught.

A: There is no conclusive way to check for type equality in a linter without actually running the code because the code can do all sorts of things and a linter can't know what might actually be present in a variable when it is used in a comparison. This is a consequence of using a language such as Javascript that does not require strict typing.
There are variants of Javascript such as TypeScript (that can be compiled to Javascript) that offer more capabilities in this regard.