text:
Q: React setstate does not work in IE11 after render is called I am new to react development and I have a react app where on the componentDidMount am setting the state of value as "add" and it renders the div content for "add" and once button click on the add div am calling an addstate method
where am setting the state of the value as "edit" and it renders the div content with respect to "edit" and where i call again the addstate method through done method call.
In this case the fetch call from addstate method is happening to the backend but the state is  not setting back to edit..it fails only in IE11. It works on chrome, firefox and mobile devices.
If i remove the piece of code "Value:edit" in addstate method its working good. But my requirement needs to render based upon different scenarios. so basically am able to set the state of the result only once in IE11. it does not work repeatedly.
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: "test",
            items: []
        }

    };

    addState() {
        fetch("/local/addThings").then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        value: "edit",
                        items: result
                    });
                   }
            )
            .catch(error => console.error('Error:', error));
    }

     done() {
          this.setState({
               value: "add"
              });

             }
    componentDidMount() {

        fetch("/local/getThings")
            .then(
                (result) => {
                       this.setState({
                            value: "add"
                        });

                }
            )
            .catch(error => console.error('Error:', error));

    }

    render() {
        const { value, items } = this.state;

        if (value === "add") {
            return

 this.addState()}>

AddButton

                ;
        }
        if (value === "edit") {
            return (

 this.done()}>

SaveButton

                         {items.map(item => (

{item.name}

                            ))}

            );
        }

        }

}
ReactDOM.render(React.createElement(App, null), document.getElementById("details")); ```

A: Try binding your method and refer to it directly in your onClick event:
lass App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: "test",
            items: []
        }
        this.addState = this.addState.bind(this);

    };

    addState() {
        fetch("/local/addThings").then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        value: "edit",
                        items: result
                    });
                   }
            )
            .catch(error => console.error('Error:', error));
    }

     done() {
          this.setState({
               value: "add"
              });

             }
    componentDidMount() {

        fetch("/local/getThings")
            .then(
                (result) => {
                       this.setState({
                            value: "add"
                        });

                }
            )
            .catch(error => console.error('Error:', error));

    }

    render() {
        const { value, items } = this.state;

        if (value === "add") {
            return <div >
                <div >
                    <ul >
                        <li onClick={this.addState}>
                            <div>
                                <img src="Add.png" />
                                <center><p>AddButton</p></center>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
                ;
        }
        if (value === "edit") {
            return (<div>
                <div >
                    <ul >
                        <li onClick={() => this.done()}>
                            <div >
                                <img src="Save.png" />
                                <center><p>SaveButton</p></center>
                            </div>
                        </li>
                         {items.map(item => (
                                      <center><p>{item.name}</p></center>

                                </li>
                            ))}
                   </ul>

                </div>
            </div>

            );
        }

        }

}

A: I added settimeout in my methods and it worked in IE. It seems like the response was slower in IE for the API calls. Not sure if there is a workaround or this is the right approach.
        fetch("/local/addThings").then(res => res.json())
            .then(
                (result) => {
                 setTimeout(() => {
                    this.setState({
                        value: "edit",
                        items: result
                    });
                     }, 200);
                       }
            )
            .catch(error => console.error('Error:', error));
    }```


text:
Q: how to set up UWP C# StorageFile to store a SoftwareBitmap to a specific path I'm trying to save a SoftwareBitmap to a file.
But I get error "The parameter is incorrect" when I do:
 StorageFile.GetFileFromPathAsync()
HERE IS THE ERROR...….

pathname = "diag ProcessFrame .JPG"
CODE FOR EVENT HANDLER FOR WEBCAM USB FRAME...……
        private void FrameReader_FrameArrived(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
    {
        // Get frame image from camera:
        using (var frame = sender.TryAcquireLatestFrame())    //  ==>  MediaFrameReference
        {
            // Got image?
            if (frame != null)
            {
                var renderer = _frameRenderers[frame.SourceKind];

                        renderer.ProcessFrame(frame);
            }
        }
    }

    // Process latest frame received from USB webcam.
    public void ProcessFrame( MediaFrameReference frame)
    {
        // Convert frame to a SoftwareBitmap of a valid format to display in an Image control:
            //      SoftwareBitmap Class
            //          https://learn.microsoft.com/en-us/uwp/api/windows.graphics.imaging.softwarebitmap?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(Windows.Graphics.Imaging.SoftwareBitmap)%3Bk(TargetFrameworkMoniker-.NETCore%2CVersion%3Dv5.0)%3Bk(DevLang-csharp)%26rd%3Dtrue
            var softwareBitmap = FrameRenderer.ConvertToDisplayableImage(frame?.VideoMediaFrame);

        if (softwareBitmap != null)
        {
            // Swap the processed frame to _backBuffer and trigger UI thread to render it
            softwareBitmap = Interlocked.Exchange(ref _backBuffer, softwareBitmap);          // does bytes = h X w ?

            // UI thread always reset _backBuffer before using it.  Unused bitmap should be disposed.
            softwareBitmap?.Dispose();

            ////////////////////////   DISPLAY FRAME LOCALLY   /////////////////////////

            // Changes to xaml ImageElement must happen in UI thread through Dispatcher
            var task = _imageElement.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                async () =>
                {
                    // Keep draining frames from the backbuffer until the backbuffer is empty.
                    SoftwareBitmap latest_frame_SoftwareBitmap;
                    while (( latest_frame_SoftwareBitmap = Interlocked.Exchange(ref _backBuffer, null)) != null)
                    {
                                                         // Diag to save frame to a file:
                                                                 //VideoMediaFrame inputFrame    =     frame.VideoMediaFrame;
                                                                 //SoftwareBitmap  frame_SoftwareBitmap = inputFrame.SoftwareBitmap;

                                                                 Common.SaveSoftwareBitmapToFile( latest_frame_SoftwareBitmap, "diag ProcessFrame .JPG");

                    . . .

        }

    // Saves encoded (ie. compressed) SoftwareBitmap image pixel data to a specific file pathname.
    public static async void SaveSoftwareBitmapToFile(SoftwareBitmap softwareBitmap, String pathname)
    {

        StorageFile outputFile = await StorageFile.GetFileFromPathAsync( pathname );
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  ERROR OCCURS HERE

        using (IRandomAccessStream stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            // Create an encoder with the desired format
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

            // Set the software bitmap
            encoder.SetSoftwareBitmap(softwareBitmap);

            // Set additional encoding parameters, if needed
            //encoder.BitmapTransform.ScaledWidth = 320;
            //encoder.BitmapTransform.ScaledHeight = 240;
            //encoder.BitmapTransform.Rotation = Windows.Graphics.Imaging.BitmapRotation.Clockwise90Degrees;
            //encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
            encoder.IsThumbnailGenerated = true;

            try
            {
                await encoder.FlushAsync();
            }
            catch (Exception err)
            {
                const int WINCODEC_ERR_UNSUPPORTEDOPERATION = unchecked((int)0x88982F81);
                switch (err.HResult)
                {
                    case WINCODEC_ERR_UNSUPPORTEDOPERATION:
                        // If the encoder does not support writing a thumbnail, then try again
                        // but disable thumbnail generation.
                        encoder.IsThumbnailGenerated = false;
                        break;
                    default:
                        throw;
                }
            }

            if (encoder.IsThumbnailGenerated == false)
            {
                await encoder.FlushAsync();
            }

        }
    }

A: From the documentation of StorageFile:

ArgumentException
The path cannot be a relative path or a Uri. Check
  the value of path.

You need to specify an absolute path to the file.
Unrelated note: I would try some better naming conventions for your files. The extra space between the name and extension is kind of unconventional (and could cause problems for certain file systems like svn on a unix/linux based OS). From the context, a file name like "C:/path/to/diagProcessFrame.jpg" would honestly appear to look just fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: onItemSelected Listner are not trigger with the long String array from database UPDATE:
I found the problem, the problem may cause by get the adapter content from SQL requset. Now I post my getLockerList() code here now.
I tested the function with long string
"asdajdnajkdaadasdaajd najkdaadasdaajdnajkdaadasdaajdnajkdaadasdaajdnaj kdaadasdaajdnajkdaadasdasdas"

and it still could work perfectly, so now I guess the problem is come from when I got the data.
I set a spinner with arrayadapter. The content of adapter is come from MySQL request.
I got the data and create the adapter successfully, but when I try to show what item was selected by user, it show nothing after I click the item.
I've tried add some system print to find out the problem, finally I found that the problem is the listener not even call, no matter onItemSelected or onNothingSelected
I think I may find the problem now, my view list is stored different location which is very long String. I tried change the content of the adapter to "test" and it work perfectly. So now the problem is now can I display the long string?
Here is my code:
public class PlaceOrderActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private Spinner from_spinner;
    private ArrayList<String> locker_list = new ArrayList<String>();

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

        from_spinner = (Spinner) findViewById(R.id.from_spinner);
        from_spinner.setVisibility(View.VISIBLE);
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,locker_list);
        from_spinner.setAdapter(adapter);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        from_spinner.setOnItemSelectedListener(this);
    }

    private void getLockerList() {
         // Response received from the server
    Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONArray jsonResponse = new JSONArray(response);
                //JSONObject jsonObject = jsonResponse.getJSONObject(0);
                if (jsonResponse!=null) {
            //        System.out.println(jsonResponse);
                    for (int i=0;i< jsonResponse.length();i++)
                    {
                        JSONObject jsonObject = jsonResponse.getJSONObject(i);
                        String location = jsonObject.getString("location1")+" "+jsonObject.getString("location2")+" "+jsonObject.getString("location3");
                        locker_list.add(location);
                    }
                } else {
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error);
        }
    };
    getLoockerLocationRequest request = new getLoockerLocationRequest(responseListener,errorListener);
    RequestQueue queue = Volley.newRequestQueue(PlaceOrderActivity.this);
    queue.add(request);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        System.out.println("selected item");
        Toast.makeText(parent.getContext(),from_spinner.getSelectedItem().toString(),
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        System.out.println("nothing select");
        String no_selected_value = "Select the location";
        Toast.makeText(parent.getContext(),no_selected_value,
                Toast.LENGTH_SHORT).show();
    }

}

A: I solved the problem.
I don't know what is the concept of it. But if I add one extra item to the arraylist, no matter the item is "" (just blank/nothing inside) or "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
The program will became could run perfectly.
So I just add one locker_list.add(""); before the adapter create.
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_place_order);
        locker_list.add("");
        getLockerList();
        from_spinner = (Spinner) findViewById(R.id.from_spinner);
        from_spinner.setVisibility(View.VISIBLE);
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,locker_list);
        from_spinner.setAdapter(adapter);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        from_spinner.setOnItemSelectedListener(this);
    }


