text:
Q: How to calculate the outcome of difference between two fields from hibernate and show it on a jsp? I am making a simple CRUD app, using spring mvc, hibernate and mySQL.
I have a single table in mySQL:
CREATE TABLE `product` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `product_name` VARCHAR(45) DEFAULT NULL,
    `quantity_needed` INT DEFAULT NULL,
    `status` INT DEFAULT NULL,
     PRIMARY KEY (`id`)
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

I have the basics fixes - listing all of the elements on a JSP, adding a new element, updating and deleting.
I want to also show a separate list with just the products, where the status value < quantity_needed with the difference being shown. I created the code to show just the list(without anything else). Below is a part of my productDAOImpl:
@Transactional
@Override
public List<Product> buyList() {

    // get the current hibernate session
    Session currentSession = sessionFactory.getCurrentSession();

    // query the database to find the requested items
    Query<Product> theQuery = currentSession.createQuery("from Product p where p.status<p.quantityNeeded");

    // get the result list
    List<Product> buyList = theQuery.getResultList();

    return buyList;
}

and a the controller:
@GetMapping("/buy")
public String buyList(Model theModel) {

    // get the requested list of items to be bought
    List<Product> theProduct = productDAO.buyList();

    // add them to the page
    theModel.addAttribute("products", theProduct);

    return "buy-list";
}

part of my JSP:
<c:forEach var="tempProduct" items="${products}">

        ${tempProduct.productName}
        {tempProduct.difference}

In my product entity I created a new field difference
// field for quantityNeeded-status value
@Transient
private int difference;
public int getDifference(Integer quantityNeeded,Integer status) {

    difference=quantityNeeded-status;

    return difference;
}

As mentioned above, the list I am showing should also have a new parameter, which will be calculated(as a difference of 2 ints from the database).This value will be shown on the page.
How can I do this?

A: Although it seems a good and straightforward approach, you should never propagate the domain model object outside the business layer, for instance by using entities in the front end.
What you should do, is to create a service layer, with its own dto, where you would put all the information you need to pass to the front end.
So, if your frontend layer needs specific information from the backend, you will create a ProductDTO file with only the fields you need, for instance the productName and the priceDifference.
The service layer will retrieve the information from the DAO, and then translate it into the DTO, to decouple the responsibilities between the datasource and the presentation.
This way, if you change the logic of the calculation of the priceDifference, you just replace the business logic, while the presentation layer will continue working.
I would change:
List<Product> theProduct = productDAO.buyList();

to
List<ProductDTO> theProduct = productService.buyList();

The ProductDTO is a simple POJO with the fields you need and the service would have something like:
public List<ProductDTO> buyList() {
    List<Product> myProducts = productDAO.buyList();
    //convert the myProduct list to a list of ProductDTO
    //calculate the priceDifference
    //return the list od DTOs
    return dtoList;
}

A: Quick dirty way -- create the correct getter
public int getDifference() {
   return quantityNeeded-status;
}

Proper way is @senape's mentioned above.


text:
Q: Mysql count columns values based on condition I have a table with columns day, month, year, total_payments. And I have to calculate total_payments according to days, months, years.
How can I calculate values?
I am thinking code like :
select
    month, year, sum(total_payments)
from
    webassignment.subscription_stats
group by
    day;

select
    month, year, sum(total_payments)
from
    webassignment.subscription_stats
group by
    month;

select
    month, year, sum(total_payments)
from
    webassignment.subscription_stats
group by
    year;

but it will not return the correct answers. And I want to calculate total_payments daywise, monthwise, yearwise. Please help me to find values.
Sample input :
Day Month   Year    Total_payments
10  01      2008    10
10  01      2008    20
11  02      2008    10
10  03      2010    10

Output:
Daywise :
day month year total_payments
-----------------------------
10  01    2008 30
11  02    2008 10
10  03    2010 10

Same for month and yearwise

A: A way could be the use on an union for show the different result based  on different group by level
  select day, month,year,sum(total_payments)
  from webassignment.subscription_stats group by day, month,year
  union
  select null, month,year,sum(total_payments)
  from webassignment.subscription_stats group by month,year
  union
  select null, null ,year,sum(total_payments)
  from webassignment.subscription_stats group by year
  order by year, month, day

for the sample you provided should be enough
  select day, month,year,sum(total_payments)
  from webassignment.subscription_stats group by day, month,year
  order by day, month,year

A: You can get a summary with Totals by Year, Month and Day using GROUP BY WITH ROLLUP:
SELECT
    `Year`,
    `Month`,
    `Day`,
    SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`,`Month`,`Day` WITH ROLLUP;

If you want individual queries for Year, Month and Day:
By Year:
SELECT
    `Year`,
    SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`
ORDER BY `Year;

By Month:
SELECT
    `Year`,
    `Month`,
    SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
WHERE `Year` = 2017
GROUP BY `Year`,`Month`
ORDER BY `Year`,`Month`;

By Day:
SELECT
    `Year`,
    `Month`,
    `Day`,
    SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`,`Month`,`Day`
ORDER BY `Year`,`Month`,`Day`;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why entity framework need generate local query view? How about Nhibernate?
I found a very interesting in page: http://msdn.microsoft.com/en-us/library/cc853327.aspx
Here you can see during query stages, there is an stage named "Generating views" will cost a lot. Even though EF provides some method to pre-compile  it, but if you have many query without pre-compile you still may get problems.
You can find How to: Pre-Generate Views to Improve Query Performance here: http://msdn.microsoft.com/en-us/library/bb896240.aspx
And here, you can see query without pre-generate will cost twice time. So that means it does cost a lot. http://blogs.msdn.com/b/appfabriccat/archive/2010/08/06/isolating-performance-with-precompiled-pre-generated-views-in-the-entity-framework-4.aspx
So I have a question, why EF design this stage? And does NHibernate also have this stage? If true, how about it performance in Nhibernate?

A: EF views have nothing to do with SQL views - EF views are mapping transformation compiled into executable code. EF use these transformation to convert its query representation into target SQL representation. The reason for this compilation is performance of the whole application - you need to invest time to initialization but all your subsequent queries and updates will use compiled code instead of some lookup in EDM. If you don't need to modify mapping at runtime you can even pre-compile those views during compilation of your application.
EF views are used for query preparation (transforming one representation into another) but the query preparation must be done for each unique query. In EF 4 this preparation is not cached unless you manually use Compiled query. In EF 4.5 and 5.0 (.NET 4.5) all queries are automatically "compiled" = there is the cache and each unique query is really prepared only once. Subsequent execution of the same query use compiled version from the cache.
You can read more about performance and EF 5.0 in this beginner guide.


text:
Q: Flattening and projection of a covariance matrix onto a vector in the x-y plane I am working with a covariance matrix $P \in R^3$ that I need to simultaneously project onto a vector $\mathbf{v}_f \in R^3$ and flatten into the plane $z=0$. A paper in my posession states that the formula for this is
$$\mathbf{u}_z = \begin{bmatrix} 0 & 0 & 1 \end{bmatrix}^T$$
$$J = I_{3\times 3} - \frac{\mathbf{v}_f\mathbf{u}_z^T}{\mathbf{v}_f^T\mathbf{u}_z}$$
$$P_{flat} = JPJ^T$$
My primary question is how to obtain J, meaning, how to project $P$ onto $v_{f}$ and flatten it onto $z=0$. I have neither seen this formula  anywhere else nor am I able to reproduce it from any approach I've tried based on other stack exchange answers having to do with orthogonal projections. The closest I have gotten is the projection matrix onto $\mathbf{v}_{flat} \in R^3$ with
$$M=\frac{\mathbf{v}_{flat}\mathbf{v}_{flat}^T}{\mathbf{v}_{flat}^T\mathbf{v}_{flat}}$$
Where
$$\mathbf{v}_{flat}=\mathbf{v}_f - (\mathbf{v}_f^T\mathbf{u}_z)\mathbf{u}_z$$
But this does not work out to the described formula from the paper I have.


text:
Q: Is redux Toolkit only used for Hooks ? If not please provide official documentation for using RTK for Class Components & video content online Is redux Toolkit only used for Hooks ? If not please provide official documentation and video content online!
if possible please provide any youtube videos link which explains Redux Toolkit in Class components

A: React class components are pretty much legacy at this point - you should really not be writing new code with them, as most new libraries do not provide functionality for it. The whole ecosystem is shifting towards a hooks-only approach since 2019.
But apart from that, React Toolkit is completely platform independent (apart from the RTK-Query /react entrypoint, which only provides hooks - see reasoning above).
You use Redux Toolkit with React - just like plain Redux - using the react-redux library, which provides the useSelector and useDispatch hooks as well as the connect function, which can be used to use Redux (with or without Toolkit) with class components.
connect is at this point considered a legacy api. It will stay around for the forseeable future, but might work less well in some edge cases of future React 18, since React 18 is really tailored around concepts that do not work well with class components.
If you need information on that, please see the React-Redux documentation, not the Redux Toolkit documentation.


text:
Q: Yielding on UnityWebRequest's 'Send()' makes two calls instead of just one I have already searched, but maybe just couldn't find the right words.
The point is, I'm doing requests to a nodejs/express through Unity/C# using UnityWebRequest on a Coroutine and it always send two requests as the server always print 'request received' twice.
//UNITY C# REQUEST
IEnumerator RequestRoutine () {
    using ( UnityWebRequest req = UnityWebRequest.Get ( "http://localhost:8080/blablabla" ) ) {
        yield return req.Send ();

        yield return req.isDone;
        Debug.Log ( "is done" );
    }
}

