text:
Q: FragmentTabHost - No tab known for tag null Few days ago I implemented TabHostFramgent in a Fragment with a NavigationDrawer, and I faced with a problem that is the following error :

java.lang.IllegalStateException: No tab known for tag null

The thing is that all works perfectly since my first item list of my NavigationDrawer is my TabHostFragment, so it works perfect, but the problem is when I go in example to the second item and then I want to go back to the first item, every time that I try so it crashes.
I was searching everywhere, here in SO, code.google.com, etc... and I still don't get the proper answer.
My tab_host_test_2.xmllooks like :
  <android.support.v4.app.FragmentTabHost xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

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

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="0" />

        <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />
    </LinearLayout>

</android.support.v4.app.FragmentTabHost>

My activity_main.xml where I've got my NavigationDrawer looks like :
 <android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>

My TabHostFragment.java:
    public class TabHostFragment extends Fragment {

    public TabHostFragment(){

    }
    private FragmentTabHost mTabHost;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab_host_test2, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mTabHost = (FragmentTabHost)view.findViewById(android.R.id.tabhost);
        mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Tab1"),
                MisOfertasFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
                RecomendacionesFragment.class, null);

    }

}

My ActivityMain.java:
public class MainActivity extends FragmentActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    // saber si esta abierto
    public boolean mDrawerOpened;
    // nav drawer title
    private CharSequence mDrawerTitle;
    private FragmentTabHost mTabHost;
    // used to store app title
    private CharSequence mTitle;

    //para ponerlo visible
    public MenuItem mi;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

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

        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // Pages
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
        //AyudaSugerencias
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));

        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setBackgroundDrawable(new ColorDrawable(0xff1d97dd));
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(
                        Html.fromHtml(""
                                + mTitle + ""));

                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
                mDrawerOpened = false;
                syncState();

            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(
                        Html.fromHtml(""
                                + mDrawerTitle + ""));

                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
                mDrawerOpened = true;
                syncState();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Fragment fragment = null;
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            case R.id.ofertasRefresh:
                return true;
            case R.id.menu_search:
                return true;
            case R.id.newOffer:
                getFragmentManager().beginTransaction().replace(R.id.frame_container, new TipusNouProducte()).commit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        if (mDrawerOpened) {
            menu.removeItem(R.id.ofertasRefresh);
            menu.removeItem(R.id.menu_search);
            menu.removeItem(R.id.newOffer);
        }
        if (!mDrawerOpened) {
            menu.add(Menu.NONE, R.id.ofertasRefresh, Menu.NONE, mTitle);
        }
        return super.onPrepareOptionsMenu(menu);

    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     */
    private void displayView(int position) {
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
        Fragment fragment = null;

        switch (position) {
            case 0:
                fragment = new TabHostFragment();
                break;
            case 1:
                fragment = new RecomendacionesFragment();
                break;
            case 2:
                fragment = new LocalizacionFragment();
                break;
            case 3:
                fragment = new ListaProductosFragment();
                break;
            case 4:
                fragment = new ConfiguracionFragment();
                break;
            case 5:
                fragment = new AyudaSugerenciasFragment();
                break;
            case 6:
                fragment = new AyudaSugerencias();
                break;

            default:

                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit(); /// here says that replace android.app.Fragment in FragmentTransaction cannot be applied...

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);

    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

The full LogCat error is :
  03-04 16:53:05.708    2232-2232/info.androidhive.slidingmenu E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: info.androidhive.slidingmenu, PID: 2232
java.lang.IllegalStateException: No tab known for tag null
        at android.support.v4.app.FragmentTabHost.doTabChanged(FragmentTabHost.java:330)
        at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:280)
        at android.view.View.dispatchAttachedToWindow(View.java:13406)
        at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2707)
        at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2714)
        at android.view.ViewGroup.addViewInner(ViewGroup.java:3919)
        at android.view.ViewGroup.addView(ViewGroup.java:3733)
        at android.view.ViewGroup.addView(ViewGroup.java:3678)
        at android.view.ViewGroup.addView(ViewGroup.java:3654)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:958)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:454)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

EDIT
The answer of @Y.S., was kinda different about what I was asking for, but it could be a solution, but it didn't worked fine at all, and the NavigationDrawer is under the TabHostFragment, etc... I don't want to change anything of my layout.

A: There is another way to display tabs which can be used here.
Define TabHostFragment like this:
public class TabHostFragment extends Fragment implements ActionBar.TabListener{

    public TabHostFragment(){

    }

    AppSectionsPagerAdapter mAppSectionsPagerAdapter;
    ViewPager mViewPager;

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

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
        mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getChildFragmentManager());

        final ActionBar actionBar = ((FragmentActivity)getActivity()).getSupportActionBar();

        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mViewPager = (ViewPager) view.findViewById(R.id.pager);
        mViewPager.setAdapter(mAppSectionsPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
            actionBar.addTab(
                actionBar.newTab()
                        .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
        }
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {

        public AppSectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            Fragment f = null;
            switch (i) {
                case 0:
                    f = new MisOfertasFragment();
                    break;

                case 1:
                    f = new RecomendacionesFragment();
                    break;
            }

            return f;
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return getFragmentTitle(position);
        }

        private String getFragmentTitle(int position){
            if(position == 0)
                return "Tab 1";
            else if(position == 1)
                return "Tab 2";
            else
                return "";
        }
    }
}

Define tab_host_test2.xml like this:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Rest of the code remains the same.
Try this. This should work.
EDIT:
Add this to the displayView() method:
if(position != 0)
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

A: specify in .xml file where you are using this TabHostFragment(complete path like com.my.TabHostFragment). like
 <com.my.TabHostFragment
        android:id="@+id/fragmentId"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
         />


text:
Q: Ubuntu 18.04 won't change volume I have just installed Ubuntu 18.04 on my Asus UX490 and now I cannot change the volume but I can mute/unmute.
I can move the volume bar right/left but volume does not change. However, when I move it to left most side or just click the sound icon, computer mutes/unmutes correctly.
Also when I try to change the volume with fn+f11/f12 I see the volume level thingy changing in the middle of the screen but sound does not change as well. However, again, I can mute/unmute with fn+f10.
Similar things happen when I try from Setting > Sound. Under this menu in the "Choose a device for sound output:" list I only see "Speakers - Built-in Audio".
Another thing, if I change the sound in a player (let's say youtube) sound changes.
I tried these two but they did not help.

*

*Volume control not working

*Can't change volume in Ubuntu 14.04
PS: Just to make it clear, this is the first time I installed any Ubuntu version on this laptop. I mean, I do not say "it was working and got broken after I installed 18.04"

A: try the solution from this question?
Volume control not working

I think I may have solved the issue. Upon examining /etc/modprobe.d/alsa-base.conf, I noticed that it no longer had the
  following line.
options snd-hda-intel model=auto
I re-added this line, saved, rebooted, and everything seems to be
  working now.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular Ionic POST 405 (Method Not Allowed), using Chrome I managed to send a $http.post to skyscannerAPI: http://partners.api.skyscanner.net/apiservices/pricing/v1.0
However, I get the POST http://partners.api.skyscanner.net/apiservices/pricing/v1.0 405 (Method Not Allowed), I searched through Info someone said it is perhaps due to I'm using Chrome, So I installed the extension Allow-Control-Allow-Origin, but it is still showing the error.
The complete error message showing that like this:
POST http://partners.api.skyscanner.net/apiservices/pricing/v1.0 405 (Method Not Allowed)
    (anonymous) @ ionic.bundle.js:25005
    sendReq @ ionic.bundle.js:24798
    serverRequest @ ionic.bundle.js:24508
    processQueue @ ionic.bundle.js:29132
    (anonymous) @ ionic.bundle.js:29148
    $eval @ ionic.bundle.js:30400
    $digest @ ionic.bundle.js:30216
    $apply @ ionic.bundle.js:30508
    (anonymous) @ ionic.bundle.js:65428
    defaultHandlerWrapper @ ionic.bundle.js:16792
    eventHandler @ ionic.bundle.js:16780
    triggerMouseEvent @ ionic.bundle.js:2953
    tapClick @ ionic.bundle.js:2942
    tapTouchEnd @ ionic.bundle.js:3069

The (anonymous) @ ionic.bundle.js:25005 is following code:
xhr.send(isUndefined(post) ? null : post);

My code is as following:
//service.js
.service('skyscanner',function($http){
      var baseUrl= "http://partners.api.skyscanner.net/apiservices/pricing/v1.0";
      var bodyInfo= {
            body: {
              apikey: My_API_KEY,
              Country: "CA",
              Currency: "CAD",
              //more data......
            }
          };
      this.getKey= function(){
        var require_sessionkey= $http({
          method:"POST",
          url:baseUrl,
          data: bodyInfo,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept' :'application/json'
          }
        })
        .success(function successCallback() {
          var polling={};
          var session_key = require_sessionkey.headers["location"];
          (function(){
            polling=$http.get(session_key, {query: {apikey: My_API_KEY}});
          })();
          return polling;
        }).error(function errorCallback() {
          console.log("something gets wrong: "+ require_sessionkey);
        });
      };
    })

