How to start shared element transition using Fragments?

Question: I am trying to implement transitions between fragments which have "shared elements" as described in the new material design specs.
The only method I can find is the ActivityOptionsCompat.makeSceneTransitionAnimation, which I believe works on Activity only.
I've been searching for this same functionality but with/for fragments.
Comment: I can now confirm that transitioning a view that's inside a list item layout to a view in a new fragment does not work.  If I put a view in my first fragments layout, outside the listview, it does work.
Comment: @broccoli I found solution for listview\recyclerview. You need unique transition name for each item. Read more: http://www.androidauthority.com/using-shared-element-transitions-activities-fragments-631996/
Comment: Have you checked FragmentTransaction.addSharedElement -method ; http://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#addSharedElement(android.view.View,java.lang.String) ?
Comment: I wasn't able to get it to work with ImageViews inside list items either.  I was able to put together a very simple Activity with 2 fullscreen fragments.  Each fragment had 2 Views with black background in different sizes and positions and when I tap the screen it switches the fragment.  The shared elements did animate as expected in this case.  So it does work, just maybe not when your view is in a list item.  I wonder if it's because the list items aren't known until run time?
Comment: I tried using that actually, but it didn't seem to work, at least from an imageview in a listview item. There are probably a bunch of undocumented limitations. Disabling transitions and animations on the transaction didn't seem to help though.
Comment: Here're [a series of posts](http://www.androiddesignpatterns.com/2014/12/activity-fragment-transitions-in-android-lollipop-part1.html) which can help to understand Fragments' transition.
Answer: I had the same problem but had it working by adding a new fragment from another fragment.
The following link is very helpful in getting started on this: https://developer.android.com/training/material/animations.html#Transitions
Following is my code that works. I'm animating an ImageView from one fragment to the other.
Make sure the View you want to animate has the same android:transitionName in both fragments.
The other content doesn't really matter.
As a test, you could copy this to both your layout xml files. Make sure the image exists.
<ImageView
android:transitionName="MyTransition"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/test_image" />

Then I have 1 file in my res/transition folder, named change_image_transform.xml.
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
    <changeImageTransform />
</transitionSet>

Now you can get started. Lets say you have Fragment A containing the image and want to add Fragment B.
Run this in Fragment A:
@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.product_detail_image_click_area:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                setSharedElementReturnTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.change_image_transform));
                setExitTransition(TransitionInflater.from(getActivity()).inflateTransition(android.R.transition.explode));

                // Create new fragment to add (Fragment B)
                Fragment fragment = new ImageFragment();
                fragment.setSharedElementEnterTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.change_image_transform));
                fragment.setEnterTransition(TransitionInflater.from(getActivity()).inflateTransition(android.R.transition.explode));

                // Our shared element (in Fragment A)
                mProductImage   = (ImageView) mLayout.findViewById(R.id.product_detail_image);

                // Add Fragment B
                FragmentTransaction ft = getFragmentManager().beginTransaction()
                        .replace(R.id.container, fragment)
                        .addToBackStack("transaction")
                        .addSharedElement(mProductImage, "MyTransition");
                ft.commit();
            }
            else {
                // Code to run on older devices
            }
            break;
    }
}

Comment: @stoefln check out this link http://www.androidauthority.com/using-shared-element-transitions-activities-fragments-631996/
Comment: This works for me except it always starts the animation at the top of the screen in the second fragment.  So if I have a view in each element of my listview (or in my case RecyclerView) and you tap on one near the bottom of the list and the new placement for that view in the second fragment is at the bottom of the screen, it actually animates from the top to the bottom instead of animating from the place on the screen in the first fragment where the view started.  Anyone know why this is?
Comment: I am assigning unique id's to each instance in my Adapter.  I'm appending the items position.

That being said, I solved my problem.  As it turns out you need to include the ChangeTransform to your TransitionSet.  This tells the system to save the start position of the view you just selected and use that as the start position for the animation in the new fragment.
Comment: I think this is because the list view repeatedly contains the same elements. If one would perform a findViewById, the first item would return. I think you should uniquely identify the animated view by assigning the transitionName dynamically when clicking the item.
Comment: @brockoli can you elaborate on " As it turns out you need to include the ChangeTransform to your TransitionSet." ? How do you do that?
Comment: @ar34z it's just res/transition, gradle wouldn't build it otherwise. https://developer.android.com/reference/android/transition/Transition.html
Comment: This doesn't work when i `add` the fragment instead of `replace'. Any ideas on how to achieve the transition animation with `add`? -- http://stackoverflow.com/questions/29145031/shared-element-transition-works-with-fragmenttransaction-replace-but-doesnt-w
Comment: @Lilo, nice tutorial. Though note that `addSharedElement` of the `FragmentTransaction` is called outside of the Lollipop if-statement, so it wont work on older devices as it is an API lev. 21 method. It should be fixed. See http://developer.android.com/reference/android/app/FragmentTransaction.html#addSharedElement(android.view.View, java.lang.String)
Comment: cay anyone please help me with this SO question https://stackoverflow.com/q/59431465/4291272
Answer: The shared element fragment transitions do work with ListViews, as long as the source and target views have the same (and unique) transitionName.
If you make your list view adapter to set unique transitionNames to the views you want (e.g. some constant + specific item id) and also change your detail fragment to set the same transitionNames to the target views at runtime (onCreateView), the transitions actually work!
Comment: This fixed it for me.  I'm able to animate my shared ImageViews from one fragment to another within the same Activity now.

Now my issue is that my ImageViews aren't translating into their new positions, they just appear in their new location but run a scale up animation.  I'm using setSharedElementEnterTransition(new ChangeBounds()); when I create my fragment instance.  Similar behaviour with ChangeImageTransform()
Comment: Is it possible to get a piece of working code to test this? I have been trying for a while now, and nothing works.
Comment: for me, even if each of the image views share the same transitionName, it kinda works. it does work fine if the image is still in memory and only after the first time the animation occurs.

the catch is, as i'm using downloaded images, you can see the image view swapping for the fallback one first before loading the proper one. still, i have to forcefully load the same image in fragment B, passing the image url as an argument from fragment A.
Comment: @Dimitris cay you please help me with this SO question https://stackoverflow.com/q/59431465/4291272
Answer: Shared elements do work with Fragments but there are some things to keep in mind:

Don't try to set the sharedElementsTransition in the onCreateView of your Fragment. You have to define them when creating an instance of your Fragment or in onCreate.
Take note of the official documentation on the possible animations for enter/exit transitions & sharedElementTransition. They are not the same.
Trial and error :)
Comment: cay you please help me with this SO question https://stackoverflow.com/q/59431465/4291272
Comment: Well this official code sample actually sets `sharedElementTransition` in the `onCreateView` : https://github.com/android/animation-samples/blob/master/GridToPager/app/src/main/java/com/google/samples/gridtopager/fragment/ImagePagerFragment.java
Answer: This should be a comment to the accepted answer, as I am unable to comment on it.
The accepted answer (by WindsurferOak and ar34z) works, except for a "minor" problem which caused a null pointer exception when navigating up with the backStack. It seems that setSharedElementReturnTransition() should be called on the target fragment instead of the original fragment.
So instead of:
setSharedElementReturnTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.change_image_transform));

it should be
fragment.setSharedElementReturnTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.change_image_transform));

https://github.com/tevjef/Rutgers-Course-Tracker/issues/8
Comment: cay you please help me with this SO question https://stackoverflow.com/q/59431465/4291272
Answer: Following are some helpful resources:
https://github.com/lgvalle/Material-Animations
http://www.androiddesignpatterns.com/2014/12/activity-fragment-transitions-in-android-lollipop-part1.html
https://www.youtube.com/watch?v=5e1Yh0fSZhQ
Answer: The key is to use a custom transaction with
transaction.addSharedElement(sharedElement, "sharedImage");

Shared Element Transition Between Two Fragments
In this example, one of two different ImageViews should be translated from the ChooserFragment to the DetailFragment.
In the ChooserFragment layout  we need the unique transitionName attributes:
<ImageView
    android:id="@+id/image_first"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_first"
    android:transitionName="fistImage" />

<ImageView
    android:id="@+id/image_second"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_second"
    android:transitionName="secondImage" />

In the ChooserFragments class, we need to pass the View which was clicked and an ID to the parent Activity wich is handling the replacement of the fragments (we need the ID to know which image resource to show in the DetailFragment). How to pass information to a parent activity in detail is surely covered in another documentation.
view.findViewById(R.id.image_first).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (mCallback != null) {
            mCallback.showDetailFragment(view, 1);
        }
    }
});

view.findViewById(R.id.image_second).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (mCallback != null) {
            mCallback.showDetailFragment(view, 2);
        }
     }
});

In the DetailFragment, the ImageView of the shared element also needs the unique transitionName attribute.
<ImageView
    android:id="@+id/image_shared"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:transitionName="sharedImage" />

In the onCreateView() method of the DetailFragment, we have to decide which image resource should be shown (if we don't do that, the shared element will disappear after the transition).
public static DetailFragment newInstance(Bundle args) {
    DetailFragment fragment = new DetailFragment();
    fragment.setArguments(args);
    return fragment;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_detail, container, false);

    ImageView sharedImage = (ImageView) view.findViewById(R.id.image_shared);

    // Check which resource should be shown.
    int type = getArguments().getInt("type");

    // Show image based on the type.
    switch (type) {
        case 1:
            sharedImage.setBackgroundResource(R.drawable.ic_first);
            break;

        case 2:
            sharedImage.setBackgroundResource(R.drawable.ic_second);
            break;
    }

    return view;
}