//NODE.JS server
app.get('/blablabla', (req, res) => {
    console.log('request received')
    res.end()
})


text:
Q: Spring AMQP with RabbitMQ receiving same message I have small rabbitmq spring boot application:
@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory)
{
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);
    factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
    return factory;
}

Simple queue definition:
@Bean
public Queue queue()
{
    return new Queue("queue");
}

And a simple listener which logs the message:
@RabbitHandler
public void process(@Payload Message message)....

I am seeing that the same message is being sent multiple times before the
removed from queue.
How can i change this config to ensure the message is sent exactly once.

A: If your listener throws an exception the message will be requeued and sent.
It cannot be sent multiple times otherwise - impossible.
Turn on DEBUG logging to watch the message flow.


text:
Q: How to get view from drawer header layout with binding in activity? So this is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context="MainActivity"
    >
    <!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <!-- As the main content view, the view below consumes the entire
             space available using match_parent in both dimensions. -->

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:id="@+id/ll_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/my_awesome_toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@android:color/black"
                    android:fitsSystemWindows="true"
                    >

                    <TextView
                        android:id="@+id/toolbar_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="10dp"
                        android:layout_marginStart="10dp"
                        android:textColor="@android:color/white"
                        android:textSize="@dimen/abc_text_size_title_material_toolbar"
                        tools:text="@string/default_toolbar_title"/>

                </android.support.v7.widget.Toolbar>

                <FrameLayout
                    android:id="@+id/container"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                </FrameLayout>
            </LinearLayout>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_fuf"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginBottom="20dp"
                android:layout_marginEnd="20dp"
                android:layout_marginRight="20dp"
                android:src="@drawable/flamme"
                app:fabSize="normal"
                />
        </RelativeLayout>

        <android.support.design.widget.NavigationView
            android:id="@+id/navigation_view"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@android:color/black"
            **app:headerLayout="@layout/drawer_header"**
            app:itemTextColor="@color/drawer_item_color_selector"
            app:menu="@menu/menu_drawer"/>

    </android.support.v4.widget.DrawerLayout>
</layout>

and I am using binding for the activity so I don't have to use the findViewById and cast it etc.. like this:
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

        Toolbar toolbar = binding.myAwesomeToolbar;
        toolbarTitle = binding.toolbarTitle;
        BalrogFontsHelper.SetKhandBoldToView(toolbarTitle);
        setSupportActionBar(toolbar);
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeAsUpIndicator(R.drawable.ic_dehaze_white_24);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
            actionBar.setDisplayShowTitleEnabled(false);
        }

        drawerLayout = binding.drawerLayout;
        **tvLoggedUserEmail = (TextView) findViewById(R.id.tv_logged_user_email);**
        BalrogFontsHelper.SetKhandBoldToView(tvLoggedUserEmail);

As you can see, I can get the views that are directly in the activity_main.xml layout by binding but when the view I am trying to get is not there I can't see the variable in the binding object.
drawer_header.xml:
    <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="96dp"
                xmlns:tools="http://schemas.android.com/tools"
                android:background="@android:color/black"
                android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <TextView
        android:id="@+id/tv_logged_user_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="16dp"
        tools:text="@string/login_placeholder_email"
        android:textAllCaps="true"
        android:textAppearance="@style/TextAppearance.AppCompat.Body2"
        android:textSize="20sp"/>

</RelativeLayout>

How could I get this tv_logged_user_email TextView in a binding way so I have:
**tvLoggedUserEmail = binding.tvLoggedUserEmail;**

A: ImageView imageView = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.imageButton);

imageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if (flag) {
            navigationView.getMenu().clear(); //clear old inflated items.
            navigationView.inflateMenu(R.menu.drawer_view1);
            flag = false;
        } else {
            navigationView.getMenu().clear(); //clear old inflated items.
            navigationView.inflateMenu(R.menu.drawer_view);
            flag = true;
        }
    }
});

A: If you set app:headerLayout="@layout/drawer_header then you don't have to inflate the view again. You can just use .bind instead of .inflate.
You can get the already inflated header view and bind it like this:
View headerView = binding.navigationView.getHeaderView(0);
DrawerHeaderBinding headerBinding = DrawerHeaderBinding.bind(headerView);

A: Updated solution (13/11/2015)
Solution: Update your Design Support Library to 23.1.1:

Changes for Design Support library 23.1.1:

*

*Added the getHeaderView method to the NavigationView class.

*Fixed a transparent background issue for a FloatingActionButton object on devices running Android 4.0 (API level 15) and lower. (Issue 183315)

See https://developer.android.com/tools/support-library/index.html for more info

Original solution
I don't know why there is no method which provides header view
attached programmatically.
Instead, here's two solutions:
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
View headerView = navigationView.inflateHeaderView(R.layout.header_layout)
ImageView iv = (ImageView)headerview.findViewById(R.id.your_image_view)

Or:
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
View headerView = LayoutInflater.from(this).inflate(R.layout.header_layout, navigationView, false);
navigationView.addHeaderView(headerView);

ImageView iv = (ImageView) headerView.findViewById(R.id.yourImageView)

A: I have a slightly cleaner solution, where I don't have to "pollute" fragment/activity with code responsible for inflating and adding header view to NavigationView. I implemented extension class for NavigationView. I did that like this:
Layout of my activity:

<data>
    <variable
        name="dashboard"
        type="ramps.view.model.DashboardScreenViewModel"/>
</data>

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/activity_dashboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        bind:dashboard="@{dashboard}"
        />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:background="@color/white"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:navigationItemSelectedListener="@{dashboard.onMenuItemSelected}"
        app:model="@{dashboard.score}"
        app:menu="@menu/activity_main_drawer"/>

</android.support.v4.widget.DrawerLayout>

As you can see, there is no app:headerLayout in NavigationView, but I have added my custom app:model, with data I want to pass to the header layout.
How did I define this custom parameter? By extension class:
public class NavigationViewExtensions {

@BindingAdapter({"bind:model"})
public static void loadHeader(NavigationView view, ScoreViewModel model) {
    ViewNavigationHeaderBinding binding = ViewNavigationHeaderBinding.inflate(LayoutInflater.from(view.getContext()));
    binding.setScore(model);
    binding.executePendingBindings();
    view.addHeaderView(binding.getRoot());
  }
}

Just place this class anywhere in your project. And the layout of my header:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bind="http://schemas.android.com/apk/res-auto"
>

<data>

    <import type="android.view.View"/>

    <variable
        name="score"
        type="ramps.view.model.ScoreViewModel"/>
</data>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/graphite"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin_large"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin_large"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <include
        android:id="@+id/player_details_header_score"
        layout="@layout/view_avatar_score_header"
        bind:score="@{score}"/>

</LinearLayout>

A: I have/had the same problem.
A workaround is to inflate the header view and add it programatically.
Like this:
DrawerHeaderBinding drawerHeaderBinding = DrawerHeaderBinding.inflate(LayoutInflater.from(navigationView.getContext()));
navigationView.addHeaderView(drawerHeaderBinding.getRoot());
drawerHeaderBinding.tvLoggedUserEmail = "email";
drawerHeaderBinding.executePendingBindings();

So remove the app:headerLayout and do it programatically. I do think google should fix the core issue here though, either in the design library or in the data binding library.

A: Quite a simple solution here. Let's suppose you added your NavigationView as
<android.support.design.widget.NavigationView
    android:id="@+id/navigationView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/my_nav_drawer_header"
    app:menu="@menu/menu_nav_drawer"/>

And that you want to access a TextView in my_nav_drawer_header.xml that has an id of textView2. So you would just use this code in your activity:
View headerContainer = navigationView.getHeaderView(0); // This returns the container layout from your navigation drawer header layout file (e.g., the parent RelativeLayout/LinearLayout in your my_nav_drawer_header.xml file)
TextView textView2 = (TextView)headerContainer.findViewById(R.id.textView2);
textView2.setText("Sorted!");

No need to inflate or interfere with your existing code, etc.

A: Try this with DataBinding library it works for me.
navigation_view_header.xml:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="@dimen/navigation_view_header_height"
    android:paddingLeft="@dimen/navigation_view_padding"
    android:paddingTop="@dimen/navigation_view_top_padding"
    android:background="@color/colorPrimary">

    <ImageView
        android:id="@+id/avatar"
        android:layout_width="@dimen/avatar_dimen"
        android:layout_height="@dimen/avatar_dimen"
        android:contentDescription="@null"
        android:src="@drawable/default_avatar" />

    <TextView
        android:id="@+id/profile_email"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_below="@+id/avatar"
        android:text="email"
        android:textColor="@color/white"
        android:layout_alignParentBottom="true"
        android:gravity="center_vertical" />

</RelativeLayout>
</layout>

activity_main.xml:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="navigationItemSelectedListener"
            type="com.example.MainActivity"/>
    </data>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:tag="layout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/my_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:titleTextColor="@color/white"
            android:background="@color/colorPrimary"
            app:theme="@style/Toolbar.Theme"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="@dimen/navigation_view_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:theme="@style/Theme.AppCompat.Light"
        app:menu="@menu/drawer_menu"
        app:navigationItemSelectedListener="@{navigationItemSelectedListener::onNavigationItemSelected}"/>

</android.support.v4.widget.DrawerLayout>
</layout>