text:
Q: How to copy a graph in JGraphT? I need make a copy of a simple graph.
I don't see a graph duplicator among graph generators
and UndirectedGraph doesn't implement a clone method.
Year, I can copy a graph by hands.
But I want to do this in one line.

A: UndirectedGraph is an interface.  However, most of the concrete subclasses (e.g. SimpleGraph) extend AbstractBaseGraph which does implement the clone() method.
So, if you can guarantee that the UndirectedGraph you have in your hand inherits from AbstractBaseGraph, simply cast to AbstractBaseGraph and call the clone method.
public void someMethod(UndirectedGraph g)
{
  // Do some stuff...

  ((AbstractBaseGraph)g).clone(); // <== Your 1-liner

  // Do some more stuff...
}

Bear in mind though, that according to the JavaDoc, the clone() method does a shallow clone.  So the graph instance is cloned but the vertices and edges within it aren't.

A: A very crude (but quick) solution to copy a graph would be:
    DirectedGraph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
    DirectedGraph<String, DefaultEdge> revGraph = new EdgeReversedGraph<>(graph);
    DirectedGraph<String, DefaultEdge> graphCopy = new EdgeReversedGraph<>(revGraph);
    //To reduce the memory complexity
    revGraph = null;

However, it is to be kept in mind that the solution would have high memory & computation complexity if the graph is too big. Discarding the intermediate reversed graph would improve the solution.


text:
Q: C++ Pointer being freed was not allocated (possibly, an issue with unique_ptr or boost::ublas) This is a follow up on one of my previous questions. The issue that I am dealing with is explained in detail in the formulation of the aforementioned question. Unfortunately, I was not able to provide a minimal example that showcases the problem.
In this question, I am making an attempt to redefine the problem and provide a minimal example. The code presented in the example below executes and does what it is supposed to do. However, in a slightly more complex case presented in the previous question, sometimes, it results in the runtime error
dynamic_links(3941,0x7fff749a2310) malloc: *** error for object 0x61636f6c65720054: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug

Unfortunately, I was only able to produce the error when the optimisation is set to -O3 (possibly -O2 as well). This creates a problem when using debugging tools. Unfortunately, I was not able to reproduce the problem with no/minimal code optimisation. For a reference, I am using gcc 4.9.1.
In the present question, I would like to understand if the structural design of the class inheritance mechanism that I am using could, potentially, be dangerous from the perspective of the dynamic memory allocation. Please find the code below:
namespace ublas = boost::numeric::ublas;

template<typename TScalarType = double>
using ublasRn = ublas::vector<TScalarType>;

class Base
{
public:
    virtual ~Base(void) = 0;
};
Base::~Base(void){}

template<typename T1, typename T2>
class Composite : public Base
{
protected:
    T1 T1Instance;
    std::unique_ptr<T2> u_T2Instance;
public:
    Composite(){}
    virtual ~Composite(void){}
    const std::type_info& returnT1TypeID(void) const
        {return typeid(T1);}
    const std::type_info& returnT2TypeID(void) const
        {return typeid(T2);}
};

template<typename T2>
class CompositeCT: virtual public Composite<double, T2>
{
public:
    using Composite<double, T2>::Composite;
    virtual ~CompositeCT(void)
        {}
};

template<typename T1>
class CompositeRn: virtual public Composite<T1, ublasRn<double>>
{
public:
    using Composite<T1, ublasRn<double>>::Composite;
    virtual ~CompositeRn(void){}
};

class CompositeCTRn :
    public CompositeCT<ublasRn<double>>,
    public CompositeRn<double>
{
public:
    CompositeCTRn(void):
        Composite<double, ublasRn<double>>(),
        CompositeCT<ublasRn<double>>(),
        CompositeRn<double>()
        {};
};

template<typename T1, typename T2, class TComposite>
class Trajectory: public Base
{
protected:
    std::vector<std::unique_ptr<TComposite>> m_Trajectory;
public:
    Trajectory(void)
        {checkType();}
    void checkType(void) const
        {
            TComposite CI;
            if (
                !(
                    CI.returnT1TypeID() == typeid(T1) &&
                    CI.returnT2TypeID() == typeid(T2)
                    )
                )
            throw std::runtime_error("Error");
        }
    virtual ~Trajectory(void){}
};

int main()
{

    Trajectory<
        double,
        ublasRn<>,
        CompositeCTRn
        > T;

    std::cout << 123 << std::endl;
}

Note. I am using the external library boost::ublas. I believe that it is not unlikely that the problem is related to the dynamic memory allocation mechanism for the ublas objects.

A: Well. I'm thinking you're really pushing the type system. I cannot begin to fathom why you would want this egregious type hierarchy:

That's a lot of damage done in ~60 lines of code. I cannot think of a reasonable situation where Liskov Substitution Principle holds for this hierarchy.

I also note that this kind of emphasis on runtime polymorphism does seem to run counter to the design goals of C++ and uBlas in particular.