The parent Activity is receiving the callbacks and handles the replacement of the fragments.
@Override
public void showDetailFragment(View sharedElement, int type) {
    // Get the chooser fragment, which is shown in the moment.
    Fragment chooserFragment = getFragmentManager().findFragmentById(R.id.fragment_container);

    // Set up the DetailFragment and put the type as argument.
    Bundle args = new Bundle();
    args.putInt("type", type);
    Fragment fragment = DetailFragment.newInstance(args);

    // Set up the transaction.
    FragmentTransaction transaction = getFragmentManager().beginTransaction();

    // Define the shared element transition.
    fragment.setSharedElementEnterTransition(new DetailsTransition());
    fragment.setSharedElementReturnTransition(new DetailsTransition());

    // The rest of the views are just fading in/out.
    fragment.setEnterTransition(new Fade());
    chooserFragment.setExitTransition(new Fade());

    // Now use the image's view and the target transitionName to define the shared element.
    transaction.addSharedElement(sharedElement, "sharedImage");

    // Replace the fragment.
    transaction.replace(R.id.fragment_container, fragment, fragment.getClass().getSimpleName());

    // Enable back navigation with shared element transitions.
    transaction.addToBackStack(fragment.getClass().getSimpleName());

    // Finally press play.
    transaction.commit();
}

Not to forget - the Transition itself. This example moves and scales the shared element.
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class DetailsTransition extends TransitionSet {

    public DetailsTransition() {
        setOrdering(ORDERING_TOGETHER);
        addTransition(new ChangeBounds()).
            addTransition(new ChangeTransform()).
            addTransition(new ChangeImageTransform());
    }

}

Comment: cay you please help me with this SO question https://stackoverflow.com/q/59431465/4291272
Answer: I searched for SharedElement in fragments and I find very useful source code on GitHub.
1.first you should define transitionName for your Objects(Like ImageView) in both Fragments layout(We add a button in fragment A for handling click event):
fragment A:
  <ImageView
    android:id="@+id/fragment_a_imageView"
    android:layout_width="128dp"
    android:layout_height="96dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="80dp"
    android:scaleType="centerCrop"
    android:src="@drawable/gorilla"
    android:transitionName="@string/simple_fragment_transition />

<Button
    android:id="@+id/fragment_a_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="24dp"
    android:text="@string/gorilla" />

fragment B:
    <ImageView
    android:id="@+id/fragment_b_image"
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:scaleType="centerCrop"
    android:src="@drawable/gorilla"
    android:transitionName="@string/simple_fragment_transition" />

Then you should write this code in your transition file in transition Directory(if you haven't this Directory so create One: res > new > Android Resource Directory > Resource Type = transition > name = change_image_transform ):

change_image_transform.xml:
 <?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android">
  <changeBounds/>
  <changeTransform/>
  <changeClipBounds/>
  <changeImageTransform/>
</transitionSet>

In the last step you should complete codes in java:

fragment A:
public class FragmentA extends Fragment {

    public static final String TAG = FragmentA.class.getSimpleName();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_a, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        final ImageView imageView = (ImageView) view.findViewById(R.id.fragment_a_imageView);
        Button button = (Button) view.findViewById(R.id.fragment_a_btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getFragmentManager()
                        .beginTransaction()
                        .addSharedElement(imageView, ViewCompat.getTransitionName(imageView))
                        .addToBackStack(TAG)
                        .replace(R.id.content, new FragmentB())
                        .commit();
            }
        });
    }
}

fragment B:
public class FragmentB extends Fragment {

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setSharedElementEnterTransition(TransitionInflater.from(getContext()).inflateTransition(android.R.transition.move));

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_b, container, false);
    }
}

don't forget to show your "A" fragment in your activity:

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

        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.content, new SimpleFragmentA())
                .commit();
    }

source : https://github.com/mikescamell/shared-element-transitions
Comment: cay you please help me with this SO question https://stackoverflow.com/q/59431465/4291272
Comment: @FaisalShaikh did you follow this answer step by step? it works for me.
Answer: How to start shared element transition using Fragments?
I assume you want to transition of your Image using Fragment (instead of Activity)

it wont work perfectly if you have already set AppTheme

keep the transition name of source and destination same

You have to do three things for transition:
1.Set transitionName to the source View(xml or programatically) -> before calling makeFragmentTransition
private void setImageZoom(boolean isImageZoom) {
    ImageView imageView = this.findViewById(R.id.image);

    if (isImageZoom) {
        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewCompat.setTransitionName(imageView, "imageTransition");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    makeFragmentTransition(imageView);
            }
            }
        });
    }
}

2.Fragment Transition

Set TransitionSet for the specicific Transition animation

apply them on Fragment

call addSharedElement(View, transitionName) while fragmentTransition
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public void makeFragmentTransition(ImageView sourceTransitionView) {
//transtionName for sourceView
//MUST set transitionName before calling this method(programattically or give ->transitionName to the view in xml)
String sourceTransitionName = ViewCompat.getTransitionName(sourceTransitionView);
TransitionSet transitionSet = new TransitionSet();
transitionSet.setDuration(500);
transitionSet.addTransition(new ChangeBounds());  //to expand boundaries
transitionSet.addTransition(new ChangeTransform()); //for transtion vertically
transitionSet.addTransition(new ChangeImageTransform()); // image transform work
transitionSet.setOrdering(TransitionSet.ORDERING_TOGETHER);
  ImageTransitionFragment fragment = new ImageTransitionFragment();
  fragment.setSharedElementEnterTransition(transitionSet);
  fragment.setSharedElementReturnTransition(transitionSet);
  fragment.setAllowReturnTransitionOverlap(false);

  try {

      getHostActivity().getSupportFragmentManager()
              .beginTransaction()
              //sharedElement is set here for fragment
              //it will throw exception if transitionName is not same for source and destionationView
              .addSharedElement(sourceTransitionView, sourceTransitionName)
              //R.id.fragmentView is the View in activity on which fragment will load...
              .replace(R.id.fragmentView, fragment)
              .addToBackStack(null)
              .commit();
  } catch (Exception e) {
      //
      String string = e.toString();
  }

}

3.set desitionNation transitionName in ImageView
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/destionationTransitionPage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:transitionName="@string/pageTransition"
android:background="@color/black_color">

<com.android.foundation.ui.component.FNImageView
    android:id="@+id/destinationImageView"
    android:layout_width="@dimen/_400dp"
    android:layout_gravity="center"

    android:transitionName="imageTransition"
    android:layout_height="@dimen/_400dp" />
</FrameLayout>

Please respond if anything is not clear or it need more improvement
Comment: I am facing issue of Transition it is not working on my project, same code working in core project.
Comment: Thank you for this code snippet, which might provide some limited short-term help.  A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions.  Please [edit] your answer to add some explanation, including the assumptions you've made.
Comment: Thank you Toby, your feedback is really greatfull, I will improve my answer as soon as possible, as I have solved the question.


Best way to bring power to a moving garage door

Question: I'm planning a project to add RGB lighting to the inside of my garage door.  It will add white light to the garage when I need it, as well as visually confirm door motion and position, and clearance of the doorway when complete.
One aspect though that I'd like suggestions on, is how to physically electrically connect the large moving door to the stationary house.
1) The three options I've seen so far would be a horizontal cable festoon:

2) Curly cord flat against the wall from the midpoint of the door to the corner of the ceiling.

3) Using non-conductive roller wheels for the door, and using the two tracks themselves as conductors with 'brushes on the door' that would ride in contact with the rails.  I'd be a little concerned about corrosion over time if this was DC, and the effect of a large looped field if it were AC.
With any of these I will almost certainly be using current-limited 12 or 24v, so that when it eventually breaks I don't have to worry too much about an electrical hazard. Perhaps tension rated break-away connectors would be a good idea to to avoid damage.
The control module will probably be a raspberry pi, mounted on the door. It will probably use wifi for its data connection.  But it would be nice to use hardwired ethernet if that wasn't much extra hassle.  A festoon for example could accommodate power and ethernet with little extra headache.
My primary concern is physical durability and the likelyhood of cables getting snagged and breaking or blocking the operation of the automatic door opener.
Actually the door opener itself, having a rail and a plastic trolley, might serve as an electric path without having to add any physical objects that could add a snag hazard.  As could the torsion spring wires....
Anyway. What other means can you come up with to bring power to my garage door, and what method do you think is the best and why?
Comment: will you need the lights on when the door is up? if not, it can be a bit simpler: Al tape contacts at bottom of door meeting the floor. Pi seems way overkill for LEDs but should work.
Comment: Yes. I envision the light bar flashing red when the door starts to go up, and flashing green when it's high enough that my vehicle can fit under. Rpi would process downward facing video to verify no obstructions to the door's path, and if the door stayed open for too long without and motion through the door way, it could text me, or blink lights on my home automation network to get my attention.  I could perhaps see having a lithium battery on the door.  Then charging contacts that would engage at either end of the doors travel.  But a battery has it's own risks and maintenance cost
Comment: Wont ever be too dark, with one or two strips of high density leds immediately above.  I might paint lines on the floor, and if say 95 percent of that region is within 5% of the designed color. Then it reads as clear.  Very hard to do while moving, but easier if the check always occurs when the door is fully up.  And if it's not fully up and not fully closed, then it's almost certainly opening which I wouldn't worry about instructions, or closing, during which the existing beam would protect against, and I'd almost always be present anyway.
Comment: In brightness yes, but not too much in hue.  Regardless, I'm hoping to keep this question to physical cabling.
Comment: Will the door spend long periods of time in the open or partially open position?
Comment: At least an hour a week in the open position.  Twice to three times that in the summer
Answer: You have two components which may be electrically isolated from each other if the door itself is not metal:  Tracks and spring/counterweight mechanism; and The opener track. You can make one positive and the other negative.  You will have trouble electrically separating the tracks and springs from each other. Keep in mind that spring preload is dangerous, cannot be reasoned with, and does not know pity or remorse or fear.
However, I would be more inclined to use induction, or "two halves of a transformer".  Place one half on the door. Place the other half where the door is in the down location.  If you only need the lights to to work in that position, you are done.  Otherwise either a) have a second "transformer" primary in the open position; or b) install a large enough battery on the door. NiCd D-cells are a good choice, because it is not expensive and rides through abuse better than most.  A protected lithium might also do.   Presence or absence of AC would also be a means to detect door position.
Keep in mind with transformers, the carried wattage decides the mass of copper, but the frequency decides the size of the iron core.