and within your activity:
ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this,
                R.layout.activity_main);
activityMainBinding.setNavigationItemSelectedListener(this);/* with this line navigation menu item selection events are handled in onNavigationItemSelected() specified in navigation_view_header.xml*/

NavigationViewHeaderBinding navigationViewHeaderBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.navigation_view_header,activityMainBinding.navigationView,false);
        activityMainBinding.navigationView.addHeaderView(navigationViewHeaderBinding.getRoot());

and make sure your activity implements NavigationView.OnNavigationItemSelectedListener

A: *

*Edit your gradle file to update com.android.support libraries to version 23.1.1 or beyond.

*Use navigationView.getHeaderView(i), where i is the index of the headerview. If you just defined this view on layout, is 0.

A: I have updated build tools from Android sdk manager, then 23.1.0 is also working fine for me.
I am using buildToolsVersion "23.0.2" Before this it was 23.0.1.
and there is no need of using:
(View) navigationView.findViewById(R.id.idOfViewFromHeaderView);

In your activity you can directly use:
(View) findViewById(R.id.idOfViewFromHeaderView);

A: Just put navigationView.getHeaderView(0) then use any views
        TextView profile,info;
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        profile = navigationView.getHeaderView(0).findViewById(R.id.profile);
        info = navigationView.getHeaderView(0).findViewById(R.id.info);
        profile.setOnClickListener(this);
        info.setOnClickListener(this);

A: You can do this. First initialize the navigation view.
    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);

and then initialize all the views that is inside of navigationView.
    CircleImageView circleView = (CircleImageView) navigationView.findViewById(R.id.circleView);
    TextView name = (TextView) navigationView.findViewById(R.id.name);
    TextView email = (TextView) navigationView.findViewById(R.id.email);
    LinearLayout header = (LinearLayout) navigationView.findViewById(R.id.header);

and then you can use those views as you wish.
eg:
        name.setText(NAME);
        email.setText(EMAIL);

A: It works for me.
MainActivity.java:
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);

    NavHeaderMainBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.nav_header_main, navigationView, false);

    navigationView.addHeaderView(binding.getRoot());

activity_main.xml:
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <RelativeLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <include layout="@layout/toolbar" />

        </android.support.design.widget.AppBarLayout>

    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

nav_header.xml:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

    <variable
        name="account"
        type="lonja.dreamteam.su.trainingdiary.view_model.AccountViewModel"/>

</data>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/header_background"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/imageView"
        android:layout_width="72dp"
        android:layout_height="72dp"
        android:src="@{account.sex}"
        app:civ_border_color="@color/colorAccent"
        app:civ_border_width="0dp" />

    <TextView
        android:id="@+id/userName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="@{account.name}"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

</LinearLayout>


text:
Q: Bootstrap (4.3.1) Card with Navigation Tabs - I need the "default" tab to be automatically selected I have a Bootstrap Card and inside this card I have Navigation tabs that open tab-panes, I need to have the first (Default) Tab to be selected and opened when the user arrives on the page

                    Main

.....

I have tried aria-expanded aria-selected and aria-pressed in both the content and header but no difference

A: Add the class active against the

*

*anchor with class nav-link i.e. Main

*div with the class tab-pane i.e.

working snippet:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

            Home

            Menu 1

            Menu 2

HOME

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Menu 1

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Menu 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.


text:
Q: How can i remove the first x number of characters of a column name from 200+ columns with each column being not the same number of characters How can I remove a specific number of characters from a column name from 200+ column names for example: "Q1: GOING OUT?" and "Q5: STATE, PROVINCE, COUNTY, ETC" I just want to remove the "Q1: " and the "Q5: "I have looked around but haven't been able to find one where I don't have to manually rename them manually. Are there any functions or ways to use it through tidyverse? I have only been starting with R for 2 months.
I don't really have anything to show. I have considered using for loops and possibly using gsub or case_when, but don't really understand how to properly use them.
#probably not correctly written but tried to do it anyways

for ( x in x(0:length) and _:(length(CandyData)-1){
  front -> substring(0:3)
  back -> substring(4:length(CandyData))
  print <- back
}

I don't really have any errors because I haven't been able to make it work properly.

A: Try this:
    col_all<-c("Q1:GOING OUT?","Q2:STATE","Q100:PROVINCE","Q200:COUNTRY","Q299:ID") #This is an example.If you already have a dataframe ,you may get colnames by **col_all<-names(df)**

    for(col in 1:length(col_all))              # Iterate over the col_all list
    {
        colname=col_all[col]                   # assign each column name to variable colname at each iteration
        match=gregexpr(pattern =':',colname)   # Find index of : for each colname(Since you want to delete characters before colon and keep the string succeeding :
        index1=as.numeric(match[1])            # only first element is needed for index
        if(index1>0)
        {
            col_all[col]=substr(colname,index1+1,nchar(colname))#Take substring after : for each column name and assign it to col_all list
        }

    }

    names(df)<-col_all                  #assign list as column name of dataframe

A: The H 1 answer is still the best: sub() or gsub() functions will do the work. And do not fear the regex, it is a powerful tool in data management.
Here is the gsub version:
names(df) <- gsub("^.*:","",names(df))

It works this way: for each name, fetch characters until reaching ":" and then, remove all the fetched characters (including ":").
Remember to up vote H 1 soluce in the comments


text:
Q: how to edit relationship fields in salesforce can we edit relationship fields in salesforce, like editing account name in opportunity details
page without navigating to account tab. If anyone has implemented using visualforce page, please post the code.

A: What you're asking about appears to be "Can I edit a related record from the compact layout that appears when I hover over a relationship field?"
The answer to that is no. The compact layout is only for display.
I suspect that with enough effort, you could replicate the functionality of compact layouts (and add inline editing), but it's unlikely that the effort required would be worth it.
Training your users to use the middle-click on their mice (on Windows/Linux) to open the parent record in a new tab is likely a much easier and cheaper solution.


text:
Q: merge multidimensional array cakephp i have a function in my appController ..i am not good in arrays so i want to merge these two functions
First Array
public $components = array(
    'Session',
    'Auth'=>array(
        'loginRedirect'=>array('controller'=>'users', 'action'=>'controlpanel'),
        'logoutRedirect'=>array('controller'=>'users', 'action'=>'index'),
        'authError'=>"You can't access that page",

        'authorize'=>array('Controller'),
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email')

            )
        )
    )
);

second Array
$this->Auth->authenticate = array(
        'Authenticate.MultiColumn' => array(
            'fields' => array(
                'username' => 'email',
                'password' => 'password'
            ),
            'columns' => array('email', 'mobileNo'),
            'userModel' => 'User',

        )
    );

what i want is i want to add Second function into first function if that possible

A: Assuming you want to merge two arrays as described in your description (not to arrange), then you should use CakePHP's Hash class, specifically the merge function. You can read more in the documentation.
$merged_array = Hash::merge($array1, $array2);


text:
Q: can symfony 2.8 updated with twig 2.4.4? Currently the application have symfony 2.8.42 and twig version 1.35.3.
Due to some security issue in twig we need to upgrade twig to 2.4.4 and above. But I am not sure as what else will be broken once I update the twig version ?
I cannot find anywhere for symfony 2.8 compatible twig versions or vice versa.
Can someone help me with the compatible version and what are the things that will break if I update twig to 2.4.4 ?

A: I tested myself by updating and was able to update to twig 2.4.4 without any issues. Changes the composer.lock file for the same and did the composer install again, the new twig version as created successfully.


text:
Q: Google Play Services were not found When trying to start my activity conatining an adView I receive following logcat exception:
02-26 16:02:29.766: E/GooglePlayServicesUtil(26683): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.

I created the AdView programmatically (without xml file) like that:
public class StartActivity extends Activity {

private AdView adView;
    private RelativeLayout relativeLayout;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start);
    adView = new AdView(this);
    adView.setAdUnitId("xxx");
    adView.setAdSize(AdSize.SMART_BANNER);
    relativeLayout = (RelativeLayout)findViewById(R.id.activity_start);
    relativeLayout.addView(adView);
    AdRequest.Builder adRequest = new AdRequest.Builder();
    adRequest.addTestDevice("018eb6f8");
    adView.loadAd(adRequest.build());
}
}

That's how my activity containing the adview looks like.
my manifest file looks like that (removed other irrelevant activities):
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="19" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
</application>

as you can see I've imported the google-play-services-lib to eclipse:

and here you can see I've linked it up with my project:

Any ideas?

A: You are getting this error because you have to link Google Play Service Project to yours. You can do this by copying Google Play services project from:
...\android-sdk-folder\extras\google\google_play_services.
Import this project to Eclipse and them add it as a labrary in your project's build path.


text:
Q: Existence of coproducts and products in category I am very beginner in Category theory, and the question I am asking here is related with some example of category theory coming from simple theorems in ring theory.
Fact: Let $R$ be a commutative ring with unity. If l.c.m. of $a,b$ in $R$ exists then $g.c.d.$ exists.
Now let us move in Category theory theory with a specific example. Let $R$ be a ring with unity. Define a category as follows:
Objects: members of $R$.
Morphisms: if $a$ divides $b$ in $R$, let $k_a^b$ denote a morphism, o.w.  no morphism between $a$ and $b$.
Thus, the set of morphisms between $a$ and $b$ is either singleton (when $a$ divides $b$) or empty.
Then the co-product of two objects in this category is l.c.m. and product is g.c.d. Of course, the product or co-product of two objects may not exists in this category, for certain rings $R$.
Now the fact mentioned in the beginning says that