//controller.js
.controller('FlightSearchCtrl',function($scope,skyscanner,FlightInfos){
          $scope.list = [];
          $scope.text = 'hello';
          $scope.skyscannerPost= function(){
            var polling=skyscanner.getKey();
            $scope.polling=polling;
          };
        })

A: After a couple of hours research, I found the answer.
I need to serialize my data because the Content-Type: 'application/x-www-form-urlencoded', which means that the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be(reference https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data):
MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

if the data is not serialized, it looks like:
 console.log(bodyInfo);
//=> Object {apikey: "ds436195492025844505223424234232173", country: "CA", currency: "CAD", locale: "zh_Hans_CN", adults: 1…}

After it is serialized:
    console.log(bodyInfoSerialied);
  //=>apikey=ds436195492025844505223424234232173&country=CA&currency=CAD&locale=zh_Hans_CN&adults=1&children=0&infants=0&originPlace=YVR&destinationPlace=SHA&outboundDate=2017-01-19&inboundDate=2017-01-23&locationSchema=Iata&cabinClass=Economy

Thanks to the answer
I post the edited code below:
    .service('skyscanner',function($http){
      var baseUrl= "http://partners.api.skyscanner.net/apiservices/pricing/v1.0";
      var bodyInfo= {
              'apikey': 'ds43619549203213123211202173',
              "country": "CA",
              "currency": "CAD",
              "locale": "zh_Hans_CN",
              //...
          };
//new added serialize().
      serialize = function(obj, prefix) {
        var str = [], p;
        for(p in obj) {
          if (obj.hasOwnProperty(p)) {
            var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
            str.push((v !== null && typeof v === "object") ?
              serialize(v, k) :
              encodeURIComponent(k) + "=" + encodeURIComponent(v));
          }
        }
        return str.join("&");
      }
//serialize the body.
      var bodyInfoSerialied = serialize(bodyInfo);
      console.log(bodyInfo);
      console.log(bodyInfoSerialied);
      this.getKey= function(){
        var require_sessionkey= $http({
          method:"POST",
          url:baseUrl,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept' :'application/json'
          },
          data:bodyInfoSerialied
        })
        .success(function successCallback(require_sessionkey) {
          console.log(require_sessionkey);
          var polling={};
          var session_key = require_sessionkey.headers["Location"];
          (function(){
            polling=$http.get(session_key, {query: {apikey: 'ds43619549203213123211202173'}});
          })();
          return polling;
        }).error(function errorCallback(require_sessionkey) {
          console.log("something gets wrong: "+ require_sessionkey);
          console.log("bodyInfoSerialied: "+ bodyInfoSerialied);
        });
      };
    })

Notice the code still gets something wrong, but the 405 error is solved at least.


text:
Q: Forecasting a year ahead using annual vs daily data Suppose, as an example, that you would like to forecast a share price in a year's time based on the past 20 years of data. You can either use annual data and forecast 1 period ahead, or use daily data and forecast 365 days ahead. Clearly, there are far fewer data points in the annual dataset than in the daily dataset.
I am finding that there is much greater uncertainty/variability in the forecast based on the daily data than in the forecast based on the annual data (wider prediction intervals for the former). I was wondering if this is to be expected in general or if it is problem/model specific.


text:
Q: How do i send this form and store the JSON as a var i want to send this form to the API after the user inputs the authorization code. I know i need to intercept the submit with JS or send the form as an AJAX post. I've included my attempts to do this but i can't get them to work. A response looks like this:
{"access_token":"mfi2s6i41i8hannfkaa3l87rbt","token_type":"bearer","expires_in":57600}

I want to save the respons as 3 seperate var's but for most the access_token
html:

  <body>
    <!--   form for authentication   -->
    <form id="auth-form" action="https://rsgdeborgen.zportal.nl/api/v3/oauth/token" method="post">
    <!--   hidden post data      -->
    <input id="hidden-input" type="hidden" name="grant_type" value="authorization_code"/>
    <!--    user inputfield || user input = 12 number long authorization code from: https://rsgdeborgen.zportal.nl -->
    <input id="user-auth-input" name="code" type="text" placeholder="Koppelcode" minlength=12 maxlength=15 required autofocus/>
    <!--    post button    -->
    <button id="post-button" value="inloggen" onclick="change()">inloggen</button>
  </form>
  <div id="display">

  </div>
  <!--   link to javascript   -->
  <script type="text/javascript" src="index.js"></script>
</body>

Attempt for AJAX

function sendData(callback)
{
    var xhttp = new XMLHttpRequest();
    var url = 'https://rsgdeborgen.zportal.nl/api/v3/oauth/token';
    var params = 'code=' + document.getElementById('user-auth-input').value;
    xhttp.open('POST', url, true);

    xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    xhttp.onreadystatechange = function ()
    {
        if (xhttp.readyState == 4 && xhttp.status == 200)
        {
            var response = xhttp.responseText, js;
            try
            {
              js = JSON.parse(response);
              if(typeof callback === 'function') callback(js);
            }
            catch (e)
            {
              if(typeof callback === 'function') callback(null);
            }
        }
    }
    xhttp.send(params);
}

function useToken(obj)
{
  if(obj) console.log("Token = " + obj.access_token);
}

sendData(useToken);

link to codepen

A: Server responds with code 500, because the grant_type is missing.


text:
Q: how to test xqueries manually where elements >200? currently i am working on one of the service where consumer can send 250 elements in request and i need to do the mapping for all inbound elements using xquery transformation.
Can someone let me know if there is any optimal way or any tool  to test the mapping of 250 elements in one go ?
thanks in advance.

A: This is what I use.
https://github.com/TrentBartlem/osbutils/tree/master/XQTestFramework
I put the jar into my maven repo (along with various OSB/weblogic jars), then write JUnit test cases. Doesn't even need an OSB server running.


text:
Q: My Magento page shows content above the header I have added a new template file between cart page and checkout.The issue I am facing is that the content of the file is shown above the header please help me to solve this issue
public function linkAction()
{
$this->loadLayout();
$this->renderLayout();
echo $this->getLayout()->createBlock('core/template')->setTemplate('vatexempt/checkout/onepage/vatexempt.phtml')->toHtml();
}

This is how I call the template file in my controller.
Following is the code in my xmo file
<vatexempt_index_link> <!-- frontendname_controllername_actionname -->
    <reference name="content">
       <block type="core/template" name="vatexempt" template="vatexempt/checkout/onepage/vatexempt.phtml" />
    </reference>
</vatexempt_index_link>

Please Help me I am using magento 1.8 default theme

A: You can make this change in layout.xml
<vatexempt_link_link translate="label">
    <label>link</label>
    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
    <reference name="content">
           <block type="core/template" name="vatexempt" template="vatexempt/vatexempt.phtml" />
    </reference>
    </vatexempt_link_link>

and set controller function as
public function linkAction()
{
$this->loadLayout();
$this->renderLayout();
}

This should work.

A: The reason that there is output before the header is because you use:
echo $this->getLayout()->createBlock('core/template')->setTemplate('vatexempt/checkout/onepage/vatexempt.phtml')->toHtml();

You should change this to the following so that the content is added to the content section of your page:
$this->loadLayout()
            ->_addContent(
                $this->getLayout()
                    ->createBlock('core/template')->setTemplate('vatexempt/checkout/onepage/vatexempt.phtml')->toHtml()
            )
            ->renderLayout();


text:
Q: unable to compare screen values with sql table value I am trying to compare the screen values input against the value stored in DB. Currently i am trying this code:
cell = sheet.getRow(i).getCell(2);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com:3306/madisondb","madisonadmin","t4xuw94$");// + "databasename=madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com";
Statement st = con.createStatement();
ResultSet Rs = st.executeQuery("select name, zipcode, state, city, street from business_master where user_id =(\r\n" +
    "select id\r\n" +
    "from user_master\r\n" +
    "where email = 'cell.getStringCellValue()') \r\n");

while (Rs.next()) {
    //  System.out.println(Rs.getString(1) + "  " + Rs.getString(2) + "  " + Rs.getString(3) + "  "
    //  + Rs.getString(4) + "  " + Rs.getString(5));
    System.out.println(Rs.getString(0));
}

The screen is not showing any values.. and when i am trying to print System.out.println(Rs.getString(3)) outside of the loop it gives me an error

java.sql.SQLException: Illegal operation on empty result set.

A: You are trying to find all the rows where the email address is literally the text 'cell.getStringCellValue()' rather than the value returned by that method.
Whilst you code assemble your query string, that lays you open to SQL injection attacks. Use a prepared statement instead
PreparedStatement st = con.prepareStatement(
    "select name, zipcode, state, city, street from business_master where user_id =(" +
    "select id " +
    "from user_master " +
    "where email = ?)");