resetting bxSlider

Question: I took a different direction with a carousel I implemented, opting for bxSlider instead of jCarousel. This is for an image gallery I am building http://rjwcollective.com/equinox/rishi_gallery/eqgall.php
The issue I am running into is when I reset the filters, or select a different filter, the slider doesn't reset.
This is the code for the inital load:
    //first load
$.ajax({
    type:"POST",
    url:"sortbystate.php",
    data:"city=&gender=&category=",
    success:function(data){
            //carousel

            $('#thumbs').html(data);

            //alert("whoa, careful there!");
                 $('#thumbs').bxSlider({auto: false, mode:'vertical',
                            autoControls: false,
                            autoHover: true,
                            pager: false,
                            displaySlideQty: 4,
                            speed:800,
                            infiniteLoop: true,
                            moveSlideQty: 4,

                            controls: true});
    }

});//end ajax

This is the code for handling the change of a filter:
$(".statelist :input").click(function(){

    var carousel = $('#thumbs').data('jcarousel');
    var state = $('.statelist input:checked').attr('value');
    var gender = $('.gender input:checked').attr('value');
    var category =$('.category input:checked').attr('value');
        $.ajax({
            type:"POST",
            url:"sortbystate.php",
            data:"city="+state+"&gender="+gender+"&category="+category,
            success:function(data){
                    //alert("whoa, careful there!");

                    $('#thumbs').html(data);
                         $('#thumbs').bxSlider({auto: false, mode:'vertical',
                                    autoControls: false,
                                    autoHover: true,
                                    pager: false,
                                    displaySlideQty: 4,
                                    speed:800,
                                    infiniteLoop: true,
                                    moveSlideQty: 4,

                                    controls: true});

                    //$('#thumbs').jcarousel('add', index, data);
            }

        });//end ajax
    });

I referred bxSlider's documentation and it had a built-in function to handle a reset:
destroyShow(): function()
reloadShow(): function()
I am confused as to what I am doing wrong.
Even tried emptying the carousel div before loading it with data, using .empty(), no dice.
Thoughts?
Edit: link to the bxSlider website: http://bxslider.com/
Answer: Declaring the "mySlider" variable outside the document-ready block solved the problem for me:
var mySlider;
$(function(){
    mySlider= $('#slider').bxSlider({
        auto: true,
        controls: true
    });

    mySlider.reloadShow();
})

Alex
Comment: @wilsonrufus: reloadSlider();
Comment: Anybody know of a way to do this with bxSlider v4? reloadShow() no longer exists and [as of 1/18/15 there is no plan to replace it](https://github.com/wandoledzep/bxslider-4/issues/46).
Comment: @bergie3000 did u find the solution??
Comment: Something I just ran into: reloadSlider() takes an argument for new options.  When you don't send any argument in, it uses the old; when you send new options in, it overwrites the old (does not merge).  See this [jsfiddle](http://jsfiddle.net/y2QHD/)
Answer: Solution : use reloadSlider
   slider = $('.bxslider').bxSlider();
   slider.reloadSlider();

Answer: As the website says: you have the slideshowContainer to be attached to a variable in order to use the public functions. As reloadShow() and destroyShow() are public functions, this is the only way to go. Worked perfectly for me.
I've simply put a
var $theslideshow = [functionThatCallsYourSlideshow]

before my function and called afterwards $theslideshow.destroyShow();
hope this helps
Answer: the reloadShow funciton execute to function
destoryShow and initShow
destroyShow function delete all style and wrapper which is working fine in horizontal mode
but in vertical and fade mode it also delete the content of slider
try replace condition with switch
// unwrap all bx-wrappers
// remove any styles that were appended

if(options.mode == 'fade' || options.mode == 'verticel'){
$parent.unwrap().unwrap();
$parent.children().removeAttr('style');
}else{
    $parent.unwrap().unwrap().removeAttr('style');
    $parent.children().removeAttr('style').not('.pager').remove();
}

hope this helps
Answer: To participate in this question as well: the new BxSlider doesn't seem to have a destroyShow() or reloadShow() anymore? It doesn't work for me at least, and it isn't in the API documentation as well... Just saying.
Comment: reloadSlider() and destroySlider() in v4.
Answer: Use the following:
mySlider.reloadSlider();

It will reset the slider
Answer: ** Note : For the multiple bx slider reload on click of the element.  *
$(function() {
    var slider1 = $('#slider-1 .product_slider ul').bxSlider({
            pager:false,
            auto:true,
        });

    var slider2 = $('#slider-2 .product_slider ul').bxSlider({
        pager:false,
        auto:true,
    });
    var slider3 = $('#slider-3 .product_slider ul').bxSlider({
        pager:false,
        auto:true,
    });
    var slider4 = $('#slider-4 .product_slider ul').bxSlider({
        pager:false,
        auto:true,
    });

    $('.tab_container ul.nav-tabs li a').on('click',function() {
        slider1.reloadSlider();
        slider2.reloadSlider();
        slider3.reloadSlider();
        slider4.reloadSlider();
    });
});

By: Milan Pandya
Comment: Thanks a lot :)
slider.reloadSlider();

we can use this to reinitialize the bxslider. !!

Works Great !!!
Answer: I was writing a program which make a bunch of AJAX calls on a timer and displays the results in a bxslider and I also ran into a problem where the bxslider wasn't refreshing.This is how I solved it:
var $slider = null;

And inside the portion of code where you need to initialize or refresh the slider do this:
if ($slider == null) {
    $slider = $('.sliderDashboard').bxSlider({
        slideWidth: 200,
        minSlides: 1,
        maxSlides: 1,
        slideMargin: 10
    });
}
else {
    $slider.reloadSlider();
}

Answer: You should play with these two - destroyShow() and reloadShow(). My guess is using reloadShow() only but if it doesn't work out try destroyShow() followed by bxSlider(). You'll need a variable as a reference to the plugin api.
var slider =  $('#thumbs').bxSlider( { ... } );
slider.reloadShow(); // or slider.destroyShow(); $('#thumbs').bxSlider( { ... } );

Good luck
Comment: Any updates on how to get a reference to the bxSlider instance that can access the reloadShow and destroyShow methods?
Comment: Thanks Zlatev, but that didn't seem to work. I'll try a different approach.

resetting bxSlider


is it possible to give html or php code as variable value?

Question: I have a html code including with javascript / php code.
I wanna use this for value of variable.
like this:
function abc($content){
     $content='my html code ';
     //  rest of code
}

It will output as a txt file.
But for that reason my script will be so bigger.Is there any way to submit that html code to any site and put a link in variable to grab the script from that source ?
Comment: Why do you override the contents of the parameter with a constant string? What's the use of the parameter here, anyway, then?
Answer: You can put all HTML code into a separate file and load it using file_get_contents()
function abc($content){
     $content= file_get_contents( 'myHTMLcode.htm' );
     //  rest of code
}

Comment: +1 for this option. It sure will clean up code and separate it. You might need a ton of files though..
Comment: Thanks . I think it will easier for me.
And can you tell me that where can i put my html file to grab ? I mean same folder of main scrip ?
Comment: @user1687804 You can put the file in any folder, the PHP script has access to. In some cases it might be best to put it somewhere outside the web root.
Comment: @Sirko , if i wanna put that htm file to another sites, then what will be that code ?
Comment: @user1687804 What do you mean by "put to another site"? If you just want to reference it on another site on the same machine, just change the path accordingly.
Comment: @Sirko , Sorry typing mistake !
Actually  if i wanna put that html in another site. And then grab the code from it, then what code i need to use ?
Comment: @user1687804 Sorry, but I still don't get, what you want to do. You can use `file_get_contents()` anywhere and as much as you like.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/17811/discussion-between-sirko-and-user1687804)
Comment: @Sirko , I used this file_get_contents() .
Comment: @Sirko , After searched in php.net i have found this solution. To use this : file_get_contents() .
And now see your suggestion here.
Ya, that's work perfectly. Thanks Sirco :).
will i add this solution in my post ?
Comment: @user1687804 You accepted this solution as an answer, so you don't have to do anything else, if the problem is solved for you.
Answer: you can use php htmlentities() or htmlspecialchars()function
$variable=htmlentities("data");

Comment: @think123 maybe, but `htmlentities` converts every character that has a html code. `htmlspecialchars` converts only a few, so you'll need to ask yourself when should I use which :)
Comment: or maybe `htmlspecialchars()`.
Comment: IS it will work for all codes ? I mean ,   all kinds of work in this method ?


How to upload aab to Internal App Sharing using gradle task?

Question: I want to upload aab file to internal app sharing using gradle task. On google search option is there to upload using travis but is there any possibility to upload aab using gradle task?
Answer: You can use Gradle Play Publisher plugin:
https://github.com/Triple-T/gradle-play-publisher


Why do LED Lights Flicker on Low Dimmer Setting