if co-product of two objects in the above category exists, then the product of the same  two objects also exists.

My natural question is, whether such phenomena occurs in every category, i.e.
Question: If $\mathcal{C}$ is any category, and if co-product of two objects $A,B$ in $\mathcal{C}$ exists, then is it necessary that the product of $A$ and $B$ also exists?

Please do corrections in the setting if there are mistakes in presenting category theory statements; as said initially, I am very beginner in Category theory.

A: Genrally, no. Simply take a category with three objects $a,b,c$ and other than identity morphisms only two morphisms $a\to c$ and $b \to c$. Then $c$ is the coproduct of $a$ and $b$ but their product does not exist. Take the opposite category, and you'll products withour co-roducts.
This is related to Birkhoff's theorem in lattice theory: if a lattice has all meets, then it has all joins (and vice versa). When a lattice is viewed as a catgory, that theorem becomes: if a thin category has all limits, then it has all colimts (and vice versa). For arbitrary categories this is also true but you must demand really demand all limits exist, namely not just small ones, but then by Freid's theorem such a category must be thin, so you reduce back to the previous setting. There are of course plenty of examples of complete categories that are not cocomplete, so size issues play a vital role here.


text:
Q: JQuery html on a different pages One of my pages is becoming overcrowded with html forms and js. So I was wondering if there is a way to have the form on one page and then the js on another. If you could refer me to a good site that addresses this I would really appreciate it.
Thanks

A: There is an excellent way.  You put your JavaScript in a file, say /scripts/someStuff.js off of your web root, and import it using
<script type="text/javascript" src="/scripts/someStuff.js"></script>

A: In JavaScript you can reference objects in another window, if openen with the window.open method. References take the form:
window.opener.form.fieldname.value

A: I am giving you a test example for that
I have a external js file named test.js that i have kept in Script folder in my root directory
I have button on my page and on its click event client side code is written in test.js file
Main page code
<html>
<head id="Head1">
    <title></title>
    <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script src="Scripts/test.js" type="text/javascript"></script>
 </head>
<body>
    <input id="TestButton" type="button" value="Test" />
</body>
</html>

External js code in Test.js file
$(function()
{
    $('#TestButton').click(function()
    {
        alert('I am clicked.');
    });

});


text:
Q: C++ declared constant named the same as a defined constant Is there a standard or good way of avoiding declared constants being named the same as a defined constant.
My Problem,
Im trying to compile my program using autoconf in linux which defines VERSION but in one of Mongo's db header files they declare a constant named VERSION. There's obviously a problem naming a variable using a right hand value.
Normally I would just change the name but in this case its not my library. I could figure out how to rename the defined variable autoconf.
Any suggestions?

A: You have to use no-define along with AM_INIT_AUTOMAKE in your configure.ac file.

By default this macro AC_DEFINE's PACKAGE and VERSION. This can be
  avoided by passing the no-define option, as in:
AM_INIT_AUTOMAKE([gnits 1.5 no-define dist-bzip2])

See Automake manual.

A: If you've localized the error, you can do something like this:
const unsigned int OLD_VERSION = VERSION;
#undef VERSION
#include <mongodb_header.h>

and then use OLD_VERSION in your code, instead of VERSION. Or just define your version in another namespace.
Also, file a bug in Mongodb. This is not the correct behavior of using just VERSION as a name in the outer namespace. It should check at least if VERSION is already defined, or prefix the variable such as MONGODB_VERSION, or something like that.

A: In general there's no good way to safeguard yourself against what some 3rd party library might pollute the global namespace with. This is why god invented namespaces.
You can use namespaces if VERSION is a global symbol known at compile time:
namespace yourStuff
{
    int VERSION;

    // references to VERSION here refer to the inner VERSION, not ::VERSION
}

but if VERSION is a preprocessor macro (as I suspect with its capitalization) then it doesn't follow any compilation rules and exists outside the rules of the compiler. You can detect it with other preprocessor macros:
#ifdef VERSION
 // define it to be something else
#else
#endif

(or use #undef like in Diego's answer to kill it)
But doing that everywhere VERSION is references will get nasty. You'll just need to not use VERSION.


text:
Q: How to make a dynamic layout that is larger than screen? I want to create a dynamically extending layout that may grow reflecting to user's input.  First, I've created an activity layout that allows scrolling in both directions (this is not my invention, I've used the idea explained in a comment to another question with some improvements):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clipChildren="false"
    android:clipToPadding="false"
    tools:ignore="UselessParent" >

    <FrameLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clipChildren="false"
        android:clipToPadding="false" >

        <RelativeLayout
            android:id="@+id/content"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:clipChildren="false"
            android:clipToPadding="false" >

        </RelativeLayout>
    </FrameLayout>
</FrameLayout>

Then, I created a simple UI layout, a text view and a vertical linear layout, below.  Here is my message_with_replies.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clipChildren="false"
    android:clipToPadding="false"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/header"
        android:layout_width="300dp"
        android:layout_height="wrap_content" >

<!-- some text views and buttons here,
    I've removed them to keep things simple,
    see the screenshot below -->

    </LinearLayout>

    <LinearLayout
        android:id="@+id/replies"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>

Note the 10dp margin in the replies layout and the attributes related to clipping.
So I can now inflate an item with the message_with_replies layout and add it to the content layout of the activity, and then inflate another item and add it to the replies linear layout withing the first item and so on, thus creating a tree-like hierarchy.  And the whole tree is displayed and scrolled both horizontally and vertically.
However, it looks like the layout is still limited somehow with the screen size.  I have two problems:
1) The items beyond the right edge look fine but don't receive user input.
2) The layout beyond the bottom edge is messed up.
Here is the screenshot.  From left to right: 1) Everything looks fine, 2) Oops, the button is on the edge, 3) Oops, the bottom is messed up.

Looks like I missed something simple but hidden.  How do I make the layout work beyond the screen edges?

A: The solution is surprisingly simple.
In the activity layout, a RelativeLayout node (the one with content ID) should use the custom layout class that overrides the onMeasure method.
So here is the fix for the activity layout:
<com.sample.MyRelativeLayout
    android:id="@+id/content"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clipChildren="false"
    android:clipToPadding="false" >
</com.sample.MyRelativeLayout>

and here is the class implementation:
public class MyRelativeLayout extends RelativeLayout {
    public MyRelativeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(0, 0);
    }
}

Note that I don't have to calculate anything, passing (0, 0) works just fine.
Frankly speaking, I don't yet understand all pros and cons of this solution, but it works properly.  The only issue that I have noticed so far is that the more items I expand, the slower the UI responds.
I'll appreciate any comments or suggestions.


text:
Q: How to make Java code pause and resume after event without polling I am working in 2 applications.
In the first one I need to detect if a file or folder has been modified. I would like to do this without continuously polling the file to save system resources. I have been taking a look at the Google Drive program and it doesn't consume any resources while there is no modifications on the synced folder, is this possible in java?
Lastly I am trying to implement an input stream that reads characters from a Queue until it finds a new line character '\n'. I would like for it to pause if the Queue is empty until it is populated again, how could this be done without continuously checking if the Queue is empty? Please remember that an InputStream is supposed to pause the program's execution while it gets the data.


text:
Q: Flutter : How to add element to map field inside firebase database? I'm trying to find a way to add element to map field inside firebase database from my flutter code. The element as well is a map. So it's a nested map.
 Future updateImageDate({
        String token,
        int rating,
        int like,
        int display_count,
        //Map participants,
      }) async {
        return await pictureCollection.document(token).updateData({
          'rating': rating,
          'like': like,
          'display_count': display_count,
          //'participants': participants,
         // I want to add only one element to this existing map field in firebase database.
         // Although currently it's empty, I want to keep add new element every time I use this method.
        // The element as well is a map. So it's a nested map.

        });
      }

Please help me! I'm looking forward to hearing from you. Thank you in advance. :D

A: To write to a map, use dot (.) notation. So:
pictureCollection.document(token).updateData({ 'path.to.field': 'new value' });


text:
Q: Вызов default метода интерфейса из потомка, Java 8 Я хочу вызвать дефолтный метод из интерфейса, но компилятор это не пропускает.
public class HelloWorld{

 public static void main(String []args){
    B b = new B();
    b.a();
 }
}

interface A{
    default void a() {
        System.out.println("Hi from A.a");
    }
}

class B implements A {
    @Override
    public void a() {
        super.a();   // Error
        System.out.println("Hi from B.a");
     }
}

Если это нельзя сделать, обьясните пожалуйста почему.

A: default методы добавлены для обеспечения обратной совместимости с ранними версиями Java.
Используя их вы можете расширить уже существующий интерфейс не ломая код, который написан для предыдущей версии интерфейса. Все, что будет нужно - это перекомпилировать его. А так как в предыдущей версии этого метода не было, то вы не можете его вызвать используя super.
Вам нужно использовать абстрактный класс вместо интерфейса или не переопределять метод интереса.
Абстрактный класс
public class HelloWorld{
    public static void main(String []args){
        B b = new B();
        b.a();
    }
}

abstract class A {
    void a() {
        System.out.println("Hi from A.a");
    }
}

class B extends A {
    @Override
    public void a() {
        super.a();
        System.out.println("Hi from B.a");
    }
}