Especially this line (declaring the center of the diagram, essentially):
class CompositeCTRn : public CompositeCT<ublasRn<double> >, public CompositeRn<double> {

This effectively declares a class with a single virtual base, which is "aliased" via three bases:
using VBase  = Composite<double, ublasRn<double> >;
using CTBase = CompositeCT<ublasRn<double> >;
using RnBase = CompositeRn<double>;

This means there should be only one _i1 and one _i2 member in the type. That means that on all conforming compilers, the following should compile and run without triggering any asserts or causing memory leaks etc.:
class CompositeCTRn : public CompositeCT<ublasRn<double> >, public CompositeRn<double> {
    using VBase  = Composite<double, ublasRn<double> >;
    using CTBase = CompositeCT<ublasRn<double> >;
    using RnBase = CompositeRn<double>;
public:
    CompositeCTRn() : VBase(), CTBase(), RnBase() {
        VBase::_i1 = 1;
        VBase::_i2.reset(new ublasRn<double>(3));

        CTBase::_i1 = 2;
        CTBase::_i2.reset(new ublasRn<double>(3));

        RnBase::_i1 = 3;
        RnBase::_i2.reset(new ublasRn<double>(3));

        assert(3 == VBase::_i1);
        assert(3 == CTBase::_i1);
        assert(3 == RnBase::_i1);

        assert(VBase::_i2.get() == CTBase::_i2.get());
        assert(VBase::_i2.get() == RnBase::_i2.get());

        RnBase::_i2.reset();
        assert(!(VBase::_i2 || CTBase::_i2 || RnBase::_i2));
    };
};

In fact, that's exactly what happens on gcc 4.8, 4.9, 5.0 and clang++ 3.5.
Live On Coliru
#include <boost/numeric/ublas/vector.hpp>

namespace ublas = boost::numeric::ublas;

template <typename T = double> using ublasRn = ublas::vector<T>;

struct Base {
    virtual ~Base() {}
};

template <typename T1, typename T2> class Composite : public Base {
  protected:
      template <typename, typename, typename> friend class Trajectory; // or make this public
      using Type1 = T1;
      using Type2 = T2;

      Type1 _i1;
      std::unique_ptr<Type2> _i2;

  public:
      Composite() = default;
};

template <typename T2> class CompositeCT : virtual public Composite<double, T2> {
  public:
    using Composite<double, T2>::Composite;
};

template <typename T1> class CompositeRn : virtual public Composite<T1, ublasRn<double> > {
  public:
    using Composite<T1, ublasRn<double> >::Composite;
};

class CompositeCTRn : public CompositeCT<ublasRn<double> >, public CompositeRn<double> {
    using VBase  = Composite<double, ublasRn<double> >;
    using CTBase = CompositeCT<ublasRn<double> >;
    using RnBase = CompositeRn<double>;
  public:
    CompositeCTRn() : VBase(), CTBase(), RnBase() {
        VBase::_i1 = 1;
        VBase::_i2.reset(new ublasRn<double>(3));

        CTBase::_i1 = 2;
        CTBase::_i2.reset(new ublasRn<double>(3));

        RnBase::_i1 = 3;
        RnBase::_i2.reset(new ublasRn<double>(3));

        assert(3 == VBase::_i1);
        assert(3 == CTBase::_i1);
        assert(3 == RnBase::_i1);

        assert(VBase::_i2.get() == CTBase::_i2.get());
        assert(VBase::_i2.get() == RnBase::_i2.get());

        RnBase::_i2.reset();
        assert(!(VBase::_i2 || CTBase::_i2 || RnBase::_i2));
    };
};

template <typename T1, typename T2, class TComposite> class Trajectory : public Base {
    static_assert(std::is_same<T1, typename TComposite::Type1>::value, "mismatched composite");
    static_assert(std::is_same<T2, typename TComposite::Type2>::value, "mismatched composite");
  protected:
    std::vector<std::unique_ptr<TComposite> > m_Trajectory;

  public:
    Trajectory() { checkType(); }
    void checkType() const {
        std::vector<TComposite> CI(1000);
    }
    virtual ~Trajectory() {}
};

#include <iostream>

int main() {
    Trajectory<double, ublasRn<>, CompositeCTRn> T;
    std::cout << 123 << "\n";
}

Under valgrind:
==15664== Memcheck, a memory error detector
==15664== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==15664== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==15664== Command: ./test
==15664==
123
==15664==
==15664== HEAP SUMMARY:
==15664==     in use at exit: 0 bytes in 0 blocks
==15664==   total heap usage: 6,001 allocs, 6,001 frees, 184,000 bytes allocated
==15664==
==15664== All heap blocks were freed -- no leaks are possible
==15664==
==15664== For counts of detected and suppressed errors, rerun with: -v
==15664== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

No problem at all.
Notes

*

*I replaced the type check with a static assert (because, why not?!)
template <typename T1, typename T2, class TComposite> class Trajectory : public Base {
    static_assert(std::is_same<T1, typename TComposite::Type1>::value, "mismatched composite");
    static_assert(std::is_same<T2, typename TComposite::Type2>::value, "mismatched composite");

Summary / TL;DR
I've looked at your code. Other than a nice bouquet of design smells I don't see anything wrong with it, really. If you need more help, you'll have to start being specific about versions, flags, compilers, architecture...


text:
Q: Spring Data Elasticsearch 4 - Override Object Mapper? Previously in version 3 of Spring Data Elasticsearch, the Jackson mapper was used by default, but could be overridden to use the Metamodel object mapper, as documented here:
https://docs.spring.io/spring-data/elasticsearch/docs/3.2.0.RC1/reference/html/#elasticsearch.mapping.meta-model
I understand the Jackson mapper has been removed in version 4 and replaced with the Metamodel object mapper, as documented here:
https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.mapping
But it appears the ability to override the object mapper was removed as well. Is there indeed no way to configure the Elasticsearch global object mapper to use Jackson (or any other mapper) again? It seems like a shame to lose the flexibility that option provided.

A: No. The MappingConverter is not only used and needed for converting an entity to and from JSON, but also for converting and mapping fieldnames, dateformats and other stuff for example when CriteriaQuerys are created  or when search resukts like highlights are processed. There are man places in Spring Data Elasticsearch where the mapping information for an entity is needed and Jackson cannot be used there.
So in versions before 4.0 it was necessary to customize Jackson with jackson-annotations on the entity and the other stuff with different annotations, this has been consolidated.
What functionality do you need that the MappingConverter (implementation of the meta model mapper) does not offer in combination with custom converters?
Edit 05.12.2020:
valid point from the comments: It should be possible to define a FieldNamingStrategy for an entity. I created an issue for that.


text:
Q: How to fix major lag in NSTimers? In a fairly simple application that I am making, I use many NSTimers, one which runs at a rate of .01 seconds that I use to change the position of multiple images.  This causes major lag.  How can I fix this?  Please explain in detail, as I am fairly new to app dev.

A: From the NSTimer Docs (emphasis: mine):

A timer is not a real-time mechanism; it fires only when one of the
  run loop modes to which the timer has been added is running and able
  to check if the timer's firing time has passed. Because of the various
  input sources a typical run loop manages, the effective resolution of
  the time interval for a timer is limited to on the order of 50-100
  milliseconds. If a timer's firing time occurs during a long callout or
  while the run loop is in a mode that is not monitoring the timer, the
  timer does not fire until the next time the run loop checks the timer.
  Therefore, the actual time at which the timer fires potentially can be
  a significant period of time after the scheduled firing time.

If you want to work at the display frequency, see CADisplayLink.
However, you should first understand where you program spends its time now to understand what makes it slow (profiler).


text:
Q: Passing enum in params How can I pass an enum as one of the parameters of the method? I only need in some implementations of the method, and not in others. That's how method declaration looks:
public abstract void SomeMethod(params object[] someParams);

And that's how I would like some of the implementations to look:
public override void SomeMethod(params object[] someParams) {

    SomeEnum someEnum = someParams[0];
    if (someEnum == null)
        return;

}

This code, of course, is invalid, but it shows what I intend to do. Other implementations of the method may use other enums, or use no enums at all.
Update: As many have stated, it's a very strange thing to do, throwin type-safety out of the window. So, I decided to explain why I'm doing this.
I have to pass method calls to a lot of various subclasses of a class where I declare this method through a system that sends them across a network (as well as locally) and executes them at specific time in a special order. Is there a better way to do this?

A: You can pass enum values of a type using the params keyword just as any other object.
public override void SomeMethod(params SomeEnum[] someEnums)
{
     foreach(SomeEnum e in someEnums)
     {

     }
}

In case you gotta pass other enums as well to this method, you could use System.Enum as parameter since all enums derive from it. Slightly stronger typing.
public override void SomeMethod(params Enum[] enums)
{
    //something like
    var @enum = enums[0];
    if (!(@enum is SomeEnum))
        return;

    var someEnum = (SomeEnum)@enum;
}

As to acknowledge your edit, the best way is to specify the objects you are going to pass during method call explicitly as the signature of your method. Only if the number of parameters you will pass have to be variable, you should rely on params keyword. Otherwise, you should stick to explicitly declaring the signature. If your enum SomeEnum is optional, you can declare it at last as an optional parameter. Like this:
public override void SomeMethod(int a, string b, SomeEnum? someEnum = null)
{
    if (someEnum == null)
       //handle the logic here
}

A: public override void SomeMethod(params object[] someParams)
{
    if (!(someParms[0] is SomeEnum))
        return;

    var se = (SomeEnum) someParams[0];
    ...
}

Though quite why you wouldd want to do this over an explicitly typed parameter I cannot imagine.

A: Well it looks like you're really asking for trouble here, basically removing any sort of strong typing from the signature. You'll need to cast.
Secondly, a value of type SomeEnum can never be null, because enums are value types. So you could write:
public override void SomeMethod(params object[] someParams)
{
    if (someParams[0] == null)
    {
        return;
    }
    // This will throw an exception if you've been given the wrong kind
    // of argument. I prefer that to just silently returning, as it would
    // usually indicate a programming error which should be fixed.
    SomeEnum someEnum = (SomeEnum) someParams[0];
    ...
}

However, you'd be better off working out a way of representing the parameters in a more strongly typed way. Unfortunately, we can't really help you do that without more information.

A: I think normally you'd use overloads for different implementations of the method, not overrides, if they require different parameters.  These could still have params at the end:
void M(SomeEnum someEnum, params object[] someParams)
{
   //...

Your code could work with this signature, too, however:
public override void SomeMethod(params object[] someParams) {

    if (someParams.Length == 0 or !(someParams[0] is SomeEnum))
        return;

    SomeEnum someEnum = (SomeEnum)someParams[0];
    //...


text:
Q: google custom search api for android When I am trying to run the below URL:
https://www.googleapis.com/customsearch/v1?q=a&key=AIzaSyAlA7Vv79S_pH8tWjD-SAFUIlVh2ZzHw2o&cx=002019692856142923148:nijox13azs4
the response is:

{"error": {"errors": [{"domain": "usageLimits","reason":
  "ipRefererBlocked",
      "message": "The referrer null does not match does not match the referrer restrictions configured on your API key. Please use the API
  Console to update your key restrictions.","extendedHelp":
  "https://console.developers.google.com/apis/credentials?project=672025619957"}],
  "code": 403,"message": "The referrer null does not match does not
  match the referrer restrictions configured on your API key. Please use
  the API Console to update your key restrictions."}}

I have generated the browser api key.. please tell me where is my mistake?
Thanks in advance


text:
Q: Ubuntu 19.10 Bluetooth on Intel AC 3168NGW Stopped working (WiFi still works) Fresh install of Ubuntu 19.10, I didn't manually install any drivers, Wifi and Bluetooth both worked out of the box (Asrock Deskmini A300 with 3168 dual band M.2 wifi/bluetooth card).
The OS crashed today and then bluetooth hasn't worked since. Wifi still works fine. Bluetooth has seemingly crashed in the past, but a reboot or restarting it via the settings panel worked.
Now the bluetooth settings panel rotates between saying "No bluetooth found" to "bluetooth turned off" every few seconds. Trying to enable it does nothing.
The additional drivers panel in Software & Updates shows the "device is not working", however, it has always said this. This has not changed. Though I am unable to make any selection here as the buttons are greyed out.
Here's some of the syslog that shows when I try to enable bluetooth from the settings panel:
Oct 22 14:05:57 deskmini systemd[1]: Reached target Bluetooth.
Oct 22 14:05:59 deskmini kernel: [  521.124745] usb 1-3.1: USB disconnect, device number 52
Oct 22 14:05:59 deskmini kernel: [  521.146649] Bluetooth: hci0: command 0x0c03 tx timeout
Oct 22 14:06:07 deskmini kernel: [  529.174629] Bluetooth: hci0: sending initial HCI reset command failed (-110)
Oct 22 14:06:07 deskmini systemd[1]: Stopped target Bluetooth

Drivers panel:

The Firmware files are present in /lib/firmware, I didn't manually install these: iwlwifi-3168-21.ucode, iwlwifi-3168-22.ucode, iwlwifi-3168-27.ucode, iwlwifi-3168-29.ucode
Any ideas how I can further debug this?

A: Found the answer in another thread: Bluetooth not working at all after I made some changes to pair with PS3 joystick
Turn off the computer, unplug everything including power, give it a few minutes and then power back up. Bluetooth is back again. (I had tried powering off, and rebooting, but not disconnecting everything)
You can see in the screenshot that it is still acting strange in the Additional Drivers panel, but that Bluetooth devices are successfully connected:

A: Same/similar issue on 19.10 since kernel updated to 5.3.0.24, but the solution doesn't seem to work.
Bluetooth doesn't turn on. In cli tried bluetoothctl but it just keeps responding No default device available. Seems the module is offline. Maybe kernel downgrade would help, but I'm traveling so can't risk my only computer on hand right now.


text:
Q: How to encrypt data before save and decript before use We have an yii1 site with large number of database queries and for some security point of view, we want to store data in encrypted form and want to decrypt before useage.
I am using beforeSave and afterFind methods but the grid is not working.
Below is my code:
public function beforeSave() {
        $this->name = CommonFunctions::encodeString($this->name);
        $this->currency_symbol = CommonFunctions::encodeString($this->currency_symbol);
        $this->is_base_currency = CommonFunctions::encodeString($this->is_base_currency);
        $this->exchange_rate = CommonFunctions::encodeString($this->exchange_rate);
        return parent::beforeSave();
    }
    protected function afterFind() {
        $this->name = CommonFunctions::decodeString($this->name);
        $this->currency_symbol = CommonFunctions::decodeString($this->currency_symbol);
        $this->is_base_currency = CommonFunctions::decodeString($this->is_base_currency);
        $this->exchange_rate = CommonFunctions::decodeString($this->exchange_rate);
        parent::afterFind();
    }


text:
Q: Matrix diagonal elements of a matrix I want to create a matrix where The matrix is diagonal elements of the matrix elements other? without loop in Matlab
A=[1 2;3 4]
B=[1 0 0 0;0 2 0 0;0 0 3 0;0 0 0 4]

A: In Matlab case, just do the following
v = A'(:) % transpose since it makes long column by concat left to right column
B = diag(v)

In Python case, you can use numpy
import numpy as np
A = np.array([[1,2], [3,4]])
B = np.diag(A.ravel())


text:
Q: SSL seems to be not installed properly I have a certificate for a domain example.com. So, every request in my application (MVC 3) is being redirected to the https://example.com. But the problem is, I can see the padlock icon in the Firefox browser

but one second later it disappears and I see that there is no certificate ?

I have no clue what's going on, can somebody enlighten me ? The application is being hosted on Windows Server 2008 R2.

A: The "...which is run by (unknown)" message is just a message telling you that the certificate only verifies the web site name, not the owner. The message is not very clear and has been reported as a bug to Mozilla.
The "Your connection to this site is only partially encrypted" message means that you're fetching at least some HTTP data as a part of your HTTPS page (check your font/image/media links on the page) and the data fetched via HTTP is not secure. A secure page should only link to HTTPS content, or someone listening to the connection may be able to the insecure communication and figure out what is done over the secure link. For example, if your cookies are not set as secure, they'll be sent over clear text too when fetching data from your site.
All in all, the SSL cert seems to be installed ok, but your page needs some updates to only link to secure content.


text:
Q: How do I assign Power BI administrator role to a security group? I can assign a user the role of power bi admin.
I have a security group with 5 users. How do I assign Power BI administrator role to a security group? Can this be done in azure portal or tenant admin portal?

A: There is a preview feature that supports this: https://learn.microsoft.com/en-us/azure/active-directory/roles/groups-concept
Screenshot from AAD


text:
Q: dropdown menu with top triangle I want to create a dropdown menu like this:

http://www.howdyjeff.com/

but I cant horizontally center the top triangle and the dropdown menu (based on the li a) and I'm having some :hover problem, because the dropdown ul fades away.
how can I do that?
JSFiddle:

https://jsfiddle.net/zw5rqzut/

html {
    text-align: center;
}
nav {
    width: 100%;
    height: auto;
    background-color: #000;
}
ul li {
    display: inline-block;
    position: relative;
    margin: 1em
}
ul ul {
    display: none;
    position: absolute;
    background-color: #000;
    top: 50px;
}
ul ul:after {
    position: absolute;
    left: 50%;
    top: -8px;
    width: 0;
    height: 0;
    content: '';
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-bottom: 20px solid #000000;
}
a {
    color: #fff;
    text-decoration: none;
}
li:hover ul {
 display:block;
}

            Dropdown1

Option1

Option2

Option3

            Dropdown2

Option1

Option2

Option3

            Dropdown3

Option1

Option2

Option3

A: For centering the arrow, you can add this:
ul ul:after {
    margin-left: -20px;
}

To fix the dropdown doesn't stay, give enough bottom padding like this:
nav > ul > li > a {
    padding-bottom: 50px;
}

Demo: centering dropdown and arrow:
http://jsfiddle.net/esjrhg5n/
$(document).ready(function() {
    $("nav > ul > li").mouseover(function() {
        var the_width = $(this).find("a").width();
        var child_width = $(this).find("ul").width();
        var width = parseInt((child_width - the_width)/2);
        $(this).find("ul").css('left', -width);
    });
});

Update: Non-JS version below:
https://jsfiddle.net/2Ly1h6uz/

nav {
  background-color: black;
  font-family: sans-serif;
  text-align: center;
}

nav ul,
nav li {
  list-style: none;
  padding: 0;
  margin: 0;
}

nav a {
  text-decoration: none;
  color: white;
}

nav a:hover {
  color: yellow;
}

nav>ul {
  display: flex;
  justify-content: center;
}

nav>ul>li {
  position: relative;
}

nav>ul>li>a {
  display: block;
  padding: 10px 20px;
}

nav>ul>li>ul {
  display: none;
  white-space: nowrap;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  padding-top: 15px;
}

nav>ul>li>ul>li>a {
  display: block;
  padding: 10px 20px;
  background-color: black;
  border-bottom: 1px solid darkgray;
}

nav>ul>li>ul:after {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 5px;
  width: 0;
  height: 0;
  content: '';
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 10px solid black;
}

nav>ul>li:hover>ul {
  display: block;
}

      Dropdown1

Option1

Option2 A Long One

Option3

      Dropdown2

Option1

Option2

Option3

      Dropdown3

Option1

Option2

Option3

A: To center the triangle horizontally, simply use transform as below:
left: 50%;                     //as you did
transform: translateX(-50%);


text:
Q: Issue with Jackcess ExportFilter I found a great library called Jackcess, allows you to convert, parse create, etc with Microsoft Access.
The aim is to convert, which this code does successfully.
There is a Filter functionality upon export, this can be seen on the link to the documentation below. The aim is to use the first 3 columns, exclude the rest of the data.
ExportUtil Documentation
Applying the filter object doesn't work, does anyone know if there's something else that needs to be ahcieved first... * scratching my head here *
Export Filter Documentation
public void db_dump(String mdbFile, String outputDir) {
    File file = new File("/Users/testUser/Downloads/example.mdb");
    if(file != null) {
    File outDir = new File("/Users/testUser/Desktop/output123");
    boolean success = outDir.mkdir();
        if (success) {
            Database db = null;
            try {
                db = DatabaseBuilder.open(file);
                Table t = db.getTable("MappedCHTCP");
                List<Column> cols  = new List<Column>()
                    @Override methods for list ommited .... size(), contains(), etc
                System.out.println(t.getColumns());

//                  cols.add(0,t.getColumn("word"));

                 for (Column c : t.getColumns()) {
                      if((c != null) && (c.getColumnIndex() < 3)) {
                          System.out.println(c.getName());
                          cols.add(c);
                      }
                 }

                SimpleExportFilter ef = new SimpleExportFilter(); //THIS IS THE PROBLEM
                ef.filterColumns(cols);

                File csvFile = new File(outDir+File.separator+"MappedCHTCP.csv");
                ExportUtil.exportFile(db, "MappedCHTCP", csvFile, false, null, '"',ef); //NOT ABLE TO APPLY FILTER

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

A: Based on what I found in the unit test code here, the following sample code seems to work. It exports only the first three (3) columns of the table named [Members]:
package jackcessTest;

import java.io.File;
import java.util.*;
import com.healthmarketscience.jackcess.*;
import com.healthmarketscience.jackcess.util.ExportFilter;
import com.healthmarketscience.jackcess.util.ExportUtil;
import com.healthmarketscience.jackcess.util.SimpleExportFilter;

public class JackcessTest {

    public static void main(String[] args) {
        try (Database db = DatabaseBuilder.open(
                new File("C:/Users/Public/mdbTest.mdb"))) {

            ExportFilter eFilter = new SimpleExportFilter() {
                private List<Column> _cols = new ArrayList<Column>();
                private int _colIdx = 0;
                @Override
                public List<Column> filterColumns(List<Column> columns) {
                    for (Column c : columns) {
                        if (_colIdx++ < 3) _cols.add(c);
                    }
                    return _cols;
                }
            };

            ExportUtil.exportFile(
                    db,
                    "Members",
                    new File("C:/Users/Public/zzzJdump.csv"),
                    true,
                    ",",
                    '"',
                    eFilter);
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}


text:
Q: Not able to trim timestamp format in sql loader I am new to SQL loader and unable to trim the timestamp format while loading data via SQL loader.
my control file looks like this:
LOAD DATA
APPEND
INTO TABLE MyTable
fields terminated by ','
trailing nullcols
(
column1,
column2,
column3,
column4,
DATE EXPRESSION "current_timestamp(1)"
)

The date column loaded in MyTable is in below format:
18-FEB-20 18.10.33.700000000
I want to trim the milliseconds from the output(.700000000). My output should be "18-FEB-20 18.10.33". Is there a way to do it via SQL loader itself?

A: TO_CHAR(current_timestamp(1), 'DD-MON-YY hh:mi:ss') works in a SELECT statement to format current_timestamp(1) like you are requesting. I'm not sure if the same syntax will work in SQL-Loader, but I'd expect something very similar to work for what you need.
SELECT
    TO_CHAR(current_timestamp(1), 'DD-MON-YY hh:mi:ss')
FROM DUAL


text:
Q: How to calculate Normalised Mean Square Error (NMSE) and why to use it? I've been told I need to normalise my MSE for my thesis involving neural networks.
Equations for NMSE seem a bit few and far-between. I have the following and want to corroborate it if possible:

Is the standard deviation term supposed to be calculated from the target values or the predicted values?
Also, what are the main advantages for using MSE over NMSE? Is it just that it makes error comparisons easier, because of the simpler scale?
Many thanks for any help!

A:     def nmser(x,y):
        z=0
        if len(x)==len(y):
            for k in range(len(x)):
                z = z + (((x[k]-y[k])**2)/x[k])
                z = z/(len(x))
        return z


text:
Q: How to find the tomcat automatic shutdown reason by catalina.out recently, tomcat occur several times on automatic shutdown. but not find the reason by catalina.out
Server:linux(1 core cpu, 1G memory)
tomcat: 7.0.65
tomcat server.xml add jvm setting:
JAVA_OPTS="-server -Xms256m -Xmx512m -XX:PermSize=256M -XX:MaxPermSize=512m"
catalina.out
2016-05-17 00:31:55 -173311 [http-bio-8080-exec-5] DEBUG   - ==> Parameters: 3(String)
2016-05-17 00:31:55 -173313 [http-bio-8080-exec-5] DEBUG   - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5503fcfc]
May 17, 2016 2:43:14 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["http-bio-8080"]
May 17, 2016 2:43:14 AM org.apache.coyote.AbstractProtocol pause
INFO: Pausing ProtocolHandler ["ajp-bio-8009"]
May 17, 2016 2:43:14 AM org.apache.catalina.core.StandardService stopInternal
INFO: Stopping service Catalina
2016-05-17 02:43:14 -8036625 [localhost-startStop-2] INFO    - Closing WebApplicationContext for namespace 'springMvc-servlet': startup date [Tue May 17 00:29:22 CST 2016]; parent: Root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.support.XmlWebApplicationContext).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
May 17, 2016 2:43:14 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
SEVERE: The web application [/legoms] registered the JDBC driver [com.alibaba.druid.proxy.DruidDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
May 17, 2016 2:43:14 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
SEVERE: The web application [/legoms] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
May 17, 2016 2:43:14 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [/legoms] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
2016-05-17 02:43:14 -8051975 [localhost-startStop-2] INFO    - Closing WebApplicationContext for namespace 'springMvc-servlet': startup date [Tue May 17 00:29:10 CST 2016]; parent: Root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.support.XmlWebApplicationContext).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
May 17, 2016 2:43:14 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
SEVERE: The web application [] registered the JDBC driver [com.alibaba.druid.proxy.DruidDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
May 17, 2016 2:43:14 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
SEVERE: The web application [] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
May 17, 2016 2:43:14 AM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
SEVERE: The web application [] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak.
May 17, 2016 2:43:14 AM org.apache.catalina.loader.WebappClassLoaderBase checkThreadLocalMapForLeaks
SEVERE: The web application [] created a ThreadLocal with key of type [org.apache.shiro.util.ThreadContext.InheritableThreadLocalMap] (value [org.apache.shiro.util.ThreadContext$InheritableThreadLocalMap@6ae24d54]) and a value of type [java.util.HashMap] (value [{org.apache.shiro.util.ThreadContext_SECURITY_MANAGER_KEY=org.apache.shiro.web.mgt.DefaultWebSecurityManager@2f42fc9e, org.apache.shiro.util.ThreadContext_SUBJECT_KEY=org.apache.shiro.web.subject.support.WebDelegatingSubject@56d7014f}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.
May 17, 2016 2:43:14 AM org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["http-bio-8080"]
May 17, 2016 2:43:14 AM org.apache.coyote.AbstractProtocol stop
INFO: Stopping ProtocolHandler ["ajp-bio-8009"]
May 17, 2016 2:43:14 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["http-bio-8080"]
May 17, 2016 2:43:14 AM org.apache.coyote.AbstractProtocol destroy
INFO: Destroying ProtocolHandler ["ajp-bio-8009"]

A: The reason your Tomcat server could be shutting down is due to an operating system update requiring your JVM to start (possibly a kernel update). I would start by looking in your operating system logs beginning with yum or whatever package manager your system is using to see if there were any updates and what it was doing when your server stopped.
This has happened to me quite a few times.


text:
Q: Android Video View in another Thread & Issue with android 2.1 I want stream video form url in android video view . I use the sample api code and done little modification in that to achieve my need .My code is
public class VideoViewDemo extends Activity {

private static final String TAG = "VideoViewDemo";
private String current;

/**
 * TODO: Set the path variable to a streaming video URL or a local media
 * file path.
 */
private String path = "http://www.boisestatefootball.com/sites/default/files/videos/original/01%20-%20coach%20pete%20bio_4.mp4";
private VideoView mVideoView;

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.videoview);
    mVideoView = (VideoView) findViewById(R.id.surface_view);
    runOnUiThread(new Runnable() {
        public void run() {
            playVideo();
        }
    });
}

private void playVideo() {
    try {
        // final String path = path;
        Log.v(TAG, "path: " + path);
        if (path == null || path.length() == 0) {
            Toast.makeText(VideoViewDemo.this, "File URL/path is empty",
                    Toast.LENGTH_LONG).show();

        } else {
            // If the path has not changed, just start the media player
            if (path.equals(current) && mVideoView != null) {
                mVideoView.start();
                mVideoView.requestFocus();
                return;
            }
            current = path;
            mVideoView.setVideoPath(getDataSource(path));
            mVideoView.start();
            mVideoView.setMediaController(new MediaController(this));
            mVideoView.requestFocus();

        }
    } catch (Exception e) {
        Log.e(TAG, "error: " + e.getMessage(), e);
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
    }
}

private String getDataSource(String path) throws IOException {
    if (!URLUtil.isNetworkUrl(path)) {
        return path;
    } else {
        URL url = new URL(path);
        URLConnection cn = url.openConnection();
        cn.connect();
        InputStream stream = cn.getInputStream();
        if (stream == null)
            throw new RuntimeException("stream is null");
        File temp = File.createTempFile("mediaplayertmp", "dat");
        temp.deleteOnExit();
        String tempPath = temp.getAbsolutePath();
        FileOutputStream out = new FileOutputStream(temp);
        byte buf[] = new byte[128];
        do {
            int numread = stream.read(buf);
            if (numread <= 0)
                break;
            out.write(buf, 0, numread);
        } while (true);
        try {
            stream.close();
        } catch (IOException ex) {
            Log.e(TAG, "error: " + ex.getMessage(), ex);
        }
        return tempPath;
    }
}
}

Here you can see i am using uithread to stream video .Is there any way to handle this by my on thread
What i tried is
new Thered(new Runnable() {
        public void run() {
            playVideo();
        }
    }).start();

But it Fails
And also While running in Android 2.2 The First code runs and it shows error(-38,0) in Android 2.1 what is this error?? I checked This File but cannot find out what error is this??
Can anybody Guide me??

A: You do not need to fetch the entire video, and save it in file system, then run it..The video you have mentioned is having 32Mb size, and it will take so much time to fetch via network. Instead you can give the direct link to videoview, it will progressively fetch/buffer the video and play it. You were trying to fetch the video data in UI thread, that is not acceptable. Here is the corrected code, you can check it.
public class VideoViewDemo extends Activity {

private static final String TAG = "VideoViewDemo";
private String current;

/**
 * TODO: Set the path variable to a streaming video URL or a local media
 * file path.
 */
private String path = "http://www.boisestatefootball.com/sites/default/files/videos/original/01%20-%20coach%20pete%20bio_4.mp4";
private VideoView mVideoView;

private Handler handler;

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    handler = new Handler();
    setContentView(R.layout.videoview);
    mVideoView = (VideoView) findViewById(R.id.surface_view);
/*    runOnUiThread(new Runnable() {
        public void run() {
            playVideo();
        }
    });
*/
    playVideo();
    Log.v(TAG, "activity oncreate finished");
}

private void playVideo() {
    try {
        // final String path = path;
        Log.v(TAG, "path: " + path);
        if (path == null || path.length() == 0) {
            Toast.makeText(VideoViewDemo.this, "File URL/path is empty",
                    Toast.LENGTH_LONG).show();

        } else {
            // If the path has not changed, just start the media player
            if (path.equals(current) && mVideoView != null) {
                mVideoView.start();
                mVideoView.requestFocus();
                return;
            }
            current = path;

            mVideoView.setVideoPath(path);
            mVideoView.start();
            mVideoView.setMediaController(new MediaController(VideoViewDemo.this));
            mVideoView.requestFocus();

        }
    } catch (Exception e) {
        Log.e(TAG, "error: " + e.getMessage(), e);
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
    }
}

}


text:
Q: How do I install a .deb file silently and automatically? OS: Debian 11
My goal is to install a .deb file silently and automatically from a bash script.
The command I am running inside a bash script is
sudo apt install -y ./*.deb

I get this screen

Yes, I can hit "Enter" on my keyboard, I can use the mouse to hit "OK" too.
I don't want to.
What command do I run to auto-select "OK" when prompted so that everything is automatic?

A: The message is shown via debconf, by the config script of the "zfs-dkms" package.
It's technically implemented not as a message but a debconf input dialog which gets a specific parameter, so you can avoid it by manually adding the parameter into debconf's database before installation:
echo zfs-dkms zfs-dkms/note-incompatible-licenses note true | debconf-set-selections

A: After searching the internet, I stumbled upon an answer that works:
sudo DEBIAN_FRONTEND=noninteractive apt-get -y install ./*.deb


text:
Q: Best practices for Unit tests using Entity Framework Edit: I forgot to mention that I'm using a Code First approach
I'm currently developing an application which uses the Entity Framework. The system currently has restaurants (Called Subjects in my code), users and reviews.
I'm brand new to using the Entity Framework, so I was wondering on how I can set up unit tests correctly. I'm assuming I don't have to test any inserting, retrieving and modifying data coming from EF, since this is probably tested already. When I want to set up tests for the code I'm writing, how should I handle objects coming from EF?
I'll give an example of a unit test I have developed. I'm using a repository structure for calls to the database. I'm aware this isn't necessary, but I like the abstraction in case we're switching databases.
My repository looks like this. (The user repository basically follows the same idea)
public class SubjectRepository
{
    private readonly RecommenderContext _context;

    public SubjectRepository()
    {
        _context = new RecommenderContext();
    }

    public Subject FindByGuid(Guid subjectId)
    {
        return _context.Subjects.Where(x => x.Id == subjectId).FirstOrDefault();
    }

    public void AddFollower(User userFollowing, Subject subjectToFollow)
    {
        _context.Subjects.Where(x => x.Id == subjectToFollow.Id).FirstOrDefault().Followers.Add(userFollowing);
        _context.SaveChanges();
    }

    public void CreateSubject(Subject sub)
    {
        _context.Subjects.Add(sub);
        _context.SaveChanges();
    }
}

And this is my test class
[TestClass]
public class SubjectRepositoryTests
{
    SubjectRepository _subjectRepository;
    UserRepository _userRepository;

    [TestInitialize]
    public void init()
    {
        _subjectRepository = new SubjectRepository();
        _userRepository = new UserRepository();
    }

    [TestMethod]
    public void AddFollower()
    {
        Subject restaurant = Subject.CreateRandomSubject(); //These functions return randomized objects used for testing
        User activeUser = User.CreateRandomUser();

        _subjectRepository.CreateSubject(restaurant);
        _userRepository.CreateUser(activeUser);

        _subjectRepository.AddFollower(activeUser, restaurant);

        Assert.AreEqual(activeUser.Id, _subjectRepository.FindByGuid(restaurant.Id).Followers[0].Id);
    }
}

Is this a correct way of setting up an unit test? And if so, how would I go around correctly cleaning up the objects I have inserted?
Any other feedback on how to use unit tests in my scenario better would be greatly appreciated!

A: Assuming you are using codefirst...
I would avoid having the proper RecommenderContext with direct database calls in it used in the tests. Replace it with an interface inside your repositories, and create a fake implementation that can be injected into your repository for testing. Then you don't have to worry about leaving residue or connecting to the db in tests.
You can use one of the FakeDbSet classes to implement the test context. Effectively this would test your repository logic whilst ignoring the built in EF behaviour, and leave your test nicely isolated.

A: From a purist point of view you are not unit testing in the example code you provide since the tests are depending on the underlying database to be in a particular state. In order to isolate you need to fake or mock your data by using your own test implementations of your repositories and datacontext. You didn't specify the version of EF you're using, but from EF 6 onwards this has been made easier by having virtual DbSet properties on the DbContext which can be overridden by a mock implementation. MSDN has an article with code samples that explains this in conjunction with Moq as mocking framework. There is also a link in that article for a pre-EF6 solution.
Having said that, very often I find it too much trouble to have this clear separation in unit tests. I take the approach you seem to have taken as well by generating random entities and inserting those in a test database. Another reason for not using in memory-test doubles is that you are using Linq-to-objects instead of Linq-to-SQL which have subtle differences especially when it comes to loading related data.
To clean up your test data you can use your setup and teardown methods of the test framework you're using.


text:
Q: get element by id in innerHTML I have a web app, frontend using normal HTML&JavaScript and backend using Django.
I the frontend part, I have a table, which is supposed to pass the first column(title in my case) to backend upon select a row.
Now I have finished the select part but all the row of the table are passed to backend in innerHTML.
How could I get the first column(id=book_title) in the innerHTML?

                    Title
                     Edition

                {% for book in page_obj %}

                    {{ book.title }}
                    {{ book.edition }}

                {% endfor %}


text:
Q: comparing value from database to a string getting error java.sql.SQLException : No values specified for parameter 1 I want to create a login page that only admin can log in.
My database :
- tb_users
user_id (PK)
password
-tb_userauth
user_id (FK)
objects_id (contain roles of the user such as admin and customer)
this is my program:
private void cmd_loginActionPerformed(java.awt.event.ActionEvent evt) {
    try{
        String sql = "select * from tb_users where user_id=? and password=?";
        PST=conn.prepareStatement(sql);
        PST.setString(1,txt_userid.getText());
        PST.setString(2, txt_pass.getText());
        RS=PST.executeQuery();
        RS.close();

        String sql2 = "select * from tb_userauth where objects_id=?";
        PST=conn.prepareStatement(sql2);
        RS=PST.executeQuery();
        String objek = "admin";
        String objek_id = RS.getString("objects_id");

        if(RS.next()){

             if (objek.equals(objek_id)){

            JOptionPane.showMessageDialog(null,"user id and password correct");
             submenu1 sm1 = new submenu1();
             sm1.setVisible(true);
             sm1.pack();
             sm1.setLocationRelativeTo(null);
             sm1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             this.dispose();
        }else{
            JOptionPane.showMessageDialog(null,"check your password and user id ");
        } }

    }catch (Exception e){
        JOptionPane.showMessageDialog(null,e);
    }

}

and I got an error like this:
java.sql.SQLException: No values specified for parameter 1
this is make me confused because i already use String objek_id = RS.getString("objects_id");
is there something wrong with my ResultSet?

A: You have missed the parameter of the second prepared statement. I guess you did some mistake in query so I change the query  and commented in the changes. I didn't run and test so some issues could be there. You can have idea on this.
private void cmd_loginActionPerformed(java.awt.event.ActionEvent evt) {
  try{
    String sql = "select * from tb_users where user_id=? and password=?";
    PST=conn.prepareStatement(sql);
    PST.setString(1,txt_userid.getText());
    PST.setString(2, txt_pass.getText());
    RS=PST.executeQuery();
    String user_id = RS.getString("user_id"); //I don't know the type of use_id so I guess it as string

    RS.close();

    String sql2 = "select * from tb_userauth where user_id=?"; //I change object_id to user_id

    PST=conn.prepareStatement(sql2);
    PST.setString(1,user_id);//this might not be string
    RS=PST.executeQuery();
    String objek = "admin";
    String objek_id = RS.getString("objects_id");

    if(RS.next()){

         if (objek.equals(objek_id)){

        JOptionPane.showMessageDialog(null,"user id and password correct");
         submenu1 sm1 = new submenu1();
         sm1.setVisible(true);
         sm1.pack();
         sm1.setLocationRelativeTo(null);
         sm1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         this.dispose();
    }else{
        JOptionPane.showMessageDialog(null,"check your password and user id ");
    }
  }

  }catch (Exception e){
    JOptionPane.showMessageDialog(null,e);
  }

}


text:
Q: What attack can generate the most Sepith Fragments with Sepith Up? I've noticed in The Legend of Heroes: Trails in the Sky that when i have the Sepith Up Turn Bonus some attacks like Estelle's Pummel S-Break will cause more Sepith Fragments to fall in an attack despite only dealing damage once as opposed to if she just did a regular attack.
I figured this is because Estelle's Pummel has more "hits" to the attack compared to Joshua's Sever. so i am wondering which attack can generate the most Sepith Fragments with Sepith UP?


text:
Q: Why reinterpret_cast is used in the implementation d_fun() while defining Q_DECLARE_PRIVATE macro Qt classes have a Q_DECLARE_PRIVATE macro in the public class. The macro reads:
#define Q_DECLARE_PRIVATE(Class)\
    inline Class##Private* d_func() {\
        return reinterpret_cast<Class##Private*>(qGetPtrHelper(d_ptr));\
    }\
    inline const Class##Private d_func() const {\
        return reinterpret_cast<const Class##Private *>(qGetPtrHelper(d_ptr));\
    }\
    friend class Class##Private;

Here, as per my understanding Class##Private will be parent of class of d_ptr then why reinterpret_cast is used and not dynamic_cast?

A: The reasons are:

*

*A dynamic_cast is not supported in Qt source code, as Qt can be built with RTTI turned off.
The dynamic_cast< string appears in about a dozen locations in non-tests, non-3rdparty Qt 5.7.0 sources, and most of them are essentially bugs/omissions.

*The macro is used in headers where Class##Private is forward-defined. A static_cast wouldn't work as the compiler doesn't know that Class##Private is derived from the pointed-to type of d_ptr.

*If Class##Private wasn't forward-defined, then the correct cast to use would be static_cast. A dynamic_cast would be a premature pessimization, since the macro is used in a place where d_ptr's pointed-to type is known at compile time, albeit not in the header.
For more details about Q_DECLARE_PRIVATE, see also How to use the Qt's PIMPL idiom?.

A: Because dynamic_cast requires the class to have at least one virtual method (it needs to be polymorphic). Just class inheritance isn't enough for dynamic_cast to succeed.


text:
Q: HomeBridge update AccessoryInformation I've been updating a simple HomeBridge Plugin, and as I can see the data for the HomeKit Accessory Information in the the API response from the connected advice, I'd like to populate that data into HomeKit.
The problem is AccessoryInformation only seems to accept data when I first create the service. Once getServices() has been called by HomeBridge, further calls to updateCharacteristic() on the AccessoryInformation service are ignored. The obvious problem here is, as the data is returned async, I don't yet have it at the point where HomeBridge calls getServices().
How do I force the AccessoryInformation to update once I have the data available? Or alternatively how do I delay HomeBridge calling getServices() until after the data has loaded?
This is my code.
  setDeviceInfo(responseData) {
    // Property names match HK API, values device API
    const deviceInfo = {
      Model: 'MODEL',
      Name: 'UPSNAME',
      SerialNumber: 'SERIALNO',
      SoftwareRevision: 'VERSION',
      FirmwareRevision: 'FIRMWARE',
    }

    Object.entries(deviceInfo).forEach(([key, value]) => {
      const info = responseData[value];
      this.log.info(`${key}:`, info);
      this.informationService.updateCharacteristic(Characteristic[key], info);
    })

The service is created as follows:
 this.informationService = new Service.AccessoryInformation();
    this.informationService
      .setCharacteristic(Characteristic.Manufacturer, config.manufacturer || DEFAULT_MANIFACTURER)

And passed to HomeBridge here
  getServices() {claims to have
    const services = [this.informationService, this.contactSensor, this.batteryService];

    if (this.temperatureService) {
      services.push(this.temperatureService);
    }

    return services;
  }

The whole file is on GitHub
https://github.com/cr3ative/homebridge-apcaccess/blob/ce5b53e44f7ba66c235495c9e14d66ed5cd8fa6d/index.js


text:
Q: Remove text from lines matching string using batch I need to remove the text from the lines that contain a specific string using batch processors: SED, AWK, Windows batch, Unix shell or something similar.
If the string is "green" then the following input
red
green 1
blue
green 2
yellow

will produce the output
red
<EMPTY LINE>
blue
<EMPTY LINE>
yellow

I also need to do the same thing for lines not matching the string, producing the output
<EMPTY LINE>
green 1
<EMPTY LINE>
green 2
<EMPTY LINE>

I need to remove text from lines (empty the content of lines), not to delete them.

A: Using sed to empty lines containing green:
sed '/green/s/.*//' input

And using sed to empty other lines:
sed '/green/!s/.*//' input

A: Windows Command Line/Batch
Use find or findstr.
Output non matching lines
find /V "green" file.txt

Output matching lines
find "green" file.txt

These commands will output the content to the console. Redirect the output to destination files as needed. Example:
find /V "green" file.txt > nonmatchingoutput.txt

Type find /? or findstr /? for help and all the options.

Update for updated question.
This will do what you ask using only Batch
:: Hide Commands
@echo off

:: Erase Existing Files
>match.txt ( <nul set /p "=" )
>nomatch.txt ( <nul set /p "=" )

:: Loop through Source and Generate Output
for /f "tokens=1,* delims=]" %%K in ('type temp.txt ^| find /V /N ""') do (
    for /f "delims=" %%X in ('echo(%%L ^| find /V "green"') do (
        echo(%%X>>nomatch.txt
        echo.>>match.txt
    )
    for /f "delims=" %%X in ('echo(%%L ^| find "green"') do (
        echo(%%X>>match.txt
        echo.>>nomatch.txt
    )
)

A: Using perl:
# Empty when finding green
perl -pe 's,.*,, if /green/' inputfile
# Empty when not finding green
perl -pe 's,.*,, unless /green/' inputfile

These commands will output the content to stdout, so redirect the output to the destination files.

A: Sed solutions are listed below:
Input.txt
red
green 1
blue
green 2
yellow

Try This
Code 1 :
$> grep -v green Input.txt  | sed G

or
$> sed '!s/^green//g' Input.txt

red

blue

yellow

Code 2 :
$> grep green Input.txt  | sed G

or
$> sed -n '/green/p' Input.txt

green 1

green 2


text:
Q: continuous music on website I'm against it as I'm sure ALL of you are, but my client wants background music on their website.
I'm very new to this, so was wondering how should I do that? I know I should use iframes, but what's the actual way of using them? eg:
do I just create the home page with 2 frames (one for the music, one for the rest of the website), and then every time the user clicks on a link I can load the usual destination page - or should I update all pages in some way to make sure they are 'frames enabled'?
Also, I do I style the frame to make sure it's hidden?
thanks,
Patrick
ps
please don't reopen the discussion about why background music is not good - I do know that and personally hate it. But the client is adamant and paying for it so... ;)

A: I guess first you'll have to identify how you want to play the music: flash, midi, whatever...
Using iframes, you may have size issues. Normal frames may work better. Of course style it so it's hidden.
However, the big problem is, when the user navigates away from the website with links on the website, the music will continue to play.
Nasty...
So another way you could do it is open a cool music player interface for the visitor in a new window. The problem with this is that most browsers have pop-up blockers on by default.
Think about this seriously before you do it - there are side affects as you can see.

A: In any browser there is a native audio player:
moz,webkit: <audio src=""></audio>
msie: <bgsound></bgsound>
and to go from page to page without change use web.2 ajax instead of any ugly evil frames.
A nice demo of this setup is at http://sitegen.com.au/


text:
Q: Issue with setup of Zend framework on localhost I have just started to learn Zend and referring to
http://framework.zend.com/manual/2.0/en/user-guide/skeleton-application.html
to create my first application.
I followed all the steps for creating the Virtual host but have been unsuccessful.
My Code:
<VirtualHost 127.0.0.1:80>
   ServerName zendapp.localhost
   DocumentRoot C:\Program Files\Zend\Apache2\htdocs\zendapp\public
   SetEnv APPLICATION_ENV "development"
   <Directory C:\Program Files\Zend\Apache2\htdocs\zendapp\public>
      DirectoryIndex index.php
      AllowOverride All
      Order allow,deny
      Allow from all
   </Directory>
 </VirtualHost>

After adding this code in C:\Program Files\Zend\Apache2\conf\extra\httpd-vhosts.conf, I restarted the Server and typed "zendapp.localhost"
I get a message saying "could not find zendapp.localhost"
Can anyone help I have been struggling for some time.
As I said I am extremely new to Zend.


text:
Q: how to copy & gzip files individually over ssh I'd like to transfer a directory with uncompressed files over using ssh, gzip'ing them individually along the way. Can anyone recommend a simple oneliner to achieve this?
eg.
fileA.ext -> ssh/pipe -> fileA.ext.gz
I've been piping tar over ssh with compression, but then the files are uncompressed at the end of the pipe. In this case, I'd like them to stay compressed.
Compressing beforehand would be possible, but would require space locally, or require a connection per file(?)
There are 6000+ files, and a I'd prefer a solution where all the files could be transferred using a single connection (although I do use keys for authentication!)

A: I suppose you rather want to gzip them first, then send them across.
cat dafile | gzip -c | ssh remote "cat > dafile"

Repeat with relevant loop construct. E.g.
find -type f | while read fname ; do cat $fname | gzip -c | ssh remote "cat > $fname" ; done

... or something to that effect. Need to set up pkey access, or this will be one massive password-speedtyping excercise.
EDIT:
On the subject of a single connection, see man ssh_config ControlMaster. This will mean you save the overhead of negotiating 5999 of those 6000 SSH sessions.
EDIT2:
Haha! I win!
tar zcf - /dir/of/files | ssh remote "tar zxf - --to-command=mygzip.sh"

mygzip.sh, present on the remote machine, looks like this:
#!/bin/sh
mkdir -p "$(dirname $TAR_FILENAME)"
gzip -c > "${TAR_FILENAME}.gz"

A: GNU Parallel can do this easily:
find . -type f | parallel "gzip -c {} | ssh server \"cat>{}.gz\""

which however will also find and send files in directories below the starting directory.
or alternately if you want to send just all the regular files in a single directory:
parallel "gzip -c {} | ssh server \"cat>{}.gz\"" ::: *

A: Everyone's got their own tricks to coping files without SCP.
Here mine (does not use SSH), http://linuxtipsandtricks.com/file-manipulation/transferring-files-with-netcat-nc/
Secondly if you insist on using SSH, you may want to add '-c arcfour' to your SSH.
HTH

A: You should check out this page.
It compares the execution time for this type of file transfer using scp, tar+ssh, and tar+nc with and without ssh- or gzip-compression.
Besides providing several options for completing your task, the results are interesting.


text:
Q: How to delete all the characters after one character in the String? I have a String which contains a date, for example "01-01-2012", then an space and then the time "01:01:01". The complete string is: "01-01-2012 01:01:01"
I would like to extract only the date from this string so at the end I would have "01-01-2012" but don't know how to do this.

A: Try this:
String date = s.substring(0, s.indexOf(" "));

Or even (because the length is fixed):
String date = s.substring(0, 10);

Or use StringUtils.substringBefore():
String date = StringUtils.substringBefore(s, " ");

A: Four options (last two added to make this one answer include the options given by others):

*

*Parse the whole thing as a date/time and then just take the date part (Joda Time or SimpleDateFormat)

*Find the first space using indexOf and get the leading substring using substring:
int spaceIndex = text.indexOf(" ");
if (spaceIndex != -1)
{
    text = text.substring(0, spaceIndex);
}

*Trust that it's valid in the specified format, and that the first space will always be at index 10:
text = text.substring(0, 10);

*Split the string by spaces and then take the first result (seems needlessly inefficient to me, but it'll work...)
text = text.split(" ")[0];

You should consider what you want to happen if there isn't a space, too. Does that mean the data was invalid to start with? Should you just continue with the whole string? It will depend on your situation.
Personally I would probably go with the first option - do you really want to parse "01-01-2012 wibble-wobble bad data" as if it were a valid date/time?

A: Lots of ways to do this, a very simple method is to split the String at the space and use the first part (which will be the date):
String dateTime = "01-01-2012 01:01:01";
String date = dateTime.split(" ")[0];

A: String input = "01-01-2012 01:01:01";
String date = d.split(" ")[0];

A: You can use String.split() and take only the relevant String in your resultng String[] [in your example, it will be myString.split(" ")[0]

A: In that case where only one space is in the string, you can use String.split(" "). But this is a bad practice. You should parse the date with a DateFormat
.

A: You can use substring to extract the date only:
 String thedatetime = "01-01-2012 01:01:01";
 String thedateonly = thedate.substring(0, 10);

You should really read through the javadoc for String so you are aware of the available functions.

A: If you know in advance this is the format of the string, I'd do this:
public String getDateOnly(String fullDate){
    String[] spl = fullDate.split(" ");
    return spl[0];
}

A: You can do it either using string manipulation API:
String datetime =  "01-01-2012 01:01:01";
int spacePos = datetime.indexOf(" ");
if (spacePos > 0) {
   String date = datetime.substring(0, spacePos - 1);
}

or using regular expression:
Pattern p = Pattern.compile("(\\d{2}-\\d{2}-\\d{4})");
String datetime =  "01-01-2012 01:01:01";
Matcher m = p.matcher(datetime);
if(m.find()) {
   String date = m.group(1);
}

or using SimpleDateFormat
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = fmt.parse(datetime);
Calendar c = Calendar.getInstance();
c.setTime(date);
String date = c.getDayOfMonth() + "-" + c.getMonth() + "-" + c.getYear();

A: Use String.substring(int, int). If you are interested in the value of the date and time, then use SimpleDateFormatter to parse your string.

A: myString.substring(0,10);
If your string is always in that format (2 digits, minus, 2 digits, minus, 4 digits, space etc...) then you can use substring(int beginIndex, int endIndex) method of string to get what you want.
Note that second parameter is the index of character after returning substring.

A: If you want to explode the complete date from the string use this method.
/**
 * @param dateTime format string
 * @param type type of return value : "date" or "time"
 * @return String value
 */

private String getFullDate(String dateTime, String type) {
    String[] array = dateTime.split(" ");
    if (type == "time") {
        System.out.println("getDate: TIME: " + array[1]);
        return array[1];

    } else if (type == "date") {
        System.out.println("getDate: DATE: " + array[0]);
        return array[0];
    } else {
        System.out.println("NULL.");
        return null;
    }
}

Otherwise if you want only the date for explample 01-01-2012
use this:
/**
 * @param datetime format string
 * @return
 */
private String getOnlyDate(String datetime) {
    String array[] = datetime.split("-");
    System.out.println("getDate: DATE: " + array[0]);

    return array[0];

}

I hope my answer will help you.


text:
Q: Interesting recurrence relation in the euclidean algorithm...! I do know how the Euclidean algorithm works $(I=0,1,\cdots)$:
$$r_{I-1}=p_{I+1}r_I+r_{I+1}\quad(0\leq r_{I+1}<r_I)$$
here, if we let $r_{J-1}=0$, we have $r_{J-2}=gcd(r_{-1},r_0)$ according to the Euclidean algorithm.
Under this circumstance, I have found that the recurrence relation for $\alpha_I$,
$$\alpha_{I+1}=\alpha_{I-1}+p_{I+1}\alpha_I\quad(\alpha_{-1}=0,\alpha_0=1),$$
yields the following non-trivial result in every example that I have tried (recall how $J$ is defined above):
$$\alpha_{J-1}=\frac{r_{-1}}{r_{J-2}}=\frac{r_{-1}}{gcd(r_{-1},r_0)}.$$
For now I am quite sure it is true. On top of that, in order to prove the above statement, I figured out it suffices to show that
$$\alpha_I=\left(p_1+\frac{1}{p_2+\frac{1}{\cdots}}\right)\left(p_2+\frac{1}{p_3+\frac{1}{\cdots}}\right)\cdots\left(p_{I-2}+\frac{1}{p_{I-1}+\frac{1}{p_I}}\right)\left(p_{I-1}+\frac{1}{p_I}\right)p_I$$
since this implies
$$\alpha_{J-1}=\frac{r_{-1}}{r_0}\frac{r_0}{r_1}\cdots\frac{r_{J-4}}{r_{J-3}}\frac{r_{J-3}}{r_{J-2}}=\frac{r_{-1}}{r_{J-2}}.$$
And I am quite sure that this claim is true, since the first 5~6 terms perfectly agree. But I couldn't prove it yet... I thought mathematical induction could be useful at first but it turned out that such a method is also not that helpful.
If there is anyone who has seen such a recurrence relation in the context of Euclidean algorithm or has proven similar statement before, please give me some ideas...!


text:
Q: How can I call slideDown() on an new element that renders? I have an unordered list and the li elements inside of it are rendered based on the number of items in an array in my backend.
As new items are added to an array, a corresponding li element is rendered and pops up in my list. Is it possible to give each new li element a slideDown() animation?

A: Yes, but you need to use .on() or .live() depending on which version of JQuery you're using.
http://api.jquery.com/on/
http://api.jquery.com/live/
Ok so try this wrap this in a function
function doSlideDown(){
    $('ul > li > input[type="checkbox"]').on("click", function() {

    var parent = $(this).parent("li");
    if($(this).is(":checked") === true) {
    // move to the top
    $(parent).slideUp(300, function() {
      $(parent).prependTo($(parent).parent());
      $(parent).slideDown(300);
    });
    } else {
      $(parent).slideUp(300, function() {
        $(parent).appendTo($(parent).parent());
        $(parent).slideDown(300);
      });
    }
});
}

then add this outside of your document ready function
$(document).ajaxComplete(function() {
    doSlideDown();
});

That will update the DOM every time your run some ajax and append a new item.


text:
Q: Click not always triggered on buttons close to the right side of a web page on iOS We have a design with buttons on the right side of our webpage. (close button in top-right corner of a fullscreen popup, FAB in bottom-right)
On touch devices, it feels like the buttons on the right side don't always work,
even if we use a touchscreen pen instead of a finger to be sure we click on it.
(The buttons are large enough: 48 CSS pixels)
After some investigation it looks like a small region on the right side of the page don't fire click events. (like the location were the scrollbar can appear on the page)
I only see the problem on iOS, not on Android
CodePen Sample: http://codepen.io/jovdb/full/MybojG (make sure to test it on iOS device)
I tried different ways to right align:

  A

*

*float: right;

*text-align: right;

*position: absolute; right: 0;

*flexbox

EDITED: depends on orientation:

*

*iPad 2: iOS: 7.0.4; Safari 7, WebKit v537.51.1

*

*2 orientations work: (home button on bottom and at the right side)

*iPhone 6: iOS: 9.2.1; Safari 9.0, WebKit v601.1.46

*

*all orientations don't work

*iPhone 6: iOS: 9.2.1; Chrome 48, WebKit v601.1

*

*all orientations don't work

*iPhone 4: iOS: 7.1.2; Safari 7, Webkit v537.51.2

*

*only OK when home button is at the right

I don't think it is a physical limitation by the device because buttons close to the left side of the screen work in all orientations.
Does anybody else has this problem?
Is there a workaround for this problem?


text:
Q: Safari NPAPI plugins and retina support I'm facing issues with supporting retina screens with my Safari NPAPI plugin.
I'm using a CoreGraphics based plugin and for some reason the backingScaleFactor returned by the windows I'm using is 1 instead of 2 on a retina screen.
I tried to look for some config parameters with no luck.
The only way I could make it to work, is by creating a subclass of NSWindow and overriding backingScaleFactor to return 2. However, I couldn't find a way to detect retina screens from the plugin itself.
Any thoughts?

A: Unfortunately, there probably isn't a way.  You can't get the NSWindow you're using, so there is no way to be sure which monitor you are drawing on.  If Safari doesn't give you what you need, there probably isn't an option.

A:
However, I couldn't find a way to detect retina screens from the plugin itself.

You can query this information, and get updates when it changes, using NPNVcontentsScaleFactor.


text:
Q: Bazel genrule where outputs depend on the input This answer to Looking for examples of Bazel genrules that generate data files states that "A genrule needs to know all its input files and output files".
Is it possible to write a genrule whose outputs depend on the input file? For example
genrule(
    name = "creator",
    cmd = "xargs -a $< touch",
    srcs = [ "meow.txt" ],
)

This would create a file for each word in meow.txt, e.g.
Chico
Groucho
Harpo

would create three files.
The list of output files depends entirely on the content of meow.txt and is not known in the BUILD file.

A: That is beyond the capabilities of genrule. However, it is possible write a custom rule that outputs a directory, into which arbitrary files can be written when the action executes.


text:
Q: Bold font style on Telerik Report returns to regular font style when exported as PDF I created a report using Telerik and something went wrong when I tried exporting the generated report as PDF. Some texts on my report are set to font style Bold, they're doing fine on my report viewer (which can be viewed on a browser) but when I tried exporting and downloading my report into a PDF file, the texts that I set to Bold font style became a regular font style. Is there something wrong on my report? Or is it on the PDF or the browser that I am using?
Additional info:
Reporting Tool: Telerik Q3 2014 V. 14.3.1118.0
Browser: Google Chrome V. 40.0.2214.94
PDF Reader: Adobe Reader XI V. 11.0.10
Programming Language: VB


text:
Q: request.url is giving me example.com/login instead of example.com/feed Rails 4.2.2
If I click on the link:
<%= link_to "Feed", feed_path, data: {turbolinks: false } %>

or paste the url
www.example.com/feed

A before_action in my UsersController redirects to the login_url
Application Controlller
def logged_in_user
  unless logged_in?
    store_location
    flash[:danger] = "Please log in."
    redirect_to login_url
  end
end

module SessionsHelper
def store_location
  session[:forwarding_url] = request.url if request.get?
end

def redirect_or
  redirect_to(session[:forwarding_url] || root_url)
  session.delete(:forwarding_url)
end

After successfully logging in, the redirect_or method is redirecting me back to the login_url.
request.url is being saved as www.example.com/login

A: You didn't add store_location to the login_url after this comment did you?
If you did you are overwriting store_location with the login_url after the redirect_to login_url... which you don't want to do.
If that is not the issue I would add puts in store_location before and after session[:forwarding_url] because I don't think it's getting saved properly.
Nice work debugging this one


text:
Q: What is the URL for interacting with the Google API Interactive Console to test out queries and get JSON results? I am trying to find something from Google Cloud that is similar to the Interactive Spotify API Web Console.  Does anyone have any ideas that requires a sign into the Google account associated with the Google Cloud?  Thanks!

A: This is available through the API reference pages: https://cloud.google.com/sql/docs/apis
On every method page, there's a form you can use on the right to test it out from the browser using your Google account.
For example, take a look at this page to list your Cloud SQL instances: https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/instances/list


text:
Q: c# winforms: Getting the screenshot image that has to be behind a control I have c# windows form which have several controls on it, part of the controls are located one on another. I want a function that will take for input a control from the form and will return the image that has to be behind the control. for ex: if the form has backgroundimage and contains a button on it - if I'll run this function I'll got the part of backgroundimage that located behind the button. any Idea - and code?
H-E-L-P!!!

A: That's my initial guess, but have to test it.

*

*Put button invisible

*capture current screen

*Crop screen captured to the clientRectangle of the button

*Restablish button.
public static Image GetBackImage(Control c) {
    c.Visible = false;
    var bmp = GetScreen();
    var img = CropImage(bmp, c.ClientRectangle);
    c.Visible = true;
}

public static Bitmap GetScreen() {
    int width = SystemInformation.PrimaryMonitorSize.Width;
    int height = SystemInformation.PrimaryMonitorSize.Height;

    Rectangle screenRegion = Screen.AllScreens[0].Bounds;
    var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
    Graphics graphics = Graphics.FromImage(bitmap);
    graphics.CopyFromScreen(screenRegion.Left, screenRegion.Top, 0, 0, screenRegion.Size);
    return bitmap;
}
public static void CropImage(Image imagenOriginal, Rectangle areaCortar) {
    Graphics g = null;
    try {
        //create the destination (cropped) bitmap
        var bmpCropped = new Bitmap(areaCortar.Width, areaCortar.Height);
        //create the graphics object to draw with
        g = Graphics.FromImage(bmpCropped);

        var rectDestination = new Rectangle(0, 0, bmpCropped.Width, bmpCropped.Height);

        //draw the areaCortar of the original image to the rectDestination of bmpCropped
        g.DrawImage(imagenOriginal, rectDestination, areaCortar, GraphicsUnit.Pixel);
        //release system resources
    } finally {
        if (g != null) {
            g.Dispose();
        }
    }
}

A: This is pretty easy to do.  Each control on the form has a Size and a Location property, which you can use to instantiate a new Rectangle, like so:
Rectangle rect = new Rectangle(button1.Location, button1.Size);

To get a Bitmap that contains the portion of the background image located behind the control, you first create a Bitmap of the proper dimensions:
Bitmap bmp = new Bitmap(rect.Width, rect.Height);

You then create a Graphics object for the new Bitmap, and use that object's DrawImage method to copy a portion of the background image:
using (Graphics g = Graphics.FromImage(bmp))
{
    g.DrawImage(...); // sorry, I don't recall which of the 30 overloads
        // you need here, but it will be one that uses form1.Image as
        // the source, and rect for the coordinates of the source
}

This will leave you with the new Bitmap (bmp) containing the portion of the background image underneath that control.
Sorry I can't be more specific in the code - I'm at a public terminal.  But the intellisense info will tell you what you need to pass in for the DrawImage method.


text:
Q: How to get the end of a C++ string stream? I'm adding functions to my (simple) log class to make it usable like a stream.
Currently, after some modifications, I got this (in my cpp):
// blah blah blah...
// note: here String is a defined as: typedef std::string String;

void Log::logMessage( const String& message )
    {
        logText(); // to be sure we flush the current text if any (when "composing" a message)
        addText( message );
        logText(); // really log the message and make the current text empty
    }

// blah blah blah...

    Log& operator<<( Log& log, const std::stringstream& message )
    {
        log.logMessage( message.str() );
        return log;
    }

    Log& operator<<( Log& log, const String& message )
    {
        log.addText( message );
        return log;
    }

Now in my "client" app I'm using this code to check the result (m_log is a valid pointer as you have already guessed):
gcore::Log& log = *m_log;
log << getName() << " : application created.";
log << "This is a test for " << getName();

Now the problem I got is that logText() (and logMessage) is never called because this test code will only call the << operator with String.
What I need is a way to call logText() when the given steam of string is finished :
log << getName() << " : application created.";

would be equivalent to
log.addText( getName() );
log.addText( " : application create." );
log.logText();

I'm not sure how to do this or even if it's possible. My first guess is that it would be possible to use std::endl at the end of the stream like this :
log << getName() << " : application created." << std::endl;

Or something equivalent, but if it's possible to do it without adding objects to the stream, that would be nice.
Any idea?

A: You can create a temp object and use his destructor to catch the end of the statement:
following code should give you the basic idea
class Log
{
public:
  class Sublog
  {
  public:
    Sublog(const std::string& message)
    {
      std::cout << message;
    }

    void addText(const std::string& message)
    {
      std::cout << message;
    }

    ~Sublog()
    {
      std::cout << std::endl;
    }

    Sublog& operator<<(const std::string& message )
    {
      this->addText(message);
      return *this;
    }
  };

};

Log::Sublog operator<<( Log& log, const std::string& message )
{
  return Log::Sublog(message);
}

which would be used like this
int main()
{
    Log log;
    log << "Foo" << "bar";
    log << "baz" << "plop";
}

after each semicolon, the destructor of Sublog is called

Klaim: the (working and effective) implementation of this solution in my case :
in the Log header :
    /** To allow streaming semantic on logs (used in << operator) .
*/
class LogStreamer
{
public:

    LogStreamer( Log& log, const String& text )
        : m_log( log )
    {
        m_log.addText( text );
    }

    ~LogStreamer()
    {
        m_log.logText();
    }

    LogStreamer& operator<<( const String& text )
    {
        m_log.addText( text );
        return *this;
    }

private:

    Log& m_log;

};

GCORE_API LogStreamer operator<<( Log& log, const String& message );

and in the cpp file:
LogStreamer operator<<( Log& log, const String& message )
{
    return LogStreamer( log, message );
}


text:
Q: Regexp - поиск содержимого HTML тегов Здравствуйте!
Допустим, у нас есть HTML код:

<title>Hashcode</title>

Hello!

...

Нужно составить такой шаблон поиска, чтобы нашлось содержимое "

Hello!

". Т.е. то, что находится между тегами td.
Т.е., прощу говоря, суть в том, чтобы находилось содержимое тега.
A: По поводу регулярок для HTML - можете просмотреть этот пост. А если разумно подходить к решению вопроса, то использовать соответствующие DOM-парсеры, например, PHP Simple HTML DOM Parser или phpQuery.

A: Воспользуйтесь html парсером. Напрмер, phpQuery
A: "\\
([\\w\\W\\s]*)\<\/p\>\<\/td\>"

как-то так это выглядело бы на java