Question: I just wired up the following schematic and both sets of LED recessed lights will flicker when dimmed below full power. It doesn't matter what the other dimmer is set to (full power, low power, off). The flicker is very quick, it is sporadic and doesn't follow a pattern. All lights on each line are included in the flicker. When set to full power on the dimmer slider, no flickering occurs. Both of the dimmers are the same and they are listed as compatible on each set of lights. All of the wiring that I ran was 12/2 based on this being on a 20 amp breaker.
All of the LED lights come with junction boxes and screw on pigtails down to the actual light. In the set of 4 LED's on the left of drawing, I have all 4 junction boxes wired up, but only the last light is connected by its pigtail as the wife wants to wait for the countertop to be installed before deciding how many lights she actually wants over it. So I may be removing a 1 or 2 of those lights from the line.
The middle switches in each 3 gang box are simple on/off switches to run either a ceiling fan or an exhaust fan.
I am curious of what steps I should take to try and diagnose the flicker. I just rechecked all wiring connections and nothing is loose.
My thoughts are that either the three missing lights on run one are causing the flicker. Or the USB outlets sharing the neutral line are causing the flicker. Or the dimmers, even after being listed as compatible actually aren't.
Is there anything in this schematic that jumps out to someone before I start buying different switches and outlets to troubleshoot with?