Интерфейс
public class HelloWorld{
    public static void main(String []args){
        B b = new B();
        b.a();
    }
}

interface A{
    default void a() {
        System.out.println("Hi from A.a");
    }
}

class B implements A {
}

A: A.super.a();

Вот так можно вызвать


text:
Q: Generic function that uses a delegate to centralize boilerplate code? I'm writing a class that's similar to a WCF interface proxy but that has some specialized but boilerplate extra code in it. I would like to extract the boilerplate code and use a generic or other mechanism to wrap calls to an internal instance of a class.
public interface IMyInterface
{
  long fn1(int param1, int param2);
}

public class MyInterfaceProxy : IMyInterface
{
  // generated code
}

public class MyClass : IMyInterface
{
  private MyInterfaceProxy _myProxy; // implements IMyInterface
  public long fn1(int param1, int param2)
  {
    long result = null;
    CallMethod(
               delegate(IMyInterface svc)
               {
                   result = svc.fn1(param1, param2);
               });
    return result;
  }

  private T CallMethod( ??? )
     where T : class
  {
    T result = null;

    // some boilerplate code
    // Call the delegate, passing _myProxy as the IMyInterface to act on
    // some more boilerplate code

    return result;
  }

}
If it helps, the boilerplate code can represent retry logic, timeout behavior, standardized exception handling behavior, etc.
So here are my questions:

*

*Is there a standard or preferred way to solve this problem?

*If generics are the preferred mechanism, what is the signature of the CallMethod function?

A: I think this is what you are looking for.  There is a lot more that can be done composing functions.  This is the very surface scratching of functional programming paradigms, and it's really great that we can use some of it in c# now.
EDIT: added the anonymous function implementation as well to better simulate your delegate scenario.
class Program
{
    static void Main(string[] args)
    {
        string resFromFunctionToBeWRapped = CallMethod(() => FunctionToBeWrapped());

        int resFromAnon = CallMethod(() => {
            Console.WriteLine("in anonymous function");
            return 5;
        } );

        Console.WriteLine("value is {0}", resFromFunctionToBeWRapped);
        Console.WriteLine("value from anon is {0}", resFromAnon);

        Console.ReadLine();
    }

    private static TResult CallMethod<TResult>(Func<TResult> functionToCall) //where T : class
      {
        Console.WriteLine ("in wrapper");

        var ret = functionToCall();

        Console.WriteLine("leaving wrapper");

        return ret;
      }

    private static string FunctionToBeWrapped()
    {
        Console.WriteLine("in func");
        return "done";
    }

}


text:
Q: Switch to a different cpu thread in gdb First timer here.
While doing gdb and getting prdasummary, I know to find the panicked cpu by looking at inPanic, I also find other cpu running one process which I want to find its locals.
Can I switch to a different cpu and see its registers?
Thanks,
zXi


text:
Q: Prove that the set of non-copositive matrices is non-convex A $n\times n$ symmetric matrix $A$ is said to be copositive if $\mathbf{x}^{\top}A\mathbf{x} \geq 0$ for all $\mathbf{x}\in\mathbb{R}^{n}$ and $\mathbf{x} \geq 0$. And I want to show that the set of $n \times n$ non-copositive matrices is nonconvex unless $n=1$.
I can prove that the set of $n \times n$ copositive matrices is convex, which directly follows the definition of the convex set. But for the non-copositive part, if I pick two matrices $A$, $B$ which are not copositive, we have $\mathbf{x}_1^{\top}A\mathbf{x}_1 < 0$ and $\mathbf{x}_2^{\top}B\mathbf{x}_2 < 0$ for some $\mathbf{x}_1,\mathbf{x}_2\geq 0$. How can I prove that $\theta A+(1-\theta)B$ is copositive for some $\theta$?
Besides, I have a question about the definition of the copositive matrix: is the copositive matrix always positive semidefinite or elementwise nonnegative? Could anyone give me an example?
Thanks.

A: Let
$$A = \begin{bmatrix} 100 & 0 \\0 & -1\end{bmatrix}, B = \begin{bmatrix}-1 & 0 \\0 & 100\end{bmatrix}.$$
They are both non-copositive, but the average of them
$$\frac{A+B}{2} = \begin{bmatrix}49.5 & 0 \\ 0 & 49.5\end{bmatrix}$$
is copositive. Since the average is their convex combination, we get that the set of non-copositive matrices isn't convex.


text:
Q: Getting error while installing package in docker image The beginning of this error is from creating and password based image in Azure environment. Below is the origin or this all. More info on this I just got to know we are using alpine based image.openjdk:8uX-alpine311

So I did googled a bit and found some package needs to be installed and to do that I need to execute below command.
RUN apt-get update; apt-get install -y fontconfig libfreetype6 which resulted me in

the command bin/sh sh returned a non zero code 127

After further analysis I found another solution to this is to run below query.
RUN apk add --update fontconfig libfreetype6 as result again came as

the command bin/sh sh returned a non zero code 2

I am wondering this is just some package installation on azure environment, what it takes every time change in command's. Any help appreciated, thanks in advance.

A: the command bin/sh sh returned a non zero code 127

Means the command wasn't found. Which is correct, since you're using an alpine image and apt-get is mostly found in debian based images. See also command '/bin/sh -c returned a non-zero code: 127
Testing your command on an local alpine:3.11 image I can verify that the command fails when trying to install libfreetype6
Try RUN apk add --update fontconfig freetype
You can verify if a package is available by checking pkgs.alpinelinux.org


text:
Q: Blender to Unity, vertex smoothing I have an object in blender that has sharp corners, and easily distinguishable faces, exactly what I want. However, when I place it in Unity all of the vertices smooth out, and it is impossible to see what you are looking at. How do I get the same object that I have in Blender to show up in unity?

A: This is tackled here
blender-normal-smoothing-import-problem
Also you can calculate the normals on import via 'Smoothing angle' which will edge break/phong break based on the angles


text:
Q: What can make nanosleep drift with exactly 10 sec on mac OS X 10.9 A part of my program need to sleep for 10 milliseconds. Normally I use the boost lib for this, but it sometimes sleep for 10010 milliseconds, so I tried replacing
boost::this_thread::sleep_for(boost::chrono::milliseconds(read_delay_ms));

with
struct timespec a;
a.tv_sec  = 0;
a.tv_nsec = read_delay_ms * 1000000;
int rc = nanosleep( &a, NULL );

Not surprisingly the use of nanosleep also sometimes sleep for 10010 milliseconds (sleep_for is implemented using nanosleep() on mac).
My program is complex so I have not been able to create a small example that illustrates the issue, I am working on this. Here are some highlights:

*

*It is a python extension written in C++ using boost::python as bridge

*Uses boost::threads for asynchrony tasks using boost::asio
The issue is only seen on mac OS X 10.9. It is not seen on Mac OS X 10.8 and below, and not seen on linux, win, iOS and android.
In order to find the error in either my code, boost lib or sys functions, any help or suggestions are more that welcome.

A: App Nap is most probably the reason for this. It was introduced in 10.9 and is already known for causing such surprises.
NSProcessInfo has new three methods for temporarily disabling App Nap: beginActivityWithOptions:reason:, endActivity:, performActivityWithOptions:reason:block:.
You can also disable it by writing boolean YES into NSAppSleepDisabled user default of your application's domain.

A: Here's a programmatic solution written in C that will compile and run on both older and newer OS X versions (i.e. you don't need 10.9 or to be working in Objective C to compile this).
Call osx_latencycritical_start() at the start of your program, or at least before timing critical operations begin.
Call osx_latencycritical_end() if your code is no longer doing timing critical work.
(The code is recursion safe, but not thread safe.
 I place this code in the public domain.)
#if defined(__APPLE__)

#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
# include <objc/runtime.h>
# include <objc/message.h>
#else
# include <objc/objc-runtime.h>
#endif

/* Globals */
static int osx_latencycritical_count = 0;
static id osx_latencycritical_activity = nil;

/* Tell App Nap that this is latency critical */
void osx_latencycritical_start() {
    Class pic;      /* Process info class */
    SEL pisl;       /* Process info selector */
    SEL bawo;       /* Begin Activity With Options selector */
    id pi;          /* Process info */
    id str;         /* Reason string */

    if (osx_latencycritical_count++ != 0)
        return;

    /* Avoid triggering an exception when run on older OS X */
    if ((pic = (Class)objc_getClass("NSProcessInfo")) == nil)
        return;

    if (class_getClassMethod(pic, (pisl = sel_getUid("processInfo"))) == NULL)
        return;

    if (class_getInstanceMethod(pic,
          (bawo = sel_getUid("beginActivityWithOptions:reason:"))) == NULL)
        return;

    /* Get the process instance */
    if ((pi = objc_msgSend((id)pic, pisl)) == nil)
        return;

    /* Create a reason string */
    str = objc_msgSend(objc_getClass("NSString"), sel_getUid("alloc"));
    str = objc_msgSend(str, sel_getUid("initWithUTF8String:"), "Timing Crititcal");

    /* Start activity that tells App Nap to mind its own business: */
    /* NSActivityUserInitiatedAllowingIdleSystemSleep */
    /* | NSActivityLatencyCritical */
    osx_latencycritical_activity = objc_msgSend(pi, bawo,
                    0x00FFFFFFULL | 0xFF00000000ULL, str);
}