st.setString(1, cell.getStringCellValue());
ResultSet Rs = st.executeQuery();


text:
Q: Website taking forever to load I have installed mybb in /forum and wordpress in /blog
Frequently, my wordpress blog doest not load (feels like the web server doesn't respond)
and at the same time, mybb also does not load
note: this happens very frequently but is fixed automatically after sometime
I have tried using Chrome and opera
----Chrome sometimes just keeps loading and sometime give "no data recieved"
----Opera simply keeps loading, loading and loading
First i thought this happens only with me but when i asked my friend to open my site, it happened with him too

A: If the server doesn't get hit very often,  you may find that your web server is effectively turning itself off due to inactivity.
So when you visit it after a "long" period of inactivity, it takes a while while it load the application, rebuilds the cache etc.. ie the same as restarting the web application.
You can be sure this is not the problem, if you experience the "not responding" behaviour while you are actively browsing the site.

A: If you are aggregating contents then wordpress is not your choice. However I found cache plugins like quickcache can solve your problem.


text:
Q: Concatenation result from MySQL query, using group and multiple tables I have some problem with MySQL query.
I have 5 tables (keys in brackets):
trips (tripId)
trips_moments (tripId, momentId)
moments (momentId)
moments_images (momentIs, imageId)
images (imageId)

In my situation I have 1 trip, which contains 2 moments, every moment contains 5 images.
I'd like in result to get in field "moments":
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;6;F50MTTZK;jpg;6R2XJB9X|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;19;66B7VQ84;jpg;ILQYDQUC

instead of:
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;6;F50MTTZK;jpg;6R2XJB9X|
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;7;9PY1BZD1;jpg;TP7U07ST|
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;8;VPGPFMMS;jpg;VF95BNNQ|
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;9;EC7NL3HC;jpg;PD1CEQE6|
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;10;8J1OT7IT;jpg;ZL8WAWCJ|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;19;66B7VQ84;jpg;ILQYDQUC|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;20;HZIPGJY7;jpg;FOOWJ8BV|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;21;9JOXXPJQ;jpg;ZIVJ5V7K|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;22;IS1JPW1N;jpg;31M4XVBM|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;23;OTOWNDZA;jpg;C03UFMBK

You can see in my result that record with 166 and 167 is repeated as many times as much images moment contains.
My current query:
 SELECT
`t`.`tripId`,
`t`.`title`,
`t`.`when`,
GROUP_CONCAT(
  DISTINCT(
    CONCAT(
       m.momentId, ';', m.title, ';', m.created, ';', i.imageId, ';', i.fileNameBase, ';', i.fileNameExtension, ';', i.directory)
    )
  SEPARATOR '|'
) AS `moments`
FROM `trips` AS `t`
LEFT JOIN `trips_moments` AS `tm` ON t.tripId = tm.tripId
LEFT JOIN `moments` AS `m` ON tm.momentId = m.momentId
LEFT JOIN `moments_images` AS `mi` ON m.momentId = mi.momentId
LEFT JOIN `images` AS `i` ON mi.imageId = i.imageId
WHERE (t.userId = '1')
GROUP BY `t`.`tripId`
ORDER BY `t`.`tripId` ASC

Current table structures:
CREATE TABLE IF NOT EXISTS `images` (
  `imageId` int(11) NOT NULL AUTO_INCREMENT,
  `userId` int(11) NOT NULL,
  `title` varchar(128) NOT NULL,
  `description` text NOT NULL,
  `fileNameBase` varchar(64) NOT NULL,
  `fileNameExtension` varchar(4) NOT NULL,
  `directory` varchar(64) NOT NULL,
  `source` varchar(32) NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`imageId`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `moments` (
  `momentId` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(128) NOT NULL,
  `userId` int(11) NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`momentId`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `moments_images` (
  `momentId` int(11) NOT NULL,
  `imageId` int(11) NOT NULL,
  PRIMARY KEY (`momentId`,`imageId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `trips` (
  `tripId` int(11) NOT NULL AUTO_INCREMENT,
  `userId` int(11) NOT NULL,
  `title` varchar(128) NOT NULL,
  `when` date NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`tripId`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

CREATE TABLE IF NOT EXISTS `trips_moments` (
  `tripId` int(11) NOT NULL,
  `momentId` int(11) NOT NULL,
  PRIMARY KEY (`tripId`,`momentId`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

A: I can't test right now, but this can give you an idea, I changes moemnt_images join like this:
LEFT JOIN `moments_images` AS `mi` ON m.momentId = mi.momentId
AND imageId = (select min(imageId) from moments_images where momentId=m.momentId)

full query:
SELECT
`t`.`tripId`,
`t`.`title`,
`t`.`when`,
GROUP_CONCAT(
  DISTINCT(
    CONCAT(
       m.momentId, ';', m.title, ';', m.created, ';', i.imageId, ';', i.fileNameBase, ';', i.fileNameExtension, ';', i.directory)
    )
  SEPARATOR '|'
) AS `moments`
FROM `trips` AS `t`
LEFT JOIN `trips_moments` AS `tm` ON t.tripId = tm.tripId
LEFT JOIN `moments` AS `m` ON tm.momentId = m.momentId
LEFT JOIN `moments_images` AS `mi` ON m.momentId = mi.momentId  and imageId = (select min(imageId) from moments_images where momentId=m.momentId)
LEFT JOIN `images` AS `i` ON mi.imageId = i.imageId
WHERE (t.userId = '1')
GROUP BY `t`.`tripId`
ORDER BY `t`.`tripId` ASC

A: @Kaii
I used this grouping by two columns, but results are not as expected:
In result I get two records with these values in field "moments":
1st record)
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;9;EC7NL3HC;jpg;PD1CEQE6|
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;6;F50MTTZK;jpg;6R2XJB9X|
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;8;VPGPFMMS;jpg;VF95BNNQ|
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;10;8J1OT7IT;jpg;ZL8WAWCJ|
166;Kościuszko mound in Cracow;2012-11-08 15:38:14;7;9PY1BZD1;jpg;TP7U07ST

2nd record)
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;20;HZIPGJY7;jpg;FOOWJ8BV|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;22;IS1JPW1N;jpg;31M4XVBM|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;19;66B7VQ84;jpg;ILQYDQUC|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;21;9JOXXPJQ;jpg;ZIVJ5V7K|
167;Pope John Paul II (Jan Paweł 2) home town - Wadowice;2012-11-08 15:57:15;23;OTOWNDZA;jpg;C03UFMBK

I'd like to get one result as in my question, of course if possible.


text:
Q: OpenCV cv::waitKey does not work Here is the sample code.
   cv::VideoCapture capturedVideo;
   capturedVideo.open(videoFile);
   if (!capturedVideo.isOpened())
   {
      std::cerr << "Unable to open video: " << videoFile << std::endl;
      return -1;
   }

   cv::Mat dispFrame;
   cv::namedWindow("Video Edit", cv::WINDOW_AUTOSIZE);

   while (true)
   {
      capturedVideo >> dispFrame;
      if (!dispFrame.empty())
         imshow("Video Edit", dispFrame);
      if (cv::waitKey(30) >= 0) // wait for key press event
      {
         puts("Key press");
         break;
      }
   }

However the code never flows to "Key press". I have printed the return value of cv::waitKey which supposed to be the ascii code of a pressed key. It is always correct. What is happening here?


text:
Q: Looping through columns with dplyr chain I have a data frame arranged as follows:
df <- structure(list(name1 =  c("A","A","B","B","A","A","B","B"),
                 name2     =  c("B","B","C","C","ALL","ALL","ALL","ALL"),
                 pair_id   =  c(1,1,2,2,3,3,4,4),
                 year      =  c(2010, 2011, 2010, 2011, 2010, 2011,2010, 2011),
                 var1      =  c(1.5,2,4,5,12,15,20,18),
                 var2      =  c(8,10,24,5.5,35,28,27,26),
                 var3      =  c(25,6,12,18.5,30,41,33,38)),
            .Names         =  c("name1","name2","pair_id","year", "var1", "var2", "var3"),
            row.names      =  c("1", "2", "3", "4", "5", "6", "7", "8"), class =("data.frame"))

For convenience I show 3 variables (var1,var2,var3) only. I would like to compute the percentage share of total (ALL) for all the variables I have (e.g. var1, var2, var3) by year and pair_id. The desired output should be
df <- structure(list(name1       =  c("A","A","B","B","A","A","B","B"),
                 name2           =  c("B","B","C","C","ALL","ALL","ALL","ALL"),
                 pair_id         =  c(1,1,2,2,3,3,4,4),
                 year            =  c(2010, 2011, 2010, 2011, 2010, 2011,2010, 2011),
                 var1            =  c(1.5,2,4,5,12,15,20,18),
                 var2            =  c(8,10,24,5.5,15,18,7,22),
                 var3            =  c(25,6,12,18.5,29,11,12,30),
                 var1_share      =  c(0.125, 0.133333333, 0.2, 0.277777778, 1, 1, 1, 1),
                 var2_share      =  c(0.228571429, 0.357142857, 0.888888889, 0.211538462, 1, 1, 1, 1),
                 var3_share      =  c(0.833333333, 0.146341463, 0.363636364, 0.486842105, 1, 1, 1, 1)),
            .Names               =  c("name1","name2","pair_id","year", "var1", "var2", "var3", "var1_share", "var2_share", "var3_share"),
            row.names            =  c("1", "2", "3", "4", "5", "6", "7", "8"), class =("data.frame"))

Here is my attempt. The syntax is obsviously wrong.
varlist <- c("var1","var2","var3")
for (var in varlist) {
    df <- df %>%
    group_by(name1, year) %>%
    mutate(denom = var[name2 == "ALL"]) %>%
    group_by(pair_id, add = TRUE) %>%
    mutate(var_share = (var/denom)*100)
    }

Your inputs would be appreciated.

A: With dplyr and tidyr:
library(dplyr)
library(tidyr)

df %>%
  gather(var,val, var1, var2, var3) %>%
  inner_join(.,filter(., name2=="ALL"), c("name1", "year", "var")) %>%
  mutate(var_share_val = val.x / val.y,
         var_share_var = paste0(var, "_share"),
         name2 = name2.x, name2.x = NULL,
         pair_id = pair_id.x, pair_id.x = NULL,
         pair_id.y = NULL,name2.y = NULL, val.y = NULL) %>%
  spread(var, val.x) %>%
  spread(var_share_var, var_share_val) %>%
  group_by(name1, name2, year) %>%
  summarize_all(.funs=funs(max(., na.rm=TRUE)))

  name1 name2  year pair_id  var1  var2  var3 var1_share var2_share var3_share
  <chr> <chr> <dbl>   <dbl> <dbl> <dbl> <dbl>      <dbl>      <dbl>      <dbl>
1     A   ALL  2010       3  12.0  35.0  30.0  1.0000000  1.0000000  1.0000000
2     A   ALL  2011       3  15.0  28.0  41.0  1.0000000  1.0000000  1.0000000
3     A     B  2010       1   1.5   8.0  25.0  0.1250000  0.2285714  0.8333333
4     A     B  2011       1   2.0  10.0   6.0  0.1333333  0.3571429  0.1463415
5     B   ALL  2010       4  20.0  27.0  33.0  1.0000000  1.0000000  1.0000000
6     B   ALL  2011       4  18.0  26.0  38.0  1.0000000  1.0000000  1.0000000
7     B     C  2010       2   4.0  24.0  12.0  0.2000000  0.8888889  0.3636364
8     B     C  2011       2   5.0   5.5  18.5  0.2777778  0.2115385  0.4868421


text:
Q: Left join and case clause LINQ in Entity Framework I am needing to make a left join and also use the select operator case.
My LINQ basic is this and works:
resultado.Dados =
    (
        from a in db.AgendaHorario
        join b in db.Agenda on a.AgendaID equals b.AgendaID
        join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
        from e in d.DefaultIfEmpty()
        select new
        {
            id = a.AgendaHorarioID,
            Medico = e.Identificacao
        });

But I must add a new field and it should be formatted, then my LINQ looked like this:
resultado.Dados =
  (
    from a in db.AgendaHorario
    join b in db.Agenda on a.AgendaID equals b.AgendaID
    join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
    from e in d.DefaultIfEmpty()
    select new
    {
        id = a.AgendaHorarioID,
        Medico = e.Identificacao,
        start = a.Horario.ToString("yyyy-MM-dd HH:mm:ss")
    }
  );

This error happens:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

If you add the ToList() or AsEnumerable() in db.AgendaHorario.ToList() and db.Agenda.ToList() and db.Profissional.ToList() error that appears is:
Object reference not set to an instance of an object.

What should I do to have a left join with case and fields and formatted fields

A: try to set the string in a variable then assign it to your query like this:

var myValue = Horario.ToString("yyyy-MM-dd HH:mm:ss");

resultado.Dados =   (
from a in db.AgendaHorario
join b in db.Agenda on a.AgendaID equals b.AgendaID
join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
from e in d.DefaultIfEmpty()
select new
{
    id = a.AgendaHorarioID,
    Medico = e.Identificacao,
    start = myValue
}   );

A: Try this:
resultado.Dados =
(
    from a in db.AgendaHorario
    join b in db.Agenda on a.AgendaID equals b.AgendaID
    join c in db.Profissional on a.ProfissionalID equals c.ProfissionalID into d
    from e in d.DefaultIfEmpty()
    select new
    {
        id = a.AgendaHorarioID,
        Medico = e.Identificacao,
        start = a.Horario
    }).AsEnumerable().Select(x => new
    {
        id = x.id,
        Medico = x.Medico,
        start = x.start.ToString("yyyy-MM-dd HH:mm:ss")
    }
);


text:
Q: Función para convertir una lista en un string que repita los caracteres según el valor original Tengo una lista:
list =  [1,2,3,4,5]

Busco una función eficiente para obtener como output un string de caracteres numéricos en que cada caracter aparezca repetido tantas veces como su valor original en la lista. Es decir:
string = "122333444455555"

El primer paso que he dado ha sido convertir la lista en string:
l = "".join(str(x) for x in list)

A: Siguiendo con tu idea simplemente multiplica cada elemeto por si mismo dentro del generador:
l = [1, 2 ,3 , 4, 5]
l = "".join(str(x)*x for x in l)
print(l)

Salida:

'122333444455555'

Nota: nunca llames a tu variable list, es una palabra reservada en Python y con eso la sobreescribes. Usa list_ o cualquier otra cosa.


text:
Q: Issue with LAN in Windows 10 I am using a Windows 10 x64 based Acer Laptop.
When I start work in morning, I connect the LAN to my LAP and for 1 month, there were no issues
But recently, when I connect the LAN, the Tray Icon shows No Internet Access,
When I troubleshoot it, the troubleshooter solve it and shows this was the error Doesn't have a valid IP Config.
Anyway, the issue is solved after troubleshooting.
Why this happens everyday, Since I am using the same Lan Connection and cable everyday.
How to fix it permanently(doesn't require a troubleshoot daily)

A: You can try repairing Winsock & DNS Cache to clear the stored DNS cache in Windows. Sometimes when IP address settings become corrupt you will not be able to get internet connection.
Resetting IP settings will fix that problem additionally it also
flushes and rebuilds the DNS and resets winsock entries TCP/IP stack.
You can try these commands in command prompt as admin
netsh winsock reset all
netsh int 6to4 reset all
netsh int ipv4 reset all
netsh int ipv6 reset all
netsh int httpstunnel reset all
netsh int isatap reset all
netsh int portproxy reset all
netsh int tcp reset all
netsh int teredo reset all


text:
Q: XAML StackPanel cropping items on other page I'm building a C# XAML Universal app in VS, with some simple navigation between pages. Until a few days ago, the navigation was all working fine, with you being able to click a button on the main page and it take you to the second page, then you being able to click a back button on that second page and it return you back to the start. Now, the other pages (Not the main page) are cropping all their items individually, so that small items even disappear. The back button, which is just a small 200x200px image, is not displaying, and on the 'Timer' page, the timer text is cropped down a lot. Here is a screenshot of the timer page in the editor, then in the debug program.

Below will be the source.
How can I get this to stop cropping? What am I doing wrong?
Here is a download of the whole lot: https://mega.nz/#!2gskULpZ!ExddgKx083jCTXzCetpgtE4li_rTcupsvCWLOZvK2Kg
Thanks!
timer.xaml:
    <Page
    x:Class="CubingHelper.Timer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:CubingHelper"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid x:Name="TimerBG">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="23*"/>
            <ColumnDefinition Width="1898*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="728*"/>
            <RowDefinition Height="353*"/>
        </Grid.RowDefinitions>
        <Grid.Background>
            <SolidColorBrush Color="{StaticResource BGCol}"/>
        </Grid.Background>

        <TextBlock x:Name="TimerText" Text="0.00" Margin="494,151,639,184" FontFamily="extravaganzza" FontSize="340" RenderTransformOrigin="0.696,0.733" Grid.Column="1" >
            <TextBlock.Foreground>
                <SolidColorBrush Color="{StaticResource ForeGroundText}"/>
            </TextBlock.Foreground>
        </TextBlock>

        <Button Height="724" Width="296" Click="BackButton_Click" Margin="0,0,0,3" Background="#33000000" Grid.ColumnSpan="2">
            <Button.Template>
                <ControlTemplate>
                    <Image x:Name="BackImg" HorizontalAlignment="Left" Height="100" Margin="10,10,0,0" VerticalAlignment="Top" Width="100" RenderTransformOrigin="-2.5,-1.59" Source="Assets/BackButton.png" />
                </ControlTemplate>
            </Button.Template>
        </Button>
    </Grid>
</Page>

Timer.xaml.cs:
    using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Core;
using Windows.System;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace CubingHelper
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class Timer : Page
    {
        public Timer()
        {
            this.InitializeComponent();
        }

        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(MainPage));
        }

        private void KeysDown(object sender, KeyEventArgs e)
        {
            if (e.VirtualKey == VirtualKey.Space)
            {
                TimerText.FontSize = 200;
            }
        }
    }
}

and MainPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace CubingHelper
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
            appView.Title = "Home";
        }

        private void PLL_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(PLL));
            var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
            appView.Title = "PLL";
        }

        private void OLL_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(OLL));
            var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
            appView.Title = "OLL";
        }

        private void Timer_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(Timer));
            var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
            appView.Title = "Timer";
        }
    }
}

A: You have messed up the xaml layouts totally. Dont know what exactly you are trying  achieve. To get the layout similar to your first screenshot i changed margin from your textblock from (Margin="494,151,639,184") to (Margin="494,151,0,0") and setting button's grid position as
Grid.Column="1"
Grid.RowSpan="2"


text:
Q: The first 'primordial' basis of a finite vector space Let's take a vector space $V $ and set $V= \mathbb{R}^3 $ for ease of mind.
Usually we equip $V $ with the standard basis $\{e_1,e_2,e_3\} $ and we express all our vectors in that basis:
$$v = (a,b,c) = ae_1 + be_2 + ce_3 $$
Now, we might choose a different basis $\{f_1,f_2,f_3\} $, for example:
\begin{align*}
 f_1 = (1,0,0) \\
 f_2 = (1,1,0) \\
 f_3 = (1,1,1)
\end{align*}
but here I did what seems to me a sinister trick. I gave you the new basis vectors in terms of the old one! I have $f_3 $ as $e_1 + e_2 + e_3 $.
The same thing happens for polynomial spaces, given $\{1,x,x^2 \} $ as a basis, I might want to choose $(1,x+1,1+x+\frac{1}{2}x^2) $ as a different basis, and that's also expressed in terms of the old basis.
Now my mean old uncle Bob comes along and tells me that he has a new basis:
\begin{align*}
 g_1 = (1,0,0) \\
 g_2 = (0,1,0) \\
 g_3 = (0,0,1)
\end{align*}
but what he doesn't tell me is that he's using $f_i $ as the basis to express his new basis, so that $g_i = f_i $ for all $i $! And remember, the $f_i $'s are really combinations of $e_i $'s.
It seems to me, then, that when people tell me that $e_1 = (1,0,0) $ it is without any reference to any other basis! It's like it's self-referential somehow, or it doesn't come from anywhere! How can I make sense of this?
It seems to me that $\{e_1,e_2,e_3\}$ is then some kind of 'special primordial' basis, and everything we do is implicitely in that basis, even when people choose to work in some other basis, for example the $f_i$'s! But that just doesn't feel right!
Thanks in advance

A: All of this is just an artifact of the fact that you chose to consider the vector space $V=\mathbb{R}^3$.  By definition, any element of $\mathbb{R}^3$ has three coordinates.  The basis $(e_1,e_2,e_3)$ has the property that the coefficients when expressing an element $v=(v_1,v_2,v_3)\in V$ with respect to this basis are just the coordinates $v_1$, $v_2$, and $v_3$.  But this doesn't mean that your definition of the $f_i$ is in terms of the $e_i$.  You have defined $f_3=(1,1,1)$, which is a perfectly explicit element of $V$ whose definition in no way involves the $e_i$.  You're just observing that it is very simple to read off from this definition how to express $f_3$ as a linear combination of the $e_i$, namely $f_3=e_1+e_2+e_3$.
What your uncle Bob is doing is abusing notation.  He really shouldn't write $g_3=(0,0,1)$, since that literally means that $g_3$ is the triple $(0,0,1)\in\mathbb{R}^3$.  Instead what he should write is $g_3=f_3$, or $g_3=A(0,0,1)$ where $A:V\to V$ is the unique linear map such that $A(e_i)=f_i$ for each $i$.  Note that the $e_i$ are again creeping into the definition, but this is only a matter of convention: by convention we say that a triple $(a,b,c)$ "represents" a vector $v$ with respect to a basis $(f_1,f_2,f_3)$ if $v=A(a,b,c)$ where $A$ is the linear map sending $e_i$ to $f_i$.  There's nothing special about our choice of $e_i$ in this convention; it's just an arbitrary (but convenient) choice.
To put it another way, the $e_i$ are not "primordial", but we have simply chosen them as our "default" basis of $\mathbb{R}^3$ because they are convenient to think about.  It's a social convention, not any deep mathematical truth.

A: @Ian's comment above is spot-on, except for one small point. You can't say $\mathbb R^3$ was given to you as a real vector space of dimension $3$, because even though all such spaces are isomorphic to $\mathbb R^3$ only one of them actually is $\mathbb R^3$, which is defined to be the set of all ordered 3-tuples of real numbers with addition defined term-wise and scalar multiplication defined by
$$
t (a, b, c) = (ta, tb, tc).
$$
(Some folks will say that $\mathbb R^3$ is the set of all functions from $\{0, 1, 2\}$ to $\mathbb R$, but folks who say that don't need an explanation of this question about bases, I believe.)
In general, $F^n$, where $F$ is any field, is defined analogously, and on such a "coordinate space", there's an interesting map from pairs of vectors to the underlying field, namely,
$$
(x_1, \ldots, x_n) \cdot (y_1, \ldots, y_n) \mapsto x_1y_1 + \ldots + x_n y_n.
$$
Under certain conditions on the field, this "dot product" operation happens to match the criteria for being an "inner product" on the vector space, but even when it's not, it may prove useful in various contexts.
My colleague Phil Klein has written a linear algebra book (Coding The Matrix) that discusses some of this.


text:
Q: Detecting Super Dev Mode from within GWT app I guess the title says it all:
Is there some kind of flag that allows my GWT app to check whether it is currently running in Super Dev Mode (something along the lines of GWT.isProdMode(), maybe)?

A: As it was already mentioned, there is a superdevmode property that you can use.
Here is a real-life example:

*

*Create a class containing a method that tells that we are not in SuperDevMode:
public class SuperDevModeIndicator {
    public boolean isSuperDevMode() {
        return false;
    }
}

*Extend previous class and override a method to tell that we are in SuperDevMode:
public class SuperDevModeIndicatorTrue extends SuperDevModeIndicator {
    @Override
    public boolean isSuperDevMode() {
        return true;
    }
}

*Use only one, appropriate class depending on a superdevmode property - use deferred binding - put this in your *.gwt.xml:
<!-- deferred binding for Super Dev Mode indicator -->
<replace-with class="com.adam.project.client.SuperDevModeIndicatorTrue">
  <when-type-is class="com.adam.project.client.SuperDevModeIndicator"/>
  <when-property-is name="superdevmode" value="on" />
</replace-with>

*Instantiate SuperDevModeIndicator class via deferred binding:
SuperDevModeIndicator superDevModeIndicator = GWT.create(SuperDevModeIndicator.class);

*Use it to check whether you are in SuperDevMode or not:
superDevModeIndicator.isSuperDevMode();

Voila!
Here you will find documentation on Deferred binding.

A: There's an open issue about having a public accessor like GWT.isProdMode().
In the mean time, if you really need to know, there's a deferred binding property named superdevmode that you can use in your <replace-with> or <generate-with> rules.

A: Maybe there is an "official" way, but this should work:
Storage stockStore = Storage.getSessionStorageIfSupported();
if (stockStore != null)
{
    boolean isSuperDevMode = stockStore.getItem("__gwtDevModeHook:" + GWT.getModuleName()) != null);
}

A: You could use GWTHelper.isSuperDevMode() method implemented below.
public final class GWTHelper {

    public static boolean isSuperDevMode() {
        final Storage storage = Storage.getSessionStorageIfSupported();
        if (storage == null) {
            return false;
        }
        final String devModeKey = "__gwtDevModeHook:" + GWT.getModuleName();
        return storage.getItem(devModeKey) != null;
    }

}

Source : https://gwt.googlesource.com/gwt/+/master/dev/core/src/com/google/gwt/core/linker/DevModeRedirectHook.js

A: To check for dev app server:
GWT.getHostPageBaseURL()    returns  http://127.0.0.1:8888/
Server side: request.getRemoteHost()
should return the same (though I haven't tested this).
To check for Super Dev Mode (vs dev app server without SDM):
If GWT.getModuleBaseURL() & GWT.getModuleBaseForStaticFiles() differ,
you're in Super Dev Mode.
property name="superdevmode" solution didn't work for me.

A: I used following method:
private static native boolean isSuperDevMode()/*-{
   return typeof $wnd.__gwt_sdm !== 'undefined';
 }-*/;
Works in GWT 2.7.0.

A: My solution is:
GWT.getModuleBaseForStaticFiles().contains("9876")

A: This is a pretty good solution.
boolean superdevmode = "on".equals(System.getProperty("superdevmode"));

A: May I suggest:
public boolean isSuperDevMode()
{
    return Window.Location.getPort().equals("8888");
}


text:
Q: MongoDB date range search without timestamp I have the following record in my mongodb collection:
{
    "_id" : ObjectId("5a7641b0d4b6828ad37c9a66"),
    "factor" : 1,
    "postdate" : ISODate("2018-01-31T05:00:00.000Z"),
}

I want to do a search where I do not factor the timestamp, only the year, month, day.  How can I do that?
The following does not work because the record has a time stamp that makes it not show up in my search:
db.transtest.find({postdate: { $gte : new Date("2018-01-01"), $lte : new Date("2018-01-31")}})

A: To include all of the last day of the month, use $lt and the first day of the next month:
db.transtest.find({postdate: { $gte: new Date("2018-01-01"), $lt: new Date("2018-02-01")}})

A: Simply add max day time to your $lt date criteria :
db.transtest.find({postdate: { $gte : new Date("2018-01-01"), $lte : new Date("2018-01-31T23:59:59.999Z")}})

You're sure to get all results because the precision of an ISOdate is millisecond

BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970).

Moreover, it automatically take care of timezone, since the record
{
   "_id" : ObjectId("5b459ef6744c541aa898cdd4"),
    "factor" : 1,
    "postdate" : ISODate("2018-02-01T00:10:00.000+0100")  // <== Note the date with +1 hour TZ, same as  ISODate("2018-01-31T23:10:00.000Z")
}

will be returned too.


text:
Q: How to insert Greek letters directly in math environment? Why are non-Latin characters not displayed in formulas, even when using XeLaTeX?
\documentclass{article}
\usepackage{xltxtra}

\begin{document}

$\omega$ %displyed
$ω$ %not displyed

\end{document}

A complementary for following answers:
You can use the following sites to copy and paste a lot of math symbols directly to your tex file, using unicode-math package:

*

*http://access2science.com/indexMathLanguages.html

*http://jrgraphix.net/r/Unicode

*http://tlt.its.psu.edu/suggestions/international/bylanguage
Beside more readability in your markup you have not to search for a specific package that provide a special symbol.

A: You can't use non-latin alphabets in math formulas for font reasons, even XeTeX use traditional Type1/MetaFont math fonts by default.
You can, however, use unicode-math package with OpenType math fonts:
\documentclass{article}
\usepackage{unicode-math}
\setmathfont{Latin Modern Math}
\begin{document}

$α + β + γ + δ = ε$

\[
∫f(x)dx = ∑_k Λ_k
\]

\end{document}

A: Not at all difficult:
\documentclass[a4paper]{article}
\usepackage{fontspec}

\mathcode`ω=\omega

\begin{document}

$\omega=ω$

\end{document}

Repeat for all the symbols you need, along the same path. However, switching to unicode-math might be handier:
\documentclass[a4paper]{article}
\usepackage{unicode-math}
\setmathfont{Latin Modern Math}

\begin{document}

$\omega=ω$

\end{document}


text:
Q: load a url in new tab jquery I am trying to open a url in a new tab with the below code, but can't able to do so
partial_url = '/products/compare/?ids=f25353f4e8f2,598f4166e2d9,39c17d76-133e-4a86-bf39-d4d5e600349a&fis=1,2,3,4,5,6,8,10'

final_url = window.location.host + partial_url + '&new_html=true';

var win = window.open(final_url, '_blank');
win.focus();

The above code was opening a new tab but with about:blank in the address bar, but was not opening my url, so what's wrong in the above code ?
Note:

final_url = 'http://localhost:8000/products/compare/?ids=f25353f4e8f2,598f4166e2d9,d4d5e600349a&fis=1,2,3,4,5,6,8,10&new_html=true'

A: Try this: by default window.open will open in a new tab
var win = window.open(final_url);

It works for me.

A: Remove window.location.host
try it
final_url = partial_url + '&new_html=true';


text:
Q: Pip does not want to be installed Pip does not find in the console. When I try to download it through get-pip, it produces the following errors in the console. I downloaded the latest version 3.7.4 from the official site. The same was observed with other versions. How to fix it?
F:\pic.png>python get-pip.py
Traceback (most recent call last):
  File "get-pip.py", line 21492, in <module>
    main()
  File "get-pip.py", line 197, in main
    bootstrap(tmpdir=tmpdir)
  File "get-pip.py", line 82, in bootstrap
    import pip._internal
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 668, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 638, in _load_backward_compatible
  File "C:\Users\75E3~1\AppData\Local\Temp\tmpmb245qvv\pip.zip\pip\_internal\__i
nit__.py", line 40, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 668, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 638, in _load_backward_compatible
  File "C:\Users\75E3~1\AppData\Local\Temp\tmpmb245qvv\pip.zip\pip\_internal\cli
\autocompletion.py", line 8, in <module>
  ******
  ******
  ******
  File "C:\Users\75E3~1\AppData\Local\Temp\tmpmb245qvv\pip.zip\pip\_vendor\reque
sts\_internal_utils.py", line 11, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 668, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 638, in _load_backward_compatible
  File "C:\Users\75E3~1\AppData\Local\Temp\tmpmb245qvv\pip.zip\pip\_vendor\reque
sts\compat.py", line 64, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 724, in exec_module
  File "<frozen importlib._bootstrap_external>", line 859, in get_code
  File "<frozen importlib._bootstrap_external>", line 917, in get_data
OSError: [Errno 9] Bad file descriptor


text:
Q: Classic ASP - ServerXMLHTTP NT Authentication So I have the following code which I want to use in order to download images and save them.
<%
function SaveFileFromUrl(Url, FileName)
    dim objXMLHTTP, objADOStream, objFSO

    Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.3.0")

    objXMLHTTP.open "GET", Url, false
    objXMLHTTP.send()

    If objXMLHTTP.Status = 200 OR objXMLHTTP.Status = 304 Then
        Set objADOStream = CreateObject("ADODB.Stream")
        objADOStream.Open
        objADOStream.Type = 1 'adTypeBinary

        objADOStream.Write objXMLHTTP.ResponseBody
        objADOStream.Position = 0 'Set the stream position to the start

        Set objFSO = Createobject("Scripting.FileSystemObject")
        If objFSO.Fileexists(FileName) Then objFSO.DeleteFile FileName
        Set objFSO = Nothing

        objADOStream.SaveToFile FileName
        objADOStream.Close
        Set objADOStream = Nothing

        SaveFileFromUrl = objXMLHTTP.getResponseHeader("Content-Type")
    else
        SaveFileFromUrl = ""
    End if
    response.write objXMLHTTP.Status
    Set objXMLHTTP = Nothing
end function
%>

When I run this on images from the web, it works fine. However when trying to use it on intranet images that need NT authentication, I get a 401 error back by using response.write objXMLHTTP.Status
So my somewhat obvious question is - how do I go about this in the script without taking off NT authentication?
HOWEVER
It may also be due to the fact that the images do not have an extension. They are in the form http://domain/thumbs/image1 rather than http://domain/thumbs/image1.png
Either way, I can't get it to work!
Thanks

A: http://msdn.microsoft.com/en-us/library/ms763809%28v=vs.85%29.aspx
objXMLHTTP.open(bstrMethod, bstrUrl, bAsync, bstrUser, bstrPassword);


text:
Q: Connect to BSC Node running on VPS via Websocket or HTTP I have set up my own node on BSC following the docs here - https://docs.binance.org/smart-chain/developer/fullnode.html
The problem I am having is that I am unable to connect with Web3 to the node.
When trying to connect using
web3 = Web3(Web3.WebsocketProvider('ws://[server-ip]:8545'))
print('ws - ' + str(web3.isConnected()))

my output is false
When running the node I am using:
./geth --config ./config.toml --datadir ./mainnet --ws --ws.port=8545  --ws.origins='*'

I have tried many combinations of config to get this working but with no luck. Generally, I'm trying to connect via web socket, but I'd be happy to connect with an HTTP provider instead if need be.
Looking at the netstat --listen --tcp output I get this when the node is running:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:8545          0.0.0.0:*               LISTEN
tcp        0      0 localhost:domain        0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN
tcp6       0      0 [::]:30311              [::]:*                  LISTEN
tcp6       0      0 [::]:ssh                [::]:*                  LISTEN

Does anyone know what im missing?

A: After a lot of research, I found that the best way to handle this it to simply run an Nginx proxy.
Here are the instructions I followed for any that are looking for a solution to a similar problem
https://www.nginx.com/blog/websocket-nginx/

A: The node seems to ignore the config.toml in that part. You have to add --ws to the list of parameters when starting the node. If the node is supposed to be public facing then also specify the port - like this:
./geth --ws --ws.addr=ip_of_server --config ./config.toml --datadir ./node


text:
Q: Entity Framework CASE statement with ORDER BY Can someone give me a hand in converting following SQL to a linq query?
SELECT TOP 1000 CountryID
,CoutryName
,ISO2
FROM dbo.Countries
ORDER BY CASE WHEN ISO2 IN('GB','LU','CA','ES')
THEN 0 ELSE 1 END, CountryID

A: OrderBy by CASE can be expressed by ternary operator ? :
var names = new [] {"GB", "LU", "CA", "ES"};
...
query = query.OrderBy(x => names.Contains(x.ISO2) ? 0 : 1);


text:
Q: The IPA symbol for the labiodental flap (ⱱ) I need the ⱱ character (prefereably with the advanced diacritic underneath it) for a phonetics paper, but the tipa package doesn't seem to contain it.  I have at least one font with this character on my computer (Charis SIL).  How do I get the character into my LaTeX document?

A: The symbol is defined as U+2C71 and the advanced diacritic as U+31F. If you want to use some special font on you system, you will have to use fontspec and Lua- or XeLaTeX. I am showing two fonts I found on my system and the possible kerning correction, if the diacritic is not set nicely:
% arara: lualatex

\documentclass{article}
\usepackage{fontspec}
\usepackage{lua-visual-debug} % for demo

\begin{document}
\setmainfont{quivira.otf}
\symbol{"031F}\symbol{"2C71} \symbol{"031F}\kern-.15em\symbol{"2C71}

\setmainfont{EBGaramond}
\symbol{"031F}\symbol{"2C71} \symbol{"031F}\kern-.12em\symbol{"2C71}
\end{document}

A: I had the same issue and someone answered it. Turns out you can input it as you would any Unicode character but the font needs to support it. Junicode is one such font.
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Junicode} % any font that has an entry at U+2C71

\begin{document}

\char"2C71

\end{document}


text:
Q: How to display image from local path from jsp I am trying to display an image throw jsp. Image is stored in local path so I wrote a servlet get method to retrive image and in src attribute of image tag I am giving the servlet name and image path as parameter to servlet and here is my code,
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String filePath;
 public void init() throws ServletException {

    this.filePath = "/files";
}

protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("In do get");

    // Get requested file by path info.
    String requestedFile = request.getPathInfo();

    // Check if file is actually supplied to the request URI.
    if (requestedFile == null) {
        // Do your thing if the file is not supplied to the request URI.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Decode the file name (might contain spaces and on) and prepare file object.
    File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName());

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("In do post");

}

private static void close(Closeable resource) {
    if (resource != null) {
        try {
            resource.close();
        } catch (IOException e) {
            // Do your thing with the exception. Print it, log it or mail it.
            e.printStackTrace();
        }
    }
}

in web.xml the servlet entry is as follow,
<servlet>
<description>
</description>
<display-name>FileServlet</display-name>
<servlet-name>FileServlet</servlet-name>
<servlet-class>com.mypackage.FileServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/file/*</url-pattern>
</servlet-mapping>

In Jsp I have img tag as follow,

I think I made mistake in src attribute of img tag can anyone tell wht is the mistake I made here .

A: Looks like you have misunderstood BalusC's post about this: FileServlet. In this case, you will have a base path in your disk to server your files (external to the web application folder path in server), and then the path used in your URL will be used to search inside this base path. Note from BalusC's example how to call the resources:
download foo.exe

Where:

*

*file is the URL pattern for your Servlet. Noted in your web.xml configuration:
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/file/*</url-pattern>
</servlet-mapping>

*The rest of the URL /foo.exe is the location of the file in your server hard drive. This can be easily obtained by usage of HttpServletRequest.html#getPathInfo
This is noted by this part of the code (comments are mine):
public void init() throws ServletException {
    this.filePath = "/files";
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    // Get the file path from the URL.
    String requestedFile = request.getPathInfo();

    //...
    //using filePath attribute in servletclass as the base path
    //to lookup for the files, using the requestedFile
    //path to seek for the existance of the file (by name)
    //in your server
    //decoding the name in case of GET request encoding such as
    //%2F => /
    File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
    //...
}

Then, when having a request like this (in HTML code in your view):

You have to make sure the file exists in your server:
- /  <-- root
  - /files <-- this is the base file path set in init method in your servlet
    - /img
      - myimage.png

More info:

*

*BalusC's FileServlet blog entry

*What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

A: The mistake you made is trying to call your JSP page as an image resource. The JSP itself is just a text file. You need to substitute the path to the file with a url to the page on a server that will compile/serve the results of the JSP page, namely the image. If it's on a local server, typically the url will look like http://localhost:<port>/.../img14.jsp.

A: Your src attribute of img tag should be like this to send request to your servlet.
src="${pageContext.request.contextPath}/FileServlet/getImage?path=D:\offline_registration\11022017\unzip\a89a89e9-5de2-4bb2-9225-e465bb5705b1.jpeg"
here path variable contains path of image from local system.

A: I have tried below code and it works fine in both servlet and java. If the image is converted as byte in servlet using the code below then set the converted byte code in session attribute and get it jsp.
Note: it can display any format of image
package Jx_Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;

public class Imag {

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        // TODO Auto-generated method stub
         File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Desert.jpg");

            FileInputStream fis = new FileInputStream(file);
            //create FileInputStream which obtains input bytes from a file in a file system
            //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            try {
                for (int readNum; (readNum = fis.read(buf)) != -1;) {
                    //Writes to this byte array output stream
                    bos.write(buf, 0, readNum);
                    System.out.println("read " + readNum + " bytes,");
                }
            } catch (IOException ex) {
               // Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
            }

            byte[] bytes = bos.toByteArray();

            byte[] encodeBase64 = Base64.encodeBase64(bytes);
            String base64Encoded = new String(encodeBase64, "UTF-8");

            System.out.println(base64Encoded);
    }

}

//Jsp
<img src="data:image/jpeg;base64,<%=base64Encoded%>"/>


text:
Q: How to store data in Django Model without having an input field I have model for example like this:
class Meeting(models.Model):
    date = models.DateTimeField(default=datetime.datetime.now)
    team = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = u'Meetings'
        ordering = ['-date', 'team']

    def __unicode__(self):
        return u'%s %s' % (self.date, self.team)

class Entry(models.Model):
    meeting = models.ForeignKey(Meeting, blank=True)
    meeting_date = models.DateField(null=True)
    description = models.TextField()

    class Meta:
        verbose_name_plural = u'Entries'

    def __unicode__(self):
        return self.title

I am having a form I am controlling the input with
class MyEntryAdminForm(forms.ModelForm):
class Meta:
    model = Entry

I am getting the data for the meeting field with
meeting = forms.ModelChoiceField(queryset=Meeting.objects.all(), empty_label=None)

I want to extract the date part of the meeting field (I am able to manage this). This date part should be the input for the meeting_date field. The meeting_date field has no input field in the form and should be populated automatically.
I don't know how to get this date extract into the meeting_date field and how to store it
The attempt in def clean(self)
cleaned_data['meeting_date'] = date_extract_from_meeting

does not work
Any help is highly appreciated

A: There is probably a way to override the form save() method and put the date in at that step, but I can't find any examples of doing this.
A way that I know would work for sure is to pass in commit=False to form.save (this way the actual database insert doesn't happen yet):
instance = form.save(commit=False)

Then you can set the meeting date and save the object:
instance.meeting_date = instance.meeting.date
instance.save()

Hope this helps.


text:
Q: Point light in Unity (3D) only shines in one direction when I add a normal map to a material I've been looking around for answers and I haven't found any.
Whenever I add a .jpg as a normal map in a material, and use that material on objects, point lighting breaks and only shines in one direction
https://i.stack.imgur.com/zoeT9.jpg
(With the .jpg added as a normal map)
https://i.stack.imgur.com/fZy5w.png
(Without any normal maps added, how it should look)
What am I doing wrong?
https://i.stack.imgur.com/3IWLV.png
This is the settings for the texture I'm trying to use


text:
Q: ActiveMQ and Tomcat (6.x): work together? I'm working on my first ActiveMQ deploy (actually the broker is Apollo). I'd like to use pooled connections as eventually we will have lots of producers and consumers, perhaps in the same VM, sending and receiving lots of messages.
But reading http://activemq.apache.org/how-do-i-use-jms-efficiently.html it really is not too clear to me what is the best path to efficiency:
1) camel?
2) spring?
3) PooledConnectionFactory? Is this class even compatible with Tomcat, sure likes to throw exceptions.
JCA does not look like an option since Tomcat 6.x is not supported.

A: Tomcat does not really care or even know anything about JMS. So, standard approach would do, like you stated.
As far as performance is concerned, Camel and Spring (which Camel JMS is based upon) does not really add anything to performance, rather the other way around. These frameworks instead add a lot of convenience when it comes to writing complex JMS applications. The PoolingConnecitonFactory class (or even the generic spring class [CachingConnectionFactory])2 enable reuse of objects and hence boosts performance when using Spring based JMS frameworks such as Camel.


text:
Q: Script de módulo logging: usando os.getenv Eu estou aprendendo Python e estou seguindo o livro A byte of python. Em um exercício falando sobre o módulo logging há a seguinte linha de código:
if platform.system().startswith('Windows'):
logging_file = os.path.join(os.getenv('DIRETORIOINICIAL'), os.getenv('PATH'), 'test.log')

O script apenas escreve dentro do arquivo teste.log com o data e hora em que foi rodado o script.
Segui exatamente como está no livro mas recebo sempre o mesmo trackback:
Traceback (most recent call last):
  File "using_logging.py", line 6, in <module>
    logging_file = os.path.join(os.getenv('DIRETÓRIOINICIAL'), os.getenv('PATH'), 'test.log')
  File "C:\Python34\lib\ntpath.py", line 108, in join
    result_drive, result_path = splitdrive(path)
  File "C:\Python34\lib\ntpath.py", line 159, in splitdrive
    if len(p) > 1:
TypeError: object of type 'NoneType' has no len()

Ele não retorna e nem escreve o arquivo.


text:
Q: How to stop and start Docker container from bash script Synology? Hey guys so I'm on a synology DS218+ and I'm running docker and hosting my own instance of gitlab in it.
So now I'm trying to write an update Script with bash.
docker stop gitlab_td3v
rm -rf /volume1/docker/"gitlab"
rm -rf /volume1/gitlab/"gitlab_backup.rb"
cp -r  /volume1/gitlab /volume1/docker/"gitlab"
cp /volume1/gitlab/config/gitlab.rb /volume1/gitlab/"gitlab_backup.rb"
docker rm -f gitlab_td3v
docker pull gitlab/gitlab-ee:latest
docker run --detach --hostname Myhost.name --name gitlab_td3v --publish ..:.. --publish ..:..  --publish ..:..  --restart always --volume /volume1/gitlab/config:/etc/gitlab --volume /volume1/gitlab/data:/var/opt/gitlab --volume /volume1/gitlab/logs:/var/log/gitlab gitlab/gitlab-ee:latest

The problem I have now as you can see in the image I'm trying to stop and remove the container but It doesn't recognise it's name, but if I echo  docker ps in the file it gives me the container with the name I used in the file.
CLI
Also when I just run the commands in the bash shell it works only as soon as I try to run the file it doesn't work and now I'm really confuse cause I made sure I'm on the same user on the same shell and everything and that I am but in the file it won't let me select the container over the name or the id I get from docker ps.
So now the question I guess is did anyone have the same problem or does anyone know a fix for it?
Would really appreciate it thanks.

A: The script must be executed as root.
docker stop CONTAINERNAME

CONTAINERNAME is definied by value "NAME"
See by
docker stats


text:
Q: Shouldn't you always need to define functions before using them in a C file? I have the following bit of C code:
int main() {
    myFunctionABC(2);
    return 0;
}

void myFunctionABC(int n) {
    printf("%d\n", n);
}

So... this code is working and I don't understand why. I always thought that a C compiler would always need every referred function to be already "known", otherwise would fail the compilation process.
Why is this working?

A: There has never been any requrement to define functions before calling them in C or in C++ (as the title of your question suggests). What is required in C++ and C99 (and in some cases in C89/90) is to declare functions before calling them.
As for your code... Your code is not "working". The best you can hope for is that your code will produce undefined behavior that will just happen to resemble "working".
Firstly, the code will not even compile as C++ or as C99 (and you tagged your question as both C and C++). C++ and C99 unconditionally require functions to be declared before they are called.
Secondly, with C89/90 compiler the code might compile, but will produce the aforementioned undefined behavior anyway. Even in C89/90 calling variadic functions (like printf) without declaring them first is illegal - it produces undefined behavior.
For non-variadic functions calling them without declaring them is OK - the implicit declaration rules of C89/90 will take care of that. But these rules will make the compiler to conclude that your undeclared myFunctionABC function returns an int, while in reality you defined it as returning void - this discrepancy leads to undefined behavior as well. Most self-respecting compilers will at least warn you about the problem.

A: gcc rightfully complains:
make 4356180
4356180.c:6: warning: conflicting types for 'myFunctionABC'
4356180.c:2: note: previous implicit declaration of 'myFunctionABC' was here

If I add -Wall, I get these at well:
make CFLAGS=-Wall 4356180
4356180.c: In function 'main':
4356180.c:2: warning: implicit declaration of function 'myFunctionABC'

A: It is not erroneous to declare a function prototype before actually calling it even if its definition is in a subsequent location, but it is a good practice to help the compiler out, check this similar post


text:
Q: Using Crystal Quartz I am trying to use Crystal Quartz I downloaded the source with,
svn checkout http://crystal-quartz.googlecode.com/svn/trunk/ crystal-quartz-read-only

But When I try to run the project demo, after click the "View CrystalQuartz Panel -->" on the default page I get 404 not found error from iis.
It seems to be trying to access CrystalQuartzPanel.axd, but this doesn't exist.
Has anyone used this before and know how to get it to work?

A: There's no such folder in trunk
Open this in browser: http://crystal-quartz.googlecode.com/svn/trunk/
Or check out the whole trunk


text:
Q: How to directly get option in C# Command-Line I'm testing C# console application cli tool (System.CommandLine) & I have this code:
using System.CommandLine.NamingConventionBinder;
using System.CommandLine;

internal class Program
{
    private static async Task Main (string[] args)
    {
        var rootCommand = new RootCommand { };

        var getCommand = new Command ("get")
        {
            new Option<string> (
                "me",
                description: "Gets the name of a takeep & shows its text.")
        };

        var setCommand = new Command ("set")
        {
            new Option<string> (
                "the",
                description: "Sets a takeep by name & text.")
        };

        getCommand.Handler = CommandHandler.Create<string> ((me) =>
        {
            Console.WriteLine ($"Build Version: {me}");
        });

        setCommand.Handler = CommandHandler.Create<string> ((set) =>
        {
            Console.WriteLine ($"Build Version: {set}");
        });

        rootCommand.Add (getCommand);
        rootCommand.Add (setCommand);

        await rootCommand.InvokeAsync (args);
    }
}

When I call the command, this way:
.\takeep.cli.exe get me 'Name'
Is there a way to remove that "me", but keep its functionality (I mean, other commands also work)?  Thanks for your help


text:
Q: Equivalence of definitions of Gaussian Measure Wikipedia's article on Gaussian measures notes this as the definition of Gaussian measures:
$\gamma_{\mu, \sigma^{2}}^{n} (A) := \frac{1}{\sqrt{2 \pi \sigma^{2}}^{n}} \int_{A} \exp \left( - \frac{1}{2 \sigma^{2}} \| x - \mu \|_{\mathbb{R}^{n}}^{2} \right) \, \mathrm{d} \lambda^{n} (x).$
I haven't been able to find this definition anywhere else, including the book by Bogachev.
In Bogachev's book, they mention that the density of the measure is given by:
$x \to \frac{1}{\sqrt{(2 \pi)^n \det K}} \exp{\{-\frac{1}{2}<K^{-1} (x - a), x - a> \}}$, where $K$ is the covariance.
My first question is:
Is the wikipedia definition accurate? If it is, can someone give me a reference to a published book or lectures notes for a class or some reference that has the same definition?
My second question:
How are these definitions the same? Perhaps I don't understand densities of measures well, but aren't the expressions supposed to be exactly the same?

A: That "Wikipedia" definition is for the special case where the covariance matrix is $\sigma^2 I$.  In that case they are equivalent.  A measure $\mu$ on $\mathbb R^n$ has density $\rho$ with respect to Lebesgue measure $\lambda^n$ iff
$\mu(A) = \int_A \rho(x) \; d\lambda^n(x)$ for all Lebesgue measurable sets $A$.


text:
Q: Laravel 5.4 @include not working - throws ErrorException View not found I'm new to Laravel, using 5.4 in an XAMPP stack and I can't get the @include to work.
Forgive me if I ask some stupid questions here, but this is the first framework I've worked on in nearly two years, so I'm a bit rusty.
I have a view in the resources/views directory, and I just want to include some simple html divs which I would like to be in a separate .inc file.
Basically, I have an index.blade.php view in the resources/views/xxx directory, which works fine, but has divs of html which I'd like to get out of the way in a notes.inc.blade.php file, and then @include it into the index.
I've tried creating the .inc file in the same folder, then using @include('notes.inc') , but this doesn't work. I've also tried moving the inc file to the resources/views directory and then using @include('xxx.notes.inc') but again no joy. All I get is:
Whoops, looks like something went wrong.
(2/2) ErrorException
View [notes.inc] not found.
(View: C:\xampp\htdocs\xxxxxxx\resources\views\xxxxxxs\index.blade.php)
I haven't changed any path definitions or configs.
Most of the forums (fora?) that I have found are talking about Laravel 4, so is there anyone that can point me at some clear instructions on how to do it in 5.4?
Or am I missing something obvious?
I would be happy to provide sample code if anyone needs it.

A: The view paths are not relative, so if you use @include('xxx.notes.inc') in the resources/views/xxx/index.blade.php, your included template must be in resources/views/xxx/notes/inc.blade.php.