LED Lights Link #1
LED Lights Link #2
Dimmers Link #3
Comment: Can you plug in all the lights?  That junction box for the lights must have a transformer in it, because the little pigtail with the color control switch is not going to be line voltage.  It could act up if the transformer doesn't have a load on it.
Comment: [Related](https://diy.stackexchange.com/questions/160185/led-lights-with-a-dim-light-in-open-circuit) LEDs might look dim-lit even if off.
Comment: i would scrap the analog dimmer switch and get dim-able smart bulbs. They can manage brightness without carefully controlling the power delivered to them and their peers. This lets them play well with other devices on the line, and allows per-bulb brightness tweaking that's simply not possible otherwise.
Answer: LEDs on AC Power Don't Like to be Dimmed. Period.
(LEDs on DC can actually be dimmed quite easily - just look at an older battery powered LED device (like handheld computer games from the 1980s) and you can see the LEDs dim when the battery is low.)
But most AC powered LED lights - whether complete fixtures or Edison bulb incandescent replacements - have a driver circuit that takes high voltage AC and turns it into low voltage DC. That process does not lend itself well to dimming.
A modern dimmer is not, contrary to popular belief (including what I thought when I was a kid) simply reducing the constant amount of current or voltage. Rather, it chops up the power into little pieces and only sends some of those pieces to the lights.
With incandescent lights, only the total power really matters much. It also helps that the incandescent lights use the power "as is", where an LED light has to convert from 120V AC down to very low voltage DC. So this works fine on incandescent lights.
However, CFL & LED lights are, essentially "on or off". So dimming becomes a lot more complicated. With LEDs in particular, it takes very little power to produce light, so you often end up in one of two situations:

Flickering - The LED gathers up enough "bits of power" until it has enough to produce light. Uses that power to produce light. Waits for some more power.
Dim - This is actually what you want with a dimmer. But with LEDs this can happen even with a very small trickle of current to power a timer/motion detector/etc., with the result that "off" is never really "off".

There are technical solutions, aka "dimmable compatible LEDs" together with "LED compatible dimmers". Essentially, the LED light has to figure out that the chopped up bits of power are not a deliberate attempt at flickering the lights but rather intended to dim the lights. But despite the best efforts, sometimes they just don't work well together. As you have found out the hard way.
If both the LED fixtures and the dimmers claim compatibility, I would start by trying a different brand of dimmer to see if that helps.
Comment: "A dimmer is not" Well, LED dimmers are not. Incandescent dimmers can very well be. That's one of the reasons you can't put a LED behind a normal dimmer.
Comment: `+1` LEDs proper (the *actual diode that emits the light*) have no problem being dimmed, I don't think they mind at all! The light output will be some monotonic and *roughly* linear function of current. ([fig 2a](http://maltiel-consulting.com/Light_Emitting_Diode-LED_semiconductor_maltiel.htm)) However, any intervening circuitry may behave quite badly when providing it anything except a fairly constant DC supply, so maybe you should begin with "Commercial LED lights" rather than just "LEDs"?
Comment: @Mast If dimmers worked like that (resistively), a dimmer at 50% would produce as much heat as the actual lightbulb did. Maybe some smart person can invent an inductive or capacitive dimmer which doesn't waste power. I've never heard of one.
Comment: @user253751 Not resistively, but with a transformer.
Comment: While variable autotransformers transformers (variacs) do exist and I believe they have been used for dimming stage lighting in the past, I have never heard of them being used for domestic dimming, they are too bulky and expensive. Much cheaper to simply cut up the waveform with a Triac.
Answer: The specifications of the LED lights you have say they will dim down to 10% without any flicker or buzzing.  Some lights don't go down that far, and some will go even further.
Based on the manual for your dimmer switch, there is an adjustment to change the low end of the dimming range:

I would assume the switch would be factory set to work with most lights, but maybe the quantity of lights or their exact dimming capability is a little outside the norm.  Follow that adjustment procedure and see if it helps.  If you feel like you have to adjust the minimum dimming to be quite high, you should also plug in all the lights and make sure that is not making the problem worse.
Comment: Given the current setup, this is the best answer. Unfortunately, there are limits to how well dimmable LEDs and LED-compatible dimmers will work, but the Lutron dimmers with the range setting has been, in my experience, the easiest/best way to match dimmer to LED. The gold standard is to use a separate low-voltage signal for dimming (i.e. 0-10V DC), but it's a pain to retro-fit that, since it requires a separate low-voltage line between the switch and LED driver. Other than accepting the limited minimum brightness or 0-10V system, it's just a matter of trial and error. :(
Answer: I'll tell you a secret: they flicker all the time
You just don't notice it, because the higher the power, the longer they stay ON and quicker switch on/off. As you dim down them, their flickering becomes more even and noticeable.
What about randomness ? Well, it flickers randomly to minimize harmonics disturbance. Wait, what's that ? It's topic for another question on stack exchange...
Answer: Check that your LED bulbs are compatible with dimmers, and check that your dimmers are compatible with LEDs. If their respective packages don't say, then they probably aren't compatible and you will have problems.
Even if everything claims to be compatible, you still might have issues. In that case, the best you can do is experiment with different brands and models of each until you get a combination that works.
Both AC dimmers and AC LED bulbs employ some electrical trickery to perform their intended function.
AC dimmers make the light appear dimmer by turning the voltage on and off very quickly. This on-off effect happens at twice the line frequency (e.g. 120 Hz) which is usually too fast to see.
LED bulbs typically need less voltage than is provided by the AC line, as well as constant forward polarity (in contrast to AC's alternating polarity). Packed inside the bulb is a small circuit to make these adjustments.
In isolation, both of these things work pretty well, but when combined, things can start behaving weirdly. The dimmer's rapid switching disrupts power to the LED bulb's voltage regulation, and the LED bulb's voltage regulation prevents the dimmer's rapid switching from having a useful effect.
There are "dimmable" LED bulbs that are designed to cope with dimmers, and "LED compatible" dimmers that are designed to cope with LED bulbs, but neither are guaranteed to work well in all cases.
Answer: Electronic devices like LED compatible dimmers that chop up the AC power into tiny chunks tend to generate electronic noise that consists of harmonics of the line frequency but at very high frequencies.  These signals will bounce around between other devices nearby through the wiring.  This can cause interactions between those devices which would be more likely to be noticed in LEDs operating at low output levels.
Some electrical devices are marked "Surge Protected" such as "Surge Protected" Receptacles, which contain special circuitry to absorb the electronic noise that may be present.
The protection works best when it is very close to the source of the electronic noise or close to the susceptible load.
If, for example, you insert a "5280" surge protected receptacle between the dimmers and the LED lights you should see a noticeable reduction in the flickering.  There are many other devices marked "Surge Protected" that would also work if they fit betteer into your specific application.
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.
Answer: LED flickers, because it is a light emitting diode (a solid state lamp).  The Lamp will only light when its power cycle is "on".  A dimmer in essence, SLOWS DOWN THE CYCLE TIME, therefore slowing down the time frame in which a cycle is repeated.  So, the lamp appears to flicker, because it is turning ON and OFF!
Comment: Hello, and welcome to Home Improvement. In general, that's wrong: dimmers leave the power at 60Hz, but reduce the drive time on each phase. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.


How to make rounded corner image or circular image

Question: I have some images and I want to show them on my webpage. But the problem is that I want to make their corners rounded. The deepness of rounded corner depends, some time I want decent  round corners and some time I want very deep round corners so that it appear a circular image.
What is right way to do this?
Answer: You can use following css:
<code>-moz-border-radius: 20px;
-webkit-border-radius: 20px;
border-radius: 20px;
</code>
Note:- This will not work in IE except IE9.
Comment: Actually, IE 9 supports border-radius.
Comment: @Emil: Yes it does. but peoples has not started to use IE9 especially with windows XP. Updated answer.
Comment: @Harry: IE is  very popular , so we can't leave it. have you any other solution (IE compatible).
Comment: @jams: for IE use [Curvy Corner](http://code.google.com/p/curvycorners/). It's javascript solution. Also see this discussion: http://jonraasch.com/blog/css-rounded-corners-in-all-browsers
Comment: @Harry:All these are talking about round corners, but what about circular image?
Comment: @jams: give large number in radius and it will become circle
Answer: <code>/* Gecko browsers */
-moz-border-radius: 5px;
/* Webkit browsers */
-webkit-border-radius: 5px;
/* W3C syntax - likely to be standard so use for future proofing */
border-radius: 5px;
</code>
Use all 3 to ensure the most compatibility. IE7 and IE8 don't support border-radius except IE9. However There are JavaScript hacks, most involve a heap of 1px elements absolutely positioned or use SVG.
Comment: IE is  very popular , so we can't leave it. have you any other solution (IE compatible).
Answer: Rounded corners are not supported by some major browsers (ok maybe one major browser which is ... yes IE). The only way to get a cross browser solution is to use a jQuery plugin to round the corners.
Tutorial on rounded corners
Answer: Go here
Here automatically generates all browser specific CSS
http://css3generator.com/
or
http://css3please.com/


How can I prevent the value from being updated in Jquery UI Spinner?

Question: I don't want the value of my spinner to be updated when the user clicks on the up arrow.
In the API says:

spin( event, ui )
Triggered during increment/decrement (to determine direction of spin
  compare current value with ui.value). Can be canceled, preventing the
  value from being updated.

But does not show an example of how to do it.
I started a code like this:
var spinner = $( ".mySpinner" ).spinner({
    min: 0,
    spin: function( event, ui ) {
       //don't know what to do!
    }
});

How can I cancel the spin event?
Can you help me?
Thank you!
Answer: Event cancellation in jQuery UI works the same way as for native DOM events.
You only have to call preventDefault():
var spinner = $( ".mySpinner" ).spinner({
    min: 0,
    spin: function( event, ui ) {
       // Cancel the spin event. The value will not be updated.
       event.preventDefault();
    }
});

You can also return false from the handler, however this not only cancels the event but effectively stops its propagation to ancestor elements, as if stopPropagation() was called.


How to map network scanner

Question: I have just bought a shiny new Canon MG6250 multifunction printer/scanner and connected it via LAN. Installing the printing side of things was a breeze, however, I cannot work out how to set up scanning.
I installed the MG6200 series ScanGear MP driver from Canon's site but when I open GIMP or Simple Scan, they say there is no scanner detected. Using GIMP's 'update scanner list' button to search for the scanner does not find it.
How do I tell Ubuntu, GIMP or Simple Scan to look on the network for the scanner? Is there another utility especially for this?
Comment: Found a few pages via Googling talking about xsane and configuring it. Most of them talk about scanning using a USB connected scanner. I tried a few of the outlined tweeks, but none have worked so far.
Comment: Did you try the command line tool that comes with the ScanGear driver, `scangearmp`? That found it for me.
Answer: Just got this going today. This is how I got it working over wireless network, running Xubuntu 12.10 64-bit. (No Canon drivers were needed).
After installing xsane:

The sane man pages refer to "backendname" a lot. http://www.sane-project.org/sane-mfgs.html gives the backend name for the 6250 as "pixma"
man sane-pixma (seems to be a man entry for each backend) tells you that network scanners should normally be detected, but if not, add them directly to /etc/sane.d/pixma.conf
Edit that file and add a line of the format:
bjnp://<ip_address>
IP address can be retrieved from the printer settings, or from the options in the printer itself.
After adding an entry for the printer, save pixma.conf
Now edit /etc/default/saned and set RUN=yes
Then: service saned start
Run xsane

Now xsane should discover the scanner, and instead of saying "no devices found" and dying, it should run up (brings up about 4 windows). All the default settings seem to work — just press "Scan".
Comment: Thankyou for that concise explanation. Works a treat now!!
Comment: Good tip! My scanner isn't on the officially supported list. It didn't respond over the network but worked fine via USB from `xsane`.
Comment: This is exactly how I resolved an issue with my Ubuntu 15.04, Canon PIXMA MX870 (a network multi-use device connected via WiFi) and Simple Scan. Now everything works very well. Thanks for a great tip!
Comment: Note you have to do `sudo service saned start` or the service won't actually start. Use `sudo service saned status` to confirm it has started. You should see: saned is running.
Comment: @snark: yes, all of the commands above (editing in /etc/...) have to be run as root. I've found most instructions leave it out, I guess to not clog up every command, so I followed that trend.
Comment: To anybody about to go through this howto: as a first attempt, you might want to try to update the sane backend before. Sometimes that's both sufficient and necessary to make XSane and Simple Scan work out of the box. To to this, add this ppa and update your system as usual: https://launchpad.net/~rolfbensch/+archive/ubuntu/sane-git

(see also this thread: https://ubuntuforums.org/showthread.php?t=2264532)
Comment: Radiculous. Why does ubuntu treat a multi-functional printer as a printer and a scanner separately? It's 2018, not 1968!
Answer: I found that adding the subnet IP addresses to this file worked when nothing else did:
/etc/sane.d/saned.conf
To get the subnet, look at your output from the ifconfig command. Find a line that looks like this:
inet addr:192.168.1.4   Bcast:192.168.1.255    Mask:255.255.255.0
From this output, I learned that my wireless router subnet is 192.168.1,
and then searched for the printer (wireless router and printer must be powered on and operating) using this command:
sudo nmap -sP 192.168.1.0/24
Nmap scan report for 192.168.1.6
Host is up (0.011s latency).
MAC Address: XX:Xx:XX:XX:XX:XX (Canon)
From above, 192.168.1.6 is the IP address for my Canon printer/scanner on my LAN.
Therefore, I added this entry to /etc/sane.d/saned.conf:
192.168.1.0/24
xsane could then see my scanner.
Comment: On Ubuntu 16.04 (2018), this worked for me. Something must have happened to make saned stop scanning the proper network.
Answer: I have an epson printer/scanner and had to add the IP address to /etc/sane.d/epson2.conf like this:
net 10.0.5.125

I also commented out the net autodiscovery line.
Comment: Thanks! Less complicated than the accepted answer and worked for me right away.
Comment: Same here, worked perfectly for my EPSON XP-950. It worked only with the  USB before changing net autodiscovery to the real IP of the scanner.

How to map network scanner


What happens after you earn 2015 service medal CSGO

Question: So I recently earn the 2015 Service medal by reaching rank 40. Now that I have restarted what happens when I reach rank 40 again. If I do it in 2016 will it give me a 2016 service medal? Will it give me a different 2015 medal? What if I'm rank 39 in 2015 then I turn rank 40 2016? Has valve said anything about this?
Comment: Well no news till know but you can have a look at this https://steamcommunity.com/app/730/discussions/0/541907867782693144/
Answer: As of the update 11/10/2015:
Valve has released a Level 2 for your service badge should you choose to rerank it up to 40 again.  You can see the badge below:
Answer: As far as I know Valve never released a statement regarding your questions.
But there are indicators that there will be a different coin next year.
It is not sure, if your rank/level will be reset, beginning next year or if you keep your rank/level, but many say it will be reset.
Also there are no informations what will happen if you reach rank/level 40 twice a year. If you still get XP, weekly drop, or if your will be locked because of MAX level.
Comment: FYI: This answer is out of date. Valve has recently released new information about this.


HiveQL Query to Find a Delta Between Rows if a Condition matches

Question: I have some data in data lake:
Person |  Date    |  Time    |  Number of Friends  |
Bob    |  02/01   | unix_ts1 |  5                  |
Kate   |  02/01   | unix_ts2 |  2                  |
Jill   |  02/01   | unix_ts3 |  3                  |
Bob    |  02/01   | unix_ts3 |  7                  |
Kate   |  02/02   | unix_ts4 |  10                 |
Jill   |  01/29   | unix_ts0 |  1                  |

I would like to produce a table like so:
Person |  Date    |  Time    |  Number of Friends DELTA  | Found Diff Between
Bob    |  02/01   | unix_ts1 |  NaN                      | (5, NaN)
Kate   |  02/01   | unix_ts2 |  NaN                      | (2, NaN)
Jill   |  02/01   | unix_ts3 |  2                        | (3, 1)
Bob    |  02/01   | unix_ts3 |  2                        | (7, 5)
Kate   |  02/02   | unix_ts4 |  8                        | (10, 2)

So, I have a table where each row is identified by a person's name and a time at which the data was recorded. I would like a query that will go and find instances of "Bob" and find deltas for consecutive timestamps and then give the delta, as well as the two values it found the diff between. I would like this to happen for each person.
I found a method to do this when there is just one value, using lag() command, but that would not do a match by Person. I also know how to do this in Pandas if I downloaded the data, but I am wondering if there is a way to do this in Hive.
Is there a way to do this? Thank you!
Answer: Using lag window function.
select person
      ,date
      ,time
      ,num_friends-lag(num_friends) over(partition by person order by time) as delta
      ,concat_ws(',',num_friends,lag(num_friends) over(partition by person order by time)) as found_diff_between
from tbl


Do all pets deal damage?

Question: In Terraria I have multiple pets. One of my pets is the baby slime. That is (so far) the only pet that will attack for me(on its own). The pet hornet will deal damage but only if I stand in a position that it is touching the enemy. Do all pets deal damage? What pets attack on their own? What pets must follow what the hornet does?
Comment: You mean pets or minions? one thing is to have a pet and another to have minions, minions are summoned with staffs usually.
Comment: Either. --------
Answer: There's an important distinction to make here between Pets and Minions. Pets are intended to be cosmetic, something cool to follow you around that's just for looks, whereas Minions are specifically designed to assist in combat.
All of the PC Pets are pacifists, they don't do any damage at all. That said, two of the mobile edition pets do minor damage; the Android and Elfa pets. A number of the console ones do minor damage as well, namely the Bat, Tiphia, Werewolf and Zombie pets all do damage.
With Minions, them doing damage is the rule, rather than the exception - I don't know of any Minion that doesn't do damage.
You can find the full list of pets here, note the last column which shows which ones can and can't deal damage. As Zerjack noted in the comments, the Baby Slime is actually a Minion rather than a Pet, summoned via the Slime Staff, which is why it does damage to enemies.
Comment: It's because the baby slime it's a minion too, an early game one though.
Comment: @Zerjack Ah, that would explain it. I saw a slime pet on the page and just assumed it was the same one without looking further into it. I'll update the answer accordingly.

Do all pets deal damage?


Retrieve the content of an html page under conditions (with python lxml)

Question: I'll tell you my problem.(Sorry for my english)
I have to connect to a server every day to retrieve content.
The page on which I am connecting is in this form:

thing1.xlsx01 September 2019 10:02:03 /td>1 KB

thing2.pdf02 September 2019 10:02:03 /td>1 KB

thing test 3.pdf04 September 2019 10:02:03 /td>1 KB

thing test 4.pdf04 September 2019 10:02:04 /td>1 KB

thing test 5.pdf04 September 2019 10:02:05 /td>1 KB

From this page (content will be added continuously) I must retrieve the urls (under href) of the files on the current date.
For example, if today is September 04, I have to get my 3 files: "thing test 3.pdf", "thing test 4.pdf" and "thing test 5.pdf" (we notice here that some URLs have spaces).
I started writing a script in python (with lxml), but I'm beginner I could use some help.
# coding: utf-8

from lxml import etree, html
parser = etree.HTMLParser()
tree   = etree.parse("test.html", parser)

URL = tree.xpath('//a/@href')
NAMEFILE = tree.xpath('//a/text()')

print URL

I am able to get my urls but not by today's date. Any ideas?
Answer: For me, the best way is using Beautiful Soup library, you can find detailed info on:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
In your specific case (get dates in the html) this code should be work:
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('test.html'), 'html.parser')

for tag in soup.find_all('tr'):
    print (tag.find_all('td')[1].text)

Comment: Unfortunately on the server it is impossible to find Beautiful Soup (I am on redhat) and it is cut off from the internet (proxy) so I can't download it. Do you have any other ideas?
Comment: @Prodiguy check this, maybe helps: https://stackoverflow.com/questions/18701464/beautifulsoup-installation-or-alternative-without-easy-install
Comment: @Prodiguy You can find the last source files of Beautiful Soup on https://pypi.org/project/beautifulsoup4/#files
Answer: from lxml import etree, html
parser = etree.HTMLParser()
tree   = etree.parse("test.html", parser)

URL = tree.xpath('//a/@href')
NAMEFILE = tree.xpath('//a/text()')

print URL

dates = []
example = "01 September 2019 10:02:03 /td>"
date_tds = tree.findall('.//td')
for i in date_tds:
    if len(str(i.text)) == len(example):
        dates.append(str(i.text).split(" 10")[0])

for index,i in enumerate(dates):
    if "01 September 2019" in i:
        print(URL[index])

If you want to check if it is from todays date.
Best way would be to converse the string of the date to a datetime object and check by todays date.
Comment: I tried your solution but unfortunately it doesn't work :( I have no result
Comment: Are you sure? My solution with the input data from you is: https://www.test.com/thing1.xlsx
The list dates contains all date tds.


Is there a free historic weather data API with Latitude / Longitude support?

Question: I want to extract (free) historic weather data for some countries (more specificaly the provinces / states in some countries) via latitude / longitude and I need the results as a .csv file or pandas data frame. I tried the wrapper for forecast.io / DarkSky  (https://zeevgilovitz.com/python-forecast.io/) but it is limited to 1000 requests per day. So i was wondering if there is any API that is free, returns a pandas data frame or .csv format and that supports langitude / longitude requests?
Here is what I tried (and what is also working if you only want 1000 requests per day).
lat = 30
lng = 5
start_date = datetime.datetime(2016, 1, 1)
attributes = ["temperature", "humidity", "pressure", "windSpeed"]

def getWeatherData(lat, lng, start_date, attributes):

    times = []
    data = {}

    for attr in attributes:
        data[attr] = []

    for offset in range(1, 1000):
        forecast = forecastio.load_forecast(api_key, lat, lng, time=start_date+datetime.timedelta(offset), units="us")
        h = forecast.hourly()
        d = h.data

        for p in d:
            times.append(p.time)
            for attr in attributes:
                data[attr].append(p.d[attr])

    weather_data = pd.DataFrame(data, index=times)

    return weather_data

Comment: Is the csv/df format a hard requirement, or you just need something that Pandas can read?
Answer: https://openweathermap.org/price has an API with some free plans that might be enough if you need < 1000 calls per day
It doesn't return data in csv or DataFrame formats, but pandas can handle the json format it returns
Example:
import requests
import json
import pandas as pd

url = 'https://api.openweathermap.org/data/2.5/onecall?lat=33.44&lon=-94.04&exclude=hourly,minutely&appid=<api_key_hidden>'
data = requests.get(url).json()

df = pd.DataFrame.from_dict(data['daily'])


How to use XCode's mergetool to resolve conflicts?

Question: I'm in the middle of a rebase and I need to fix some merge conflicts. When I open the file in XCode, I see the source control conflict markers (<<<<<<<, etc) in the file.
How can I use XCode's mergetool to resolve these conflicts in a graphical fashion? I'm looking for this screen:
Comment: @matt See my comment on your answer. It's not about *needing* a better tool, it's about knowing one is available but not knowing how to access it. Saying FileMerge is an equivalent graphical interface to imgur.com/hI82XQE is like saying TextEdit is equivalent to XCode when editing swift files. I'd like to use a code editor designed for swift files when resolving conflicts with my swift files. XCode has this functionality, I just don't know how to access it.
Comment: Yes, I did. Should I have done it inside xcode? I don't even know how to do that... If you have merge conflicts , XCode behaves differently depending on how you got into that situation?
Comment: Actually my point was just the opposite: no you shouldn't have done it inside Xcode because you can't, so you must have done it elsewhere — so why then do you want to use Xcode to resolve the conflict? For example, if you did a rebase using SourceTree, you can resolve the conflict using SourceTree — or, as I said, just directly in the text, which is often far and away the simplest approach.
Comment: So I guess that's the unfortunate answer to my question. As you've been saying, it's impossible to use that tool to solve merge conflicts during a rebase. XCode simply doesn't support the rebase flow. https://stackoverflow.com/a/8737859/1160216. Apparently the only way to launch that tool is to do a merge using XCode's UI as described on the page where I got the screenshot in the first place: https://www.raywenderlich.com/675-how-to-use-git-source-control-with-xcode-9. WBN if you could launch that tool and use it on any file with source code markers in the file, like you can with FileMerge.
Comment: Why not just resolve the conflict directly in the text? — Also, how did you get into this situation? I'm betting you did the rebase outside of Xcode, right?
Comment: @MikeMiller To clarify matt's first question, in the part of your screenshot highlighted in blue, there's a switch between the two versions of the file. Click the switch to choose which version to use. In your screenshot the version on the right would be used if you clicked the Merge button.
Comment: @MarkSzymczyk My problem is I don't know how to get to the screen in my screenshot (I found the screenshot online somewhere). It doesn't come up when I launch the FileMerge tool as in matt's answer. That launches something else: https://imgur.com/hI82XQE. Do I have an old version of FileMerge or something? I'm running XCode 10.1...
Comment: But you don't _need_ the screen in your screenshot, because FileMerge provides an equivalent graphical interface for resolving merge conflicts.
Comment: But how can you access it when you didn't do the merge in Xcode? Your requirements make no sense. Xcode has no idea what's going on here. You are in the middle of a rebase performed completely outside of Xcode sphere of understanding. It seems to me you don't really have a question: you're just complaining that Xcode's git support is very limited. But, as I said in an early comment, we already _know_ that.
Answer: Pulling the answer from here
# Tell system where Xcode utilities live:
sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer

# Set "opendiff" as the default mergetool globally:
git config --global merge.tool opendiff

Then, when git tells you that there is a conflict, you can run git mergetool and it will open XCode's mergetool (like in the question's screenshot) and you can work through the conflict.
Comment: That's the sort of thing I told him too. Unfortunately it isn't the answer he wants.
Comment: It was a great solution for me.
Answer: The FileMerge tool is a separate application, which you can open from the Xcode menu:
Comment: Note that if you are using an external graphical git interface such as SourceTree, you can designate FileMerge as the graphical merge tool.
Comment: I do like your answer, though. I didn't know how to access FileMerge from XCode - thanks for sharing! Unfortunately, FileMerge is not the tool I'm looking for.
Comment: FileMerge doesn't look like what's in my screenshot. It looks like this: https://imgur.com/hI82XQE. I'm running XCode 10.1. Do I need to update FileMerge somehow? Is what's in my question's screenshot not FileMerge?
Comment: I don't understand what you want.  This is a rebase conflict done outside of Xcode so I presume you're not going to get the same screen you showed in your original screenshot. Your imgur screen shot shows a wonderful interface for resolving the merge conflict graphically. Or, as I said before, it's trivial just to do it by editing the text directly. The problem is solved. Resolve the conflict and move on.
Comment: This "wonderful interface" doesn't have syntax highlighting or any of the features that makes XCode usable. It's just a vanilla text editor. I'd like to fix my merge conflicts within XCode's editor. I know it's possible to fix all the errors by hand. It's also possible to write code in TextEdit, but why would you when there are better tools to make your life easier? "what I want" is to access the tool in my question's screenshot, which will make my life easier. It exists. How can I access it?
Answer: I think you are mixing up Xcode version control and merge tool.  You can look at git changes with:
View > Version Editor > Show Comparison View.
And it will show you a side by side of before and after commits.  Doesn't help you much with Merge conflicts to my knowledge though.
If you have a tough merge conflict such as in your pbxproj file, then I recommend opening that file with visual studio.
Or maybe this?


inequivalent arg 'x-queue-type' for queue 'email.queue' in vhost 'Email': received none but current is the value 'quorum' of type 'longstr'

Question: I have WSO2 project which has RabbitMQ message store configured as follows:
<messageStore class="org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore" name="EmailErrorPendingMS" xmlns="http://ws.apache.org/ns/synapse">
    <parameter name="store.rabbitmq.host.name">rabbitmq-staging</parameter>
    <parameter name="store.producer.guaranteed.delivery.enable">false</parameter>
    <parameter name="store.rabbitmq.host.port">5672</parameter>
    <parameter name="store.rabbitmq.route.key">email.key</parameter>
    <parameter name="store.rabbitmq.username">guest</parameter>
    <parameter name="store.rabbitmq.virtual.host">Email</parameter>
    <parameter name="rabbitmq.connection.ssl.enabled">false</parameter>
    <parameter name="store.rabbitmq.exchange.name">email.exchange</parameter>
    <parameter name="store.rabbitmq.queue.name">email.queue</parameter>
    <parameter name="store.rabbitmq.password">guest</parameter>
</messageStore>

When running the project I am getting the following exception:
INFO {org.apache.synapse.config.xml.MessageStoreFactory} - Successfully added Message Store configuration of : [EmailMS].
INFO {org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore} - Store [EmailMS] Successfully connected to RabbitMQ Broker
ERROR {org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore} - Store [EmailMS]. Initialization failed... java.io.IOException
    at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:129)
    at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:125)
    at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:147)
    at com.rabbitmq.client.impl.ChannelN.queueDeclare(ChannelN.java:968)
    at com.rabbitmq.client.impl.recovery.AutorecoveringChannel.queueDeclare(AutorecoveringChannel.java:333)
    at org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore.declareQueue(RabbitMQStore.java:308)
    at org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore.init(RabbitMQStore.java:125)
    at org.apache.synapse.deployers.MessageStoreDeployer.deploySynapseArtifact(MessageStoreDeployer.java:59)
    at org.apache.synapse.deployers.AbstractSynapseArtifactDeployer.deploy(AbstractSynapseArtifactDeployer.java:205)
    at org.wso2.micro.integrator.initializer.deployment.synapse.deployer.SynapseAppDeployer.deployArtifactType(SynapseAppDeployer.java:1129)
    at org.wso2.micro.integrator.initializer.deployment.synapse.deployer.SynapseAppDeployer.deployArtifacts(SynapseAppDeployer.java:139)
    at org.wso2.micro.integrator.initializer.deployment.application.deployer.CappDeployer.deployCarbonApps(CappDeployer.java:189)
    at org.wso2.micro.integrator.initializer.deployment.application.deployer.CappDeployer.deploy(CappDeployer.java:146)
    at org.apache.axis2.deployment.repository.util.DeploymentFileData.deploy(DeploymentFileData.java:136)
    at org.apache.axis2.deployment.DeploymentEngine.doDeploy(DeploymentEngine.java:807)
    at org.apache.axis2.deployment.repository.util.WSInfoList.update(WSInfoList.java:153)
    at org.apache.axis2.deployment.RepositoryListener.update(RepositoryListener.java:377)
    at org.apache.axis2.deployment.RepositoryListener.checkServices(RepositoryListener.java:254)
    at org.apache.axis2.deployment.DeploymentEngine.loadServices(DeploymentEngine.java:135)
    at org.wso2.micro.core.CarbonAxisConfigurator.deployServices(CarbonAxisConfigurator.java:530)
    at org.wso2.micro.integrator.initializer.deployment.AppDeployerServiceComponent.invokeRegisteredDeployers(AppDeployerServiceComponent.java:227)
    at org.wso2.micro.integrator.initializer.deployment.AppDeployerServiceComponent.activate(AppDeployerServiceComponent.java:74)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:260)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
    at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:343)
    at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:113)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:985)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:234)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:151)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:866)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:804)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:130)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:228)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:525)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:544)
    at org.wso2.micro.integrator.initializer.ServiceBusInitializer.activate(ServiceBusInitializer.java:192)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:235)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
    at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:343)
    at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
    at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:113)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.dispatchEvent(BundleContextImpl.java:985)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:234)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:151)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEventPrivileged(ServiceRegistry.java:866)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.publishServiceEvent(ServiceRegistry.java:804)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistrationImpl.register(ServiceRegistrationImpl.java:130)
    at org.eclipse.osgi.internal.serviceregistry.ServiceRegistry.registerService(ServiceRegistry.java:228)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:525)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.registerService(BundleContextImpl.java:544)
    at org.wso2.micro.integrator.ntask.core.internal.TasksDSComponent.activate(TasksDSComponent.java:147)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:260)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
    at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
    at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
    at org.eclipse.equinox.internal.ds.Resolver.buildNewlySatisfied(Resolver.java:473)
    at org.eclipse.equinox.internal.ds.Resolver.enableComponents(Resolver.java:217)
    at org.eclipse.equinox.internal.ds.SCRManager.performWork(SCRManager.java:816)
    at org.eclipse.equinox.internal.ds.SCRManager$QueuedJob.dispatch(SCRManager.java:783)
    at org.eclipse.equinox.internal.ds.WorkThread.run(WorkThread.java:89)
    at org.eclipse.equinox.internal.util.impl.tpt.threadpool.Executor.run(Executor.java:70)
    Suppressed: com.rabbitmq.client.AlreadyClosedException: channel is already closed due to channel error; protocol method: #method<channel.close>(reply-code=406, reply-text=PRECONDITION_FAILED - inequivalent arg 'x-queue-type' for queue 'email.queue' in vhost 'Email': received none but current is the value 'quorum' of type 'longstr', class-id=50, method-id=10)
        at com.rabbitmq.client.impl.AMQChannel.processShutdownSignal(AMQChannel.java:401)
        at com.rabbitmq.client.impl.ChannelN.startProcessShutdownSignal(ChannelN.java:292)
        at com.rabbitmq.client.impl.ChannelN.close(ChannelN.java:613)
        at com.rabbitmq.client.impl.ChannelN.close(ChannelN.java:547)
        at com.rabbitmq.client.impl.ChannelN.close(ChannelN.java:540)
        at com.rabbitmq.client.impl.recovery.AutorecoveringChannel.close(AutorecoveringChannel.java:73)
        at org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore.init(RabbitMQStore.java:128)
        ... 74 more
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=406, reply-text=PRECONDITION_FAILED - inequivalent arg 'x-queue-type' for queue 'email.queue' in vhost 'Email': received none but current is the value 'quorum' of type 'longstr', class-id=50, method-id=10)
    at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66)
    at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36)
    at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:502)
    at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:293)
    at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:141)
    ... 78 more
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=406, reply-text=PRECONDITION_FAILED - inequivalent arg 'x-queue-type' for queue 'email.queue' in vhost 'Email': received none but current is the value 'quorum' of type 'longstr', class-id=50, method-id=10)
    at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:522)
    at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:346)
    at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:182)
    at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:114)
    at com.rabbitmq.client.impl.AMQConnection.readFrame(AMQConnection.java:719)
    at com.rabbitmq.client.impl.AMQConnection.access$300(AMQConnection.java:48)
    at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:646)
    at java.base/java.lang.Thread.run(Thread.java:834)