/* Done with latency critical */
void osx_latencycritical_end() {
    if (osx_latencycritical_count > 0) {
        osx_latencycritical_count--;
        if (osx_latencycritical_count == 0
         && osx_latencycritical_activity != nil) {
            objc_msgSend(
                         objc_msgSend(objc_getClass("NSProcessInfo"),
                                      sel_getUid("processInfo")),
                                      sel_getUid("endActivity:"),
                                      osx_latencycritical_activity);
            osx_latencycritical_activity = nil;
        }
    }
}

#endif /* __APPLE__ */


text:
Q: Set of points such that the distance is achieved by at least two geodesics is closed If $(M,g)$ is a complete Riemannian manifold and let $p\in M$. Define a function $$d^2:M\to \mathbb{R},~q\mapsto \mathrm{dist}^2(p,q).$$ Consider the set $$A=\text{Set of all points $q\in M$ such that the distance is achieved by at least two geodesics. }$$ I need to prove that the set $A$ is closed.
I tried to go by the sequence approach (as $M$ has a metric). Let $\{q_n\}$ be the points in $A$ and $q_n\to q$. I need to prove that $q\in A$. Now let $\gamma_n$  and $\eta_n$ be geodesics such that $$d(p,q_n)=l(\gamma_n)=l(\eta_n).$$ Now is it possible (or  a similar idea) to prove that limit of the two geodesics converge to the geodesic and as the length is a continuous function $$l(\gamma_n)\to l(\gamma),~~\text{and}~~ l(\eta_n)\to l(\eta),$$ which will prove that $q\in A$ and we are done.
Please tell me if this approach is valid or if any other approach I have to go through.


text:
Q: Ruby on Rails, internalization in coffescript I have a coffeescript file for one of my resources. It seems like internalization doesn't work properly in my coffescript file. I want I18 gem to transform 'select' script, but it doesn't work.
coffeescript:
console.log('employee loaded -> '+"<%= I18n.t 'select' %>")

When I open the browser console I end up with this text:
employee loaded -> <%= I18n.t 'select' %>

en.yml
en:
    select: 'Select...'

tr.yml
tr:
    select: 'Seçiniz...'

Any suggestions,
Thanks.

A: Maybe you forgot to add extension?
filename.coffee.erb


text:
Q: Exportar datos desde un progama en cobol Necesito ayuda con lo siguiente: Tengo un programa hecho en Cobol hace unos 30 años y necesito extraer la base de datos. Por mi parte no tengo ningún conocimiento en absoluto de Cobol, estuve googleando un poco pero no conseguí nada que me solucione mi problema.
Leí que utilizaban rmcobol.exe y logré encontrarlo pero no logro entender como usarlo (cuando lo ejecuto abre un cmd y lo cierra automáticamente), también leí que con un programa "recover1" el cual no pude conseguir, sin embargo entre los archivos del rmcobol que descargué hay un "recover1" pero me sucede lo mismo que con rmcobol...
El resto de lo que pude encontrar es ya para quienes tienen algún conocimiento mas avanzado de Cobol...
Del programa tengo absolutamente todos los archivos a mi disposición.
Muchas Gracias.

A: al fin logré extraer los datos... Dejo acá los pasos para que quede registro por si alguien lo necesita...
En primer lugar, al ser archivos de una versión vieja de RM/Cobol (v2.1) tuve que actualizarlos a la nueva versión:

*

*Descargar una versión mas actual del programa (Yo descargué la v5.36 de aquí) (Es de 32 bit porque yo lo hice todo desde una máquina virtual).

*Abrir la consola de windows

*Colocarse en la ruta donde se encuentra el RM/Cobol y ejecutar runcobol rmifca

*Colocar la ruta y nombre del archivo .INX

*Colocar la ruta y nombre del archivo que contiene los datos (en mi caso sólo doy enter porque se llaman de la misma forma que el .INX pero sin extensión)

*Dar enter cuando pregunta BLOCK CONTAINS (los deja en 0)

*Dar enter cuando pregunta RECORD CONTAINS (lo deja en predet.)

*Colocar ruta y nombre para el nuevo archivo actualizado (Asegurarse que sea una ruta existente)

*Luego compilar el rmifcb ejecutando rmcobol rmifcb.cbl

*Una vez compilado ejecutarlo (runcobol rmifcb) y cuando lo solicite escribir y y luego enter

*El programa comenzará a trabajar, el proceso puede demorar algunos minutos dependiendo el tamaño del archivo. Presionar enter cuando finalice

*

*Acá les dejo un link al instructivo en inglés que incluye otras versiones.

Luego, una vez actualizado el archivo hay que utilizar una herramienta diseñada por JCantero llamada Mira (La pueden descargar de acá).

*

*Abrir la consola de windows

*Colocarse en la ruta donde se encuentra Mira y ejecutar

mira ruta_y_nombre_archivo_actualizado

*Una vez ejecutado, se inicia el proceso y al finalizar (nuevamente, demora depende el tamaño del archivo) se abre un archivo llamado "A" en un block de notas (ese archivo se encuentra en la carpeta de Mira)

Una vez realizado todo este proceso se debe importar al Excel. Yo lo hice con la versión 2013, dependiendo la versión puede diferir:

*

*Ir a la pestaña "DATOS", y luego en el apartado "Obtener datos externos" seleccionar "Desde texto".

*Seleccionar la opción "De ancho fijo" y las demás opciones según lo que necesite en cada situación y darle a "Siguiente"

*Seleccionar donde se delimitará cada columna (un click agrega, dos clicks borra y para mover se debe arrastrar), luego darle a "Siguiente"

*Establecer el formato deseado de cada columna y darle a "Finalizar"

*Seleccionar desde donde se ubicarán los datos dentro de la hoja

Espero que le sirva a alguien porque a mi me hizo renegar bastante todo esto...
Saludos


text:
Q: Discards qualifiers error For my compsci class, I am implementing a Stack template class, but have run into an odd error:

Stack.h: In member function 'const T Stack<T>::top() const [with T = int]':
Stack.cpp:10: error: passing 'const Stack<int>' as 'this' argument of 'void Stack<T>::checkElements() [with T = int]' discards qualifiers

Stack<T>::top() looks like this:
const T top() const {
    checkElements();
    return (const T)(first_->data);
}

Stack<T>::checkElements() looks like this:
void checkElements() {
    if (first_==NULL || size_==0)
        throw range_error("There are no elements in the stack.");
}

The stack uses linked nodes for storage, so first_ is a pointer to the first node.
Why am I getting this error?

A: You're calling a non-const method from a const method.

A: Your checkElements() function is not marked as const so you can't call it on const qualified objects.
top(), however is const qualified so in top(), this is a pointer to a const Stack (even if the Stack instance on which top() was called happens to be non-const), so you can't call checkElements() which always requires a non-const instance.

A: Because checkElements() isn't declared const.
void checkElements() const {
    if (first_==NULL || size_==0)
        throw range_error("There are no elements in the stack.");
}

Without that declaration, checkElements cannot be called on a const object.

A: You cannot call a non-const method from a const method. That would 'discard' the const qualifier.
Basically it means that if it allowed you to call the method, then it could change the object, and that would break the promise of not modifying the object that the const at the end of the method signature offers.


text:
Q: Delphi - How to get WrapText to behave like RichEdit.Lines.Text? I use TRichEdit to edit text. I have WordWrap turned on which automatically wraps text at the edge of control so that there are no scroll-bars. RichEdit width is set to fit 80 columns.
WordWrap simulates this behaviour nicely as long as you have occasional space between words. But if you have a very loooooooooooooooooong word RichEdit wrap will break it automatically and WordWrap won't!
If I want now to access these wrapped lines I can get it through RichEdit.Lines.Text which will put automatically CRLF at column 80. If I use RichEdit.Text I get raw text with no CRLF suitable for WordWrap.
The task is not trivial to do in a custom function as I already tried and it was not a small function but might there be a way to use wrapping functions of TRichEdit? I have an idea to create hidden RichEdit but that kind of seems stupid for this task as I would have to calculate its width just to do wordwrapping - rather pointless I think.
The question - is there a way to force WordWrap to cut long words that cannot be wrapped otherwise? So if a word is 170 characters long, it would be wrapped into 3 lines 80 + 80 + 10 but also taking care of words before to fill previous and following lines?

A: Try this on for size:
procedure TForm1.RichEdit1KeyPress(Sender: TObject; var Key: Char);
const
   MAX_LENGTH = 80;
var
  nLineCount:   integer;
  sCurrentLine: string;
begin
  for nLineCount := 0 to RichEdit1.Lines.Count - 1 do
  begin
    // no space in this line
    if (pos(' ',RichEdit1.Lines.Strings[nLineCount]) = 0) then
    begin
      if (length(RichEdit1.Lines.Strings[nLineCount]) > MAX_LENGTH) then
      begin
        // hold the whole line
        sCurrentLine := RichEdit1.Lines.Strings[nLineCount];
        // the current line, make the max value
        RichEdit1.Lines.Strings[nLineCount] := copy(sCurrentLine,1,MAX_LENGTH);
        // build the next line
        RichEdit1.Lines.Add(
        copy(sCurrentLine,MAX_LENGTH + 1,1));
      end;
    end;
  end;
end;


text:
Q: Why is the height of superscripts different in tikzpicture compared to maths environments? Consider this minimal example:

Why is the height of the superscript slightly lower in the tikzpicture and how can I get it to look like it does in the equation (or in this case flalign*) environment?
Code
\documentclass{article}
\usepackage{tikz}
\usepackage{mathtools}
\setlength\parindent{0cm}
\begin{document}

\begin{flalign*}
F_i^x &&
\end{flalign*}

\begin{tikzpicture}
\node [inner sep=0pt] at (0,0) {$F_i^x$};
\end{tikzpicture}

\end{document}

A: Because the first is typeset in display style and the second is in inline style maths. To get the same formatting in the TikZ picture as in the flalign* environment (or any other displayed maths environment), you can use \displaystyle:
\documentclass{article}
\usepackage{tikz}
\usepackage{mathtools}
\setlength\parindent{0cm}
\begin{document}

\begin{flalign*}
F_i^x &&
\end{flalign*}

\begin{tikzpicture}
\node [inner sep=0pt] at (0,0) {$\displaystyle F_i^x$};
\end{tikzpicture}

\end{document}


text:
Q: Running total over duplicate column values and no other columns I want to do running total but there is no unique column or id column to be used in over clause.
CREATE TABLE piv2([name] varchar(5), [no] int);

INSERT INTO piv2
    ([name], [no])
VALUES
    ('a', 1),
    ('a', 2),
    ('a', 3),
    ('a', 4),
    ('b', 1),
    ('b', 2),
    ('b', 3);

there are only 2 columns, name which has duplicate values and the no on which I want to do running total in SQL Server 2017 .
expected result:
a 1
a 3
a 6
a 10
b 11
b 13
b 16

Any help?

A: The following query would generate the output you expect, at least for the exact sample data you did show us:
SELECT
    name,
    SUM(no) OVER (ORDER BY name, no) AS no_sum
FROM piv2;

If the order you intend to use for the rolling sum is something other than the order given by the name and no columns, then you should reveal that logic along with sample data.


text:
Q: Unable to install emacs24 on Ubuntu 12.04 Precise I've added the cassou ppa, but when I try to install emacs24 or emacs-snapshot, apt-get can't seem to find the right packages:
$ sudo add-apt-repository ppa:cassou/emacs
...
$ sudo apt-get update
...
$ sudo apt-get install emacs24 emacs24-el emacs24-common-non-dfsg
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package emacs24
E: Unable to locate package emacs24-el
E: Unable to locate package emacs24-common-non-dfsg
$ sudo apt-get install emacs-snapshot
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package emacs-snapshot is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'emacs-snapshot' has no installation candidate


text:
Q: Custom xib inside another xib not being sized properly To get started, here is the hierarchy of my views:
- Table view
-- Table view cell (loaded from custom xib)
--- Collection view
---- Collection view cell (loaded from custom xib)
----- Custom view (loaded from custom xib)

What I'm having trouble with is that last view, the custom view, that I'm loading into the collection view cell as a custom xib. For some reason, it isn't being sized properly:

As you can see, the view has a giant white space above it, instead of filling out the cell properly. Funnily enough, if I scroll down the table view a bit, and then scroll back up, it displays at it should:

Here is part of my collection view code:
// I use this to size the collection view cells to be of 16:9 ratio, nothing crazy
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // Get the width of the screen
    let width = UIScreen.main.bounds.width

    let imageWidth = width
    let imageHeight = imageWidth / (16 / 9)

    self.postMediaHeight = imageHeight

    return CGSize(width: imageWidth, height: imageHeight)
}

// Here I initialize the cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PostMediaCollectionViewCell", for: indexPath as IndexPath) as? PostMediaCollectionViewCell else {
        fatalError("The dequeued cell is not an instance of PostMediaCollectionViewCell.")
    }

    let media = post.images[indexPath.row]

    cell.initialize()

    return cell
}

Here is my collection view cell class, PostMediaCollectionViewCell. Nothing out of the ordinary:
class PostMediaCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var container: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var moreViewLabel: UILabel!
    @IBOutlet weak var myCustomView: MyCustomView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func initialize() {
        //
    }
}

And lastly, here is my class for MyCustomView:
class MyCustomView: UIView {
    @IBOutlet var rootView: UIView!
    @IBOutlet weak var videoView: VideoView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }

    func initialize() {
        Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)
        addSubview(rootView)
        rootView.frame = self.bounds
        rootView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}

I've made sure that I have my constraints set right in my xibs, so auto layout should be working, but it's clearly not:
PostMediaCollectionViewCell xib:
https://i.stack.imgur.com/GQLpj.png
MyCustomView xib:
https://i.stack.imgur.com/jpSi0.png
So what am I doing wrong here?

A: Add a breakpoint on line         rootView.frame = self.bounds and check self.bounds values. If is the value different from the value after scrolling, you should change your awakeFromNib method.
lass PostMediaCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var container: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var moreView: UIView!
@IBOutlet weak var moreViewLabel: UILabel!
@IBOutlet weak var myCustomView: MyCustomView!

override func awakeFromNib() {
    super.awakeFromNib()

    self.myCustomView.frame = self.bounds
    self.myCustomView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

}

func initialize() {
    //
}

}

A: So I found a solution to this, but I don't know why it works and whether or not it's the best way of solving it, so I'm looking for input.
If I modify my PostMediaCollectionViewCell class to include layoutIfNeeded() in the initialization function, it works:
class PostMediaCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var container: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var moreView: UIView!
    @IBOutlet weak var moreViewLabel: UILabel!
    @IBOutlet weak var myCustomView: MyCustomView!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    func initialize() {
        layoutIfNeeded()
    }
}

But I don't understand why. Can someone explain?


text:
Q: Reload Bootstrap Modal on PHP variable not valid Having some problems with the error handling of a bootstrap modal. In the modal I have two inputs (both are required). I want to be able to display a simple "required" message if the form is submitted without one of the fields populated.
I tried doing this with PHP and it works in a page by itself, but when I put it in a modal the modal closes on submit and then if you re-open the modal you see the error messages. I really want the modal to stay open or re-open if the input fields are not valid when the user submits.
Any help would be appreciated! Thanks!
HTML (Start of the modal):

               <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add a vCenter

PHP (To graph the input and report any errors):
 if ( !empty($_POST)) {
    // keep track validation errors
    $vcenternameError = null;
    $vcenterownerError = null;

    // keep track post values
    $vcentername = $_POST['vcentername'];
    $vcenterowner = $_POST['vcenterowner'];

    // validate input
    $valid = true;
    if (empty($vcentername)) {
        $vcenternameError = 'Please enter vCenter Name';
        $valid = false;
    }

    if (empty($vcenterowner)) {
        $vcenterownerError = 'Please select vCenter Owner';
        $valid = false;
    }

    // insert data
    if ($valid) {

        $sql = "INSERT INTO ";
                    $stmt = sqlsrv_query( $conn, $sql );
                    if( $stmt === false) {
                        die( print_r( sqlsrv_errors(), true) );
                    }
        header("Location: index.php");
    }
}
?>

HTML (the rest of the modal):

    <form class="form-horizontal" action="index.php" method="post">
        <div class="<?php echo !empty($vcenternameError)?'error':'';?> form-group">

                Please input the FQDN of the vCenter and select an owner.

            vCenter Name

            <input name="vcentername" type="text" placeholder="vCenter Name" value="<?php echo !empty($vcentername)?$vcentername:'';?>" class="form-control">
                 <?php if (!empty($vcenternameError)): ?>

                 <?php echo $vcenternameError;?>

                        <?php endif; ?>

                <div class="<?php echo !empty($vcenterownerError)?'error':'';?> form-group">
                    vCenter Owner

                        <input type="radio" name="vcenterowner" value="Team1"> Team1

                        <input type="radio" name="vcenterowner" value="Team2"> Team2

                        <input type="radio" name="vcenterowner" value="Team3"> Team3

                        <?php if (!empty($vcenterownerError)): ?>

                                <?php echo $vcenterownerError;?>

                        <?php endif; ?>

                      <button type="submit" class="btn btn-success">Add</button>
                      Back

                       </form>

A: You can use jQuery to open the modal again if the modal contains errors when the page loads:
    var modal = $('#createModal');
    if(modal.find('div.alert-warning').length)
        modal.modal();

But for the best user experience, you should call your PHP script with an ajax request: http://api.jquery.com/jquery.ajax/


text:
Q: fullpage.js can't zoom in or out on mobile device i have a question,i use iphone surf my web,first page is difficult to zoom in and zoom out on mobile device
i find solution  responsiveWidth:1000, first page can be zoom out and zoom in by mobile,but vertical navigation dot will disppear
i don't know to solve it ,can you give my some way?
thank you

$(window).on( 'load', function () {
 $('#dowebok').fullpage({
  sectionsColor: ['#FFFFFF', '#4BBFC3', '#7BAABE', '#f90'],
         anchors: ['page1', 'page2', 'page3', 'page4', 'page5', 'page6'],

  navigation: true,
  scrollOverflow:true,
         css3:false,
         resize:true,
         slidesNavigation:true,//水平导航
                controlArrows: false,//隐藏水平箭头
         menu: '#mymenu',
         slidesNavPosition: 'bottom',
         responsiveWidth:900,
         //touchScrolling:false

 });

});

A: You'll only be able to zoom if you use autoScrolling:false or scrollBar:true.
The responsive option sets autoScrolling to false and that's why you are able to do it then.
In any case, it is NOT consider a real responsive website if you have to zoom. So whatever you are trying to do, it is not within the best practises.