Comment: Do you have access to the RabbitMQ admin console? If it is the case, can you check what is currently configured?
Comment: @Olivier, yes I have but what exactly I should check for?
Comment: If the configuration you requested is already present (exchange **mail.exchange**, queue **mail.queue**, and specifically what are the attributes of the queue if already present (is it a classic or quorum queue)
Answer: Here's the code of the RabbitMQ Message Store https://github.com/wso2/wso2-synapse/blob/728985f1b68dd241e336f66ac312847c12417f10/modules/core/src/main/java/org/apache/synapse/message/store/impl/rabbitmq/RabbitMQStore.java#L307
    private void declareQueue(Channel channel, String queueName) throws IOException {
            channel.queueDeclare(queueName, true, false, false, new HashMap<String, Object>());
        }

As you can see, the queue properties is an empty HashMap, and in the case of a quorum queue x-queue-type: quorum
For detail, see Declaration and Property Equivalence
Therefore, when redeclaring an existing queue or exchange with non-matching properties will fail with a 406 PRECONDITION_FAILED error
If you decide to go with quorum queue, you have to extend the Message Store class to support parameter in declareQueue function


Pylibpcap for python-3.x

Question: There was a library pylibpcap for python2 that contained the functionality to create pcap objects like this:
import pcap

pc = pcap.pcapObject()

Now I'm looking for an analogue for python3, but from what I found (pypcap, pcap-ct), these libraries don't contain similar functionality and look completely different. So maybe someone knows how the pylibpcap library can be replaced in python3? I will be grateful for any advice.
Answer: You can use this package similar to your requirement, installation steps mentioned below:
$ sudo apt-get install libpcap-dev
$ pip3 install Cython python-libpcap

And usage as below:
from pylibpcap import OpenPcap
p = OpenPcap("pcap.pcap", "a")
p.write(buf)

Answer: You can store pcap files in python using scapy module. install it by -
pip install scapy

You can store the network traffic in pcap files using scapy. More info at this link - creating a pcap file using python
Comment: While it is viable for some applications, I have found that scapy only lets you process around 1000 packets per second, which in modern times is painfully slow. The more native the binding, the better for performance.

The scapy implementation is also documented badly.

Pylibpcap for python-3.x


Series of if statements functioning incorrectly

Question: I have a set of if statements that searches the raw hhtml body of an email defined by $html_part, that will replace the email's cid: text  with a relative hyperlink to the actual image that is being saved.
The problem is, if the html body of the email contains only .jpg images, they are numbered sequentially such as  image001.jpg, image002.jpg, image003.jpg. If theres a .png image first then 2 .jpg images following it, it will become, image001.png, image002.jpg, image003.jpg.
But at the moment i am testing it out with an email with 3 .jpg images only but it replaces all the email's cid parts with the first matched image, instead of sequentially. Now the image it's too be replaced with is in the directory i have a side-script for that, which does this automatically. It extracts all the images from the email and places them in a folder.
What is wrong with the if statements, why are they not replacing accordingly?
/***************************** 1st image in email**********************************/
if (preg_match('/cid:([^"@]*).(png|jpg|gif|bmp)@([^"]*)/', $html_part, $m)){

    $find = '/cid:([^"@]*).'.$m[2].'@([^"]*)/';

    if ($m[2] == 'png') $replace = $png1;
    if ($m[2] == 'jpg') $replace = $jpg1;
    if ($m[2] == 'gif') $replace = $gif1;
    if ($m[2] == 'bmp') $replace = $bmp1;

    $html_part = preg_replace($find, $replace, $html_part);
}

if (preg_match('/cid:([^"@]*).(png|jpg|gif|bmp)@([^"]*)/', $html_part, $m)){

    $find = '/cid:([^"@]*).'.$m[2].'@([^"]*)/';

    if ($m[2] == 'png') $replace = $png2;
    if ($m[2] == 'jpg') $replace = $jpg2;
    if ($m[2] == 'gif') $replace = $gif2;
    if ($m[2] == 'bmp') $replace = $bmp2;

    $html_part = preg_replace($find, $replace, $html_part);
}

/***************************** 3rd image in email**********************************/
if (preg_match('/cid:([^"@]*).(png|jpg|gif|bmp)@([^"]*)/', $html_part, $m)){

    $find = '/cid:([^"@]*).'.$m[2].'@([^"]*)/';

    if ($m[2] == 'png') $replace = $png3;
    if ($m[2] == 'jpg') $replace = $jpg3;
    if ($m[2] == 'gif') $replace = $gif3;
    if ($m[2] == 'bmp') $replace = $bmp3;

    $html_part = preg_replace($find, $replace, $html_part);
}

Comment: put the less restrictive conditions **first** and continue with the most restrictive ones (maybe your input case is falling within the first condition, because is more restrictive). Also, try using the **if/else** logic (not only ifs), or a **switch/case**
Comment: Could it be that your second (and third) preg_match matches the string you've just replaced in the first (and second) preg_replace ?
Comment: @huelbois That is what i'm thinking as well, and **Kani** i have used the else statements as well and still it produces the same result
Answer: Use instead:
if(this is it){

//somecode

}elseif(this is it){

//somecode
}

Answer: Your preg_replace matches ALL instance of $find in $html_part.
But in $find, you only have the $m[2] part changing, you don't reinject the $m[1] that you've just matched.
Not sure, but you should have something like this (not tested):
$find = '/cid:'$m[1].'.'.'.$m[2].'@([^"]*)/';

Comment: Thanks! That worked. I just had to modify your example code:

     `$find = '/cid:'.$m[1].'.'.$m[2].'@([^"]*)/';`
You had an extra single quote near the $m[2]
Answer: The reason this isn't working is that preg_replace replaces ALL matches.  The regex you pass in is searching for all images with the same extension.
What you have:
$find = '/cid:([^"@]*).'.$m[2].'@([^"]*)/';

/cid:([^"@]*).jpg@([^"]*)/ - match all jpgs

What you want is:
$find = '/'.$m[0].'/';

/cid:image001.jpg@1REG5DS/ - match only this jpg file


`bash: scp: command not found` while I do have `scp` in `$PATH`

Question: Sorry for cross posting of this question which is also posted at superuser
About off-topic: The remote server is ubuntu, the client side is on linux mint.
Here is my screen copy:

As shown in the screen copy, the scp command failed with
bash: scp: command not found
lost connection

However after I ssh into the remote server and type scp I can see that command is available, and my $PATH environment is good.
If I tried to install openssh-client as suggested in many places it says the openssh-client is already the newest version
Now I am stucked and don't know what's wrong with the scp command. Any idea?
Update
I have openssh-client installed locally, nothing wrong with the local environment:

Updates II
A screen copy shows that scp command available on both ends:
Comment: a) Don't cross-post. b) Please don't post screenshots of text.
Comment: Since you are trying to `scp` **from** your local machine (`luog-Sattelite-P50A`) **that's** the one that needs to have `openssh-client` installed on it - the fact that it's installed and in your `PATH` on the remote server is irrelevant.
Comment: Being an native linux user for 5 years and play with computer for over 20 years I know exactly what I am talking about. No, my local mint 18 has the scp installed from the very beginning. And yes I can scp to many other remote servers.
Comment: The comment about the remote server having `scp` being irrelevant is based on your question's text and image. At no point do you say, or show, that `scp` is in the `PATH` of `luog@loug-Satellite-P50-A`, or that `openssh-client` is installed there, let alone current. Based on your question we can only presume that you haven't checked those facts. I've been using computers for 4½ _decades_ and yet I still have __Doh!__ moments. They happen. Please update the question to show output from investigations on the _local_ system.
Comment: Please see updates to the question
Comment: Use text for textual output.
Answer: To be able to use scp, you need the scp binary in both client and server (and therefore installed openssh-client package)!
Comment: Ha! Didn't realize that for a looong time.


How are you supposed to buy epoxy?

Question: I have a project where we would want to do a flooring with epoxy for a water closet downstairs (because screw doing ceramic tiles) but really, buying epoxy resin seems a pretty hard thing to do.
The retailers here in Quebec dont seem to simply carry it (Home Depot, Rona, etc.) And it seem my only choice for buying it is speciality websites that would I guess send it by delivery and it does feel weird to receive chemicals by mail.
So is there a hurdle I'm not seeing? Do you absolutely have to go with experts to make epoxy for flooring?
How am I supposed to buy Epoxy? And more specifically flooring epoxy for a water closet?
Comment: There is nothing odd about delivering "chemicals" in a truck to your home.   If you don't have them delivered, they'll be delivered in a truck to the store and then in your car.  If your local shops don't carry what you want, I don't see what choice you have.     For a small WC why not just use vinyl?  It's so easy and cheap ... vinyl planks or a one-piece sheet to cover the whole room.  It will look and feel as good or better than epoxy.
Comment: You're probably shopping the wrong stores, since most use of epoxy flooring (particularly epoxy with broadcast color-chip type flooring) is industrial/commercial, not home-center customers.
Comment: Have you tried marine supply places?
Comment: While not an off-topic "product recommendation" question, this is an equally off-topic, "vendor recommendation" question. You buy the product wherever it's sold. If you're not comfortable buying it there, you either find another vendor or you don't buy it. If it were illegal to ship the "chemicals" you're interested in buying, then it wouldn't be sold by vendors who ship it. eg: Stand alone Li-Ion batteries cannot be air freighted. So they're sent by ground transport only. Doesn't mean you can't buy replacement Li-Ion batteries online.
Comment: do you have amazon where you live? they have tons of it.
Answer: I recently saw large containers of it while browsing at DeSerres (the arts & craft store). I have no idea if the pricing is reasonable but you can walk out of there with several gallons.
Answer: If there are any marinas or supply houses for boats that sell what is needed to outfit a boat, they will have the resin and fiberglass cloth if you need it.
I have seen gallon kits on the shelf of the West Marine I visited, but I only needed a quart kit.  ( Disclaimer: No I am not affiliated with West Marine. They happen have what I needed at the time)
Comment: Better to look for small family owned chandleries other than West Marine. West Marine has the popular stuff but they're overpriced (except on certain select loss-leaders in the flyer)... in other words, the Home Depot of marine LOL. The dominant brand of marine epoxies is  **West *System*** (totally unrelated to West Marine, and sanely priced as a rule).

How are you supposed to buy epoxy?


Website Forms to iphone app

Question: I've been researching for ages and still cannot find an easy solution that perfectly. So i stopped and figured i was going about this project the wrong way. All i need is an easy solution.
My project requires me to make a website that has forms (fields include images, text, urls, colors). When the user submits this form, somehow (THIS IS THE KEY QUESTION), gets sent to Xcode so that it can be used in and iPhone app.
My questions: What is an easy to use program to make a website that can do what i said? How does my website connect to Xcode (supply it with the data)? Is it possible for my app to check for newly submitted info?
Keep in mind that i don't have much coding knowledge as far as websites and i only a little about making iPhone apps (Yes, i have made some but not as advanced as this)
Thank you in advance!
Comment: O'Reilly sells a book specifically about web development for the mobile environment.  That's where you want to start.
Answer: The workflow you describe doesn't make any sense.
It starts out easily enough: you have a website that has a form with a submit button. No problem there. Hitting submit likely does a POST to a server somewhere. Again, no problem.
Then you say the form data has to ultimately end up in Xcode. This is where things are really muddled. Xcode is a programming IDE for Mac OS X. I'm not sure how or what it has to do with handling data from a Web form. The two things are, for all intents and purposes, completely independent technologies.
Please describe in much more detail exactly why you think you need to "send data to Xcode". Otherwise, your question, as written, is unanswerable.
Answer: It sounds like you want to build an IOS app that can retrieve user submitted data from the server.
Your form will have to post the data to the server where it is stored in your database.  Images will have to be uploaded to the server as well.
You can then build a server-side api that returns data to the IOS device upon request.  You can have your IOS app regularly request data from the server, receive the response and store what you need on the device.
There is a lot more to it of course, but from what I can gather from your post, this is what you're looking to do.
Comment: yes exactly. how? as far as a tutorial, how to make a website that can connect to a server that can do this. Code? Steps? Etc

Website Forms to iphone app