text:
Q: What is the right way to create .env file on remote machine(like AWS instance)? I have a Django project where the settings file refers to a .env file(in root). The .env file contains all the sensitive data like Database password, Debug value. As a security measure, this .env file has been added to .gitignore and wouldn't be uploaded to GIT repository. Now, how do I add this file to the root of a remote host like AWS instance?

A: Instead of storing and exposing your sensitive data, you can consider using Secrets Manager to manage your secrets (this is a sample code in python - demonstrates how to retrieve a secret from AWS Secrets Manager).
You can also consider to use a Python library like this to deal with AWS Secrets Manager.

A: I'd recommend using AWS Secrets Manager for anything that is sensitive data and just using environment variables for anything else that is environment specific.


text:
Q: winform TableLayoutPanel have some rows, but only one of them is visiable In a winform project, there is  a TableLayoutPanel(TLP), but something is wrong: this TLP has some rows, but onle one row is visiable, it look likes that this TLP has only one row.
To make a comparison, I create a new TLP, and this one works fine: add N rows, it shows N rows.
I compare these two TLPs, verify their properties, all the same.
Here are the images(I don't have enough reputation to post images, so put my blog(Chinese) link here):
https://blog.csdn.net/zhouyingge1104/article/details/91491476
Has anyone ever encountered the sample problem?

A: I moved this TLP to another form, in that form, the bug disappeared, and then moved it back to the original form, it works fine. Seems like a bug of Visual Studio 2010 ?


text:
Q: Pandas: filter / query rows based by string input or list frame containing some information of stars, I would like to be able to filter to a new data-frame to only show the stars of interest list:
selected_stars = ["Polaris", "Deneb", "Pollux"]
df0 = df[df['Name']==selected_stars] # this works with int but doesn't work with list of strings.

df:
    No.      Hip-No.              Name
0    1           677         Alpheratz
1    2          2081             Ankaa
2    3          3179           Schedar
3    4          3419            Diphda
4    5          7588          Achernar
5    6          9884             Hamal
6    7         13847            Acamar
7    8         14135            Menkar
8    9         15863            Mirfak
9   10         21421         Aldebaran
10  11         24436             Rigel
11  12         24608           Capella
12  13         25336         Bellatrix
13  14         25428            Elnath
14  15         26311           Alnilam
15  16         27989        Betelgeuse
16  17         30438           Canopus
17  18         32349            Sirius
18  19         33579            Adhara
19  20         37279           Procyon
20  21         37826            Pollux
21  22         41037             Avior
22  23         44816            Suhail
23  24         45238       Miaplacidus
24  25         46390           Alphard
25  26         49669           Regulus
26  27         54061             Dubhe
27  28         57632          Denebola
28  29         59803            Gienah
29  30         60718             Acrux
30  31         61084            Gacrux
31  32         62956            Alioth
32  33         65474             Spica
33  34         67301            Alkaid
34  35         68702             Hadar
35  36         68933           Menkent
36  38   71681 71683   Rigil Kentaurus
37  37         69673          Arcturus
38  39         72622     Zubenelgenubi
39  40         72607            Kochab
40  41         76267          Alphecca
41  42         80763           Antares
42  43         82273             Atria
43  44         84012             Sabik
44  45         85927            Shaula
45  46         86032        Rasalhague
46  47         87833           Eltanin
47  48         90185    Kaus Australis
48  49         91262              Vega
49  50         92855             Nunki
50  51         97649            Altair
51  52        100751           Peacock
52  53        102098             Deneb
53  54        107315              Enif
54  55        109268  Al Na'ir (Alnair)
55  56        113368         Fomalhaut
56  57        113963            Markab
57   *         11767            Polaris

How can i get the selected_stars list as a new data-frame by multiple strings as filter input or a list that  contains multiple strings?


text:
Q: A question regarding the Layered Architecture Consider the following general form of a layered architecture :

I need to check my understanding about the second layer from top . More specifically I need to check my understanding the regarding the meaning of "User interface management " . According to my understanding , UI management is the code that underlies the UI , for example it is the code for each button and each UI elements . So for example , let us consider that the user needs to generate a report from a system that uses this layered pattern as its architecture. So what happens is the user press the generate report button then the underlying code of this button knows that it need to run the code of generate report system functionality ( which exists in the third layer). After that the generate report code ( lets assume that it is implemented as a class) will refer to the database to get the required info to generate this report and then the info will "propagates upward" until it reaches the UI again to be viewed by the user. So is this right ?  In other words , is this what is the meaning of the User interface management ? and do I understand the mechanism of this architecture ?

A:
UI management is the code that underlies the UI , for example it is the code for each button and each UI elements .

Not exactly. Your next statements are actually the true meaning:

So what happens is the user press the generate report button then the underlying code of this button knows that it need to run the code of generate report system functionality ( which exists in the third layer).

This statement is a good example of what the user management layer is — a use case. It isn't so much the code behind the button. This is an abstract concept for all of the code necessary to coordinate the classes that bridge the UI layer with the business layer. Code used to interact with the database would reside in a different layer, which would be represented by the bottom-most layer.
Essentially the flow of control goes from user interface to use case. From the use case it goes to the "business layer". Other architectures or design philosophies might can this the "domain layer". From the business layer you interact with the system support layer, where you connect to the database. Many times this would be done using an ORM (Object Relational Mapper).
I would say you have it mostly right. You are correct in assuming the user management layer is responsible for taking a concrete user interaction (clicking a button) and executing and coordinating a business process (running a report).


text:
Q: De-serialize byte array to JSON I have a WCF implemented with REST to get and return JSONs and I am trying to call its methods from a winform app.
I am checking on Fiddler to know whether I am being able to send the data or not and if I get a response.
Everything looks fine, I am sending a JSON to the web service and I am getting back a JSON..the problem is when I try to de-serialize it..
The returned JSON looks like :

So as you  can see I am getting data ** data returned**..I just dont know how to read it.
I am trying the following :
var serializer = new DataContractSerializer(typeof(wcfPicture), null, int.MaxValue, false, true, null, null);
    byte[] res1 = WC.UploadData(ServiceUrl + "newImage", "POST", MS.ToArray());
    var stream = new MemoryStream(res1);
    var deserializedObjectXml = serializer.ReadObject(stream);

This is throwing me : There was an error deserializing the object of type wcfPicture. The data at the root level is invalid. Line 1, position 1.
I am also trying :
    byte[] res1 = WC.UploadData(ServiceUrl + "newImage", "POST", MS.ToArray());
                    Stream res2 = new MemoryStream(res1);
                    JSrz = new DataContractJsonSerializer(typeof(wcfPicture));
wcfPicture pI2 = (wcfPicture)JSrz.ReadObject(res2);

But the problem is that pI2 values are the default values of each property type..the strings are equal to "" and the integers are equal to 0..so I dont know what is actually going on..
Any help?


text:
Q: Dummy not responding application I am currently determining how a production environment handles hung/not responding applications during Windows shutdown.
For testing that, it would be good to have a dummy application that does nothing but to hang / do not respond.

*

*My first intention was to open cmd and start a ping -t localhost, but that gets whisked away without any problem.

*Opening notepad and typing something without saving is not helping either, because Windows easily detects that it is actually waiting for a response from me.

*Writing a small Java program consisting of nothing but a while(true) { /* Nonsense */ } is only a partial solution because of it clogging the system so that none of the other applications respond in time.

A: I haven't really found a official Microsoft document that describes what that state indicates. Most often it's associated with a threaded application where one thread is blocking the interaction with the program itself.
Questions that touch on this are:

*

*How do I make a console application appear "Not Responding"?

*Program Not Responding
A simple example to recreate it (as one of the questions details it's probably very hard for a console application), is to create a Windows Forms application with a button and on the click of the button a really time consuming action is started (a simple while(true) or System.Threading.Thread.Sleep(999999) would do). At that point the GUI won't be able to respond anymore and the process will stop acting up on messages (from what I can tell).
If you check the task manager it should show up as "Not Responding". But it will still be different from other programs that get marked as "Not Responding" as, at least in my very limited testing, there was never a popup telling you that the process stopped to respond.


text:
Q: how to optimize multiple objective functions in genetic algorithm toolbox I have optimized single objective function in GA toolbox, but how do I optimize more than one objective functions?
For example I need to optimize the following set of objective functions:
f1 = x(1)^2 - 2*x(1)*x(2) + 6*x(1) + x(2)^2 - 6*x(2);
f2 = x(2) + x(3)*x(4);
f3 = x(4)^2 - x(5);

Note: above functions are some how linked to each other therefore variables are also interconnected

*

*How these functions to be represented either in .m file or some other way?

*I am worried whether these interlinked functions affect the variables, because I need only single optimized values of variables x1 to x5.

A: The image for the fitness function for the genetic algorithm has to be a totally ordered set. Usually when computing these things we are dealing with real numbers (or computer representations of those using floating point). The easiest way to get something like this to work is to compute each of f1, f2 and f3 then combine the results of these functions to make a new objective function. If you do that then you are only optimizing over the one objective function again, at least from the point of view of the programming side of things this should be useable via the same interface as before.. Perhaps the most difficult thing to do is to find the best way of combining the functions.


text:
Q: How to change a value in url - index to home - htaccess I have an index.html file and in my htaccess, I have removed the .html so that something like www.xxx.com/index#about would work.
I have a question inregards to wanting to change the url so instead of showing index, it shows home. I changed index.html to home.html but that messed things up as it was looking for index.
Is there a way to set it in htaccess so that index is replaced with home in url?