text:
Q: Back button Gives force close in TabGroup Activity I am having four tabs by using tab group acitvity.I have an issue when clicking on back button gives crash but i want to go up to first activity in each tab.
here is my code TabHome.java
super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.tab);

        Resources res = getResources();
        tabs = getTabHost();
        TabHost.TabSpec spec;
        Intent intent;

        // Create an Intent to launch an Activity for the tab (to be reused)
        //1 -Gebrauchte  Tab
        intent = new Intent().setClass(this,TabBikesGroupActivity.class);

        // Initialize a TabSpec for each tab and add it to the TabHost
        spec = tabs.newTabSpec("gebrauchte").setIndicator("Gebrauchte",
                          res.getDrawable(R.drawable.bike))
                      .setContent(intent);
        tabs.addTab(spec);

        //2 - Produkte
        intent = new Intent().setClass(this, TabProductGroupActivity.class);
        spec = tabs.newTabSpec("produkte").setIndicator("Produkte",
                          res.getDrawable(R.drawable.t_produkt))
                      .setContent(intent);
        tabs.addTab(spec);

        //3 - Handler
        intent = new Intent().setClass(this, TabDealersGroupActivity.class);
        spec = tabs.newTabSpec("handler").setIndicator("Handler",
                          res.getDrawable(R.drawable.haendler))
                      .setContent(intent);
        tabs.addTab(spec);

        //4 - Einstellungen
        intent = new Intent().setClass(this, TabSettingsGroupActivity.class);
        spec = tabs.newTabSpec("einstellungen").setIndicator("Einstellungen",
                          res.getDrawable(R.drawable.t_settings))
                      .setContent(intent);

        tabs.addTab(spec);

     // tabHost.setCurrentTab(1);

   }

    public void switchToTab(int tabid){
        System.out.println("CURRENT TAB "+tabid);
        tabs.setCurrentTab(tabid);
}

above code describs about tabgroup activity
and
    Here is my first tab DealersDetailDisplay.java
In that i'm having two button and calling the below methods.When i click on this buttons goes to (Bike search list Activity -> Image adapter -> details activity ->search list Activity -> image adapter -> details activity -> goes same like above)infinite times.Now my problem is when i click on the back button then needs to move activity up to first Bike search list Activity.

This is my two buttons action listeners.....
    btnAllBikeDetail.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                getBikeSearchForDealer(dealerId);
            }
        });

    btnAllProductDetail.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                getProductSearchForDealer();
            }
        });

The below two methods are getting datas from particular url and list out in another activity .After that if i am selecting particular list items then moves to another activity (that is Image adapter) then again click it moves to another one then again you get the above two buttons(same action)this will goes likes this continously...
protected void getBikeSearchForDealer(String dealerId) {
        // TODO Auto-generated method stub
        try {
            URL url = URLComposer.getMotorCycleListUsedByDealerURL(dealerId);
            System.out.println("URL " + url.toString());

            Intent intent=new Intent(getParent(),BikesList.class);
            intent.putExtra("Search_Result",url.toString());
            TabGroupActivity parentActivity =(TabGroupActivity) getParent();
            parentActivity.startChildActivity("BikeSearch", intent);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void getProductSearchForDealer() {
        // TODO Auto-generated method stub
        try {
            URL url = URLComposer.getDealersProductListURL(dealerId);
            System.out.println("URL " + url.toString());

            Intent intent = new Intent(getParent(), ProductList.class);

            TabGroupActivity parentActivity = (TabGroupActivity) getParent();
            intent.putExtra("Dealer_Search_Result",       url.toString());
            parentActivity.startChildActivity("productList",
                    intent);
            System.out.println("URL " + url.toString());
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
Logcat result is

03-17 14:37:59.760: I/System.out(585): Gallery position :http://www.1000ps.at//images/gebrauchtmotorrad/g_G625147_2.jpg
03-17 14:37:59.900: D/dalvikvm(585): GC_FOR_MALLOC freed 12364 objects / 869712 bytes in 132ms
03-17 14:37:59.931: D/webviewglue(585): nativeDestroy view: 0x3d60c0
03-17 14:37:59.940: D/webviewglue(585): nativeDestroy view: 0x354ac8
03-17 14:38:03.620: I/System.out(585): Gallery position :http://www.1000ps.at//images/gebrauchtmotorrad/g_G625147_3.jpg
03-17 14:38:06.151: I/System.out(585): Gallery position :http://www.1000ps.at//images/gebrauchtmotorrad/g_G625147_3.jpg
03-17 14:38:06.301: D/dalvikvm(585): GC_EXTERNAL_ALLOC freed 4806 objects / 406080 bytes in 147ms
03-17 14:38:06.320: D/webviewglue(585): nativeDestroy view: 0x35c568
03-17 14:38:06.361: D/skia(585): --- decoder->decode returned false
03-17 14:38:08.303: I/System.out(585): Gallery position :http://www.1000ps.at//images/gebrauchtmotorrad/g_G625147_3.jpg
03-17 14:38:12.480: I/System.out(585): Gallery position :http://www.1000ps.at//images/gebrauchtmotorrad/g_G625147_2.jpg
03-17 14:38:23.981: I/System.out(585): hasUsedBikesnull
03-17 14:38:23.981: I/System.out(585): hasUsedProductsnull
03-17 14:38:24.081: I/System.out(585): hsdjka265204
03-17 14:38:26.191: I/System.out(585): bikeOrder bikeID265204
03-17 14:38:26.191: I/System.out(585): bikeOrder bikeId:265204
03-17 14:38:26.191: I/System.out(585): XML Valueshttp://iphone.1000ps.at/iphone-xml/gebrauchte_suche_result.ashx?suchen_member=265204
03-17 14:38:26.191: I/System.out(585): URL http://iphone.1000ps.at/iphone-xml/gebrauchte_suche_result.ashx?suchen_member=265204
03-17 14:38:26.241: I/System.out(585): Override const
03-17 14:38:26.860: I/System.out(585): Hitting the webservice
03-17 14:38:26.860: I/System.out(585): DOM :org.apache.harmony.xml.dom.DocumentImpl@450c69e0
03-17 14:38:26.860: I/root node of document(585): BikeResults
03-17 14:38:26.860: I/System.out(585): welcome
03-17 14:38:26.860: I/System.out(585): welcome
03-17 14:38:26.860: I/System.out(585): welcome
03-17 14:38:26.870: I/System.out(585): welcome
03-17 14:38:26.870: I/System.out(585): welcome
03-17 14:38:26.880: I/System.out(585): bikeItemListSize5
03-17 14:38:27.001: I/System.out(585): Pending View
03-17 14:38:27.011: I/System.out(585): Override const
03-17 14:38:27.550: I/System.out(585): Hitting the webservice
03-17 14:38:27.680: I/System.out(585): DOM :org.apache.harmony.xml.dom.DocumentImpl@45186100
03-17 14:38:27.690: I/root node of document(585): BikeResults
03-17 14:38:29.070: I/System.out(585): Override const
03-17 14:38:29.070: I/System.out(585): XML Valueshttp://iphone.1000ps.at/iphone-xml/gebrauchte_detail.ashx?gid=559645
03-17 14:38:29.640: I/System.out(585): Hitting the webservice
03-17 14:38:29.640: I/System.out(585): DOM :org.apache.harmony.xml.dom.DocumentImpl@451cad88
03-17 14:38:29.640: I/root node of document(585): document
03-17 14:38:29.670: I/System.out(585): BikeDataSerive, biekId: 559645
03-17 14:38:29.680: I/node list name(585): org.apache.harmony.xml.dom.NodeListImpl@450209a0
03-17 14:38:29.680: I/node values(585): 1
03-17 14:38:29.680: I/node list name(585): org.apache.harmony.xml.dom.NodeListImpl@450202a8
03-17 14:38:29.680: I/node values(585): 1
03-17 14:38:29.680: I/System.out(585): Thumbnail images http://www.1000ps.at//images/gebrauchtmotorrad/g_559645.jpg
03-17 14:38:29.680: I/System.out(585): Thumbnail images http://www.1000ps.at//images/gebrauchtmotorrad/g_559645_2.jpg
03-17 14:38:29.680: I/System.out(585): Thumbnail images http://www.1000ps.at//images/gebrauchtmotorrad/g_559645_3.jpg
03-17 14:38:29.690: I/System.out(585): Thumbnail images http://www.1000ps.at//images/gebrauchtmotorrad/g_559645_4.jpg
03-17 14:38:29.690: I/System.out(585): Original images http://www.1000ps.at//images/gebrauchtmotorrad/g_G559645.jpg
03-17 14:38:29.690: I/System.out(585): Original images http://www.1000ps.at//images/gebrauchtmotorrad/g_G559645_2.jpg
03-17 14:38:29.690: I/System.out(585): Original images http://www.1000ps.at//images/gebrauchtmotorrad/g_G559645_3.jpg
03-17 14:38:29.690: I/System.out(585): Original images http://www.1000ps.at//images/gebrauchtmotorrad/g_G559645_4.jpg
03-17 14:38:29.690: I/node list name(585): org.apache.harmony.xml.dom.NodeListImpl@4522a1c0
03-17 14:38:29.690: I/node values(585): 1
03-17 14:38:29.710: I/System.out(585): BikeDataService email:th.strassnitzky@utanet.at
03-17 14:38:29.710: I/System.out(585): kraft: null
03-17 14:38:33.321: I/System.out(585): Activity Being closeActivities.BikeDetailsDisplay
03-17 14:38:33.321: I/System.out(585): Destroy called
03-17 14:38:34.460: I/System.out(585): Activity Being closeActivities.BikesList
03-17 14:38:34.460: I/System.out(585): Destroy called
03-17 14:38:35.261: I/System.out(585): Activity Being closeActivities.BikeOrder
03-17 14:38:35.261: I/System.out(585): Destroy called
03-17 14:38:35.261: W/System.err(585): java.lang.NullPointerException
03-17 14:38:35.271: W/System.err(585):  at com.InternetGMBH.ThousandPS.Activities.TabGroupActivity.finishFromChild(TabGroupActivity.java:54)
03-17 14:38:35.271: W/System.err(585):  at android.app.Activity.finish(Activity.java:3249)
03-17 14:38:35.271: W/System.err(585):  at com.InternetGMBH.ThousandPS.Activities.TabGroupActivity.onBackPressed(TabGroupActivity.java:108)
03-17 14:38:35.271: W/System.err(585):  at com.InternetGMBH.ThousandPS.Activities.BikeOrder$1.onClick(BikeOrder.java:134)
03-17 14:38:35.271: W/System.err(585):  at android.view.View.performClick(View.java:2408)
03-17 14:38:35.281: W/System.err(585):  at android.view.View$PerformClick.run(View.java:8816)
03-17 14:38:35.281: W/System.err(585):  at android.os.Handler.handleCallback(Handler.java:587)
03-17 14:38:35.281: W/System.err(585):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 14:38:35.281: W/System.err(585):  at android.os.Looper.loop(Looper.java:123)
03-17 14:38:35.281: W/System.err(585):  at android.app.ActivityThread.main(ActivityThread.java:4627)
03-17 14:38:35.281: W/System.err(585):  at java.lang.reflect.Method.invokeNative(Native Method)
03-17 14:38:35.281: W/System.err(585):  at java.lang.reflect.Method.invoke(Method.java:521)
03-17 14:38:35.281: W/System.err(585):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-17 14:38:35.281: W/System.err(585):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-17 14:38:35.281: W/System.err(585):  at dalvik.system.NativeStart.main(Native Method)
03-17 14:39:07.670: I/System.out(585): bikeOrder bikeID265204
03-17 14:39:07.670: I/System.out(585): bikeOrder bikeId:265204
03-17 14:39:07.670: I/System.out(585): XML Valueshttp://iphone.1000ps.at/iphone-xml/gebrauchte_suche_result.ashx?suchen_member=265204
03-17 14:39:07.670: I/System.out(585): URL http://iphone.1000ps.at/iphone-xml/gebrauchte_suche_result.ashx?suchen_member=265204
03-17 14:39:07.730: I/System.out(585): Override const
03-17 14:39:09.020: I/System.out(585): Hitting the webservice
03-17 14:39:09.020: I/System.out(585): DOM :org.apache.harmony.xml.dom.DocumentImpl@451aca80
03-17 14:39:09.020: I/root node of document(585): BikeResults
03-17 14:39:09.051: I/System.out(585): welcome
03-17 14:39:09.051: I/System.out(585): welcome
03-17 14:39:09.051: I/System.out(585): welcome
03-17 14:39:09.051: I/System.out(585): welcome
03-17 14:39:09.081: I/System.out(585): welcome
03-17 14:39:09.110: I/System.out(585): bikeItemListSize5
03-17 14:39:09.231: I/System.out(585): Pending View
03-17 14:39:09.231: I/System.out(585): Override const
03-17 14:39:10.520: I/System.out(585): Hitting the webservice
03-17 14:39:10.720: I/System.out(585): DOM :org.apache.harmony.xml.dom.DocumentImpl@4529c450
03-17 14:39:10.740: I/root node of document(585): BikeResults
03-17 14:39:20.171: I/System.out(585): Activity Being closeActivities.BikesList
03-17 14:39:20.171: I/System.out(585): Destroy called
03-17 14:39:20.171: D/AndroidRuntime(585): Shutting down VM
03-17 14:39:20.171: W/dalvikvm(585): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
03-17 14:39:20.201: E/AndroidRuntime(585): FATAL EXCEPTION: main
03-17 14:39:20.201: E/AndroidRuntime(585): java.lang.NullPointerException
03-17 14:39:20.201: E/AndroidRuntime(585):  at com.InternetGMBH.ThousandPS.Activities.TabGroupActivity.finishFromChild(TabGroupActivity.java:54)
03-17 14:39:20.201: E/AndroidRuntime(585):  at android.app.Activity.finish(Activity.java:3249)
03-17 14:39:20.201: E/AndroidRuntime(585):  at com.InternetGMBH.ThousandPS.Activities.TabGroupActivity.onBackPressed(TabGroupActivity.java:108)
03-17 14:39:20.201: E/AndroidRuntime(585):  at com.InternetGMBH.ThousandPS.Activities.BikesList$1.onClick(BikesList.java:67)
03-17 14:39:20.201: E/AndroidRuntime(585):  at android.view.View.performClick(View.java:2408)
03-17 14:39:20.201: E/AndroidRuntime(585):  at android.view.View$PerformClick.run(View.java:8816)
03-17 14:39:20.201: E/AndroidRuntime(585):  at android.os.Handler.handleCallback(Handler.java:587)
03-17 14:39:20.201: E/AndroidRuntime(585):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 14:39:20.201: E/AndroidRuntime(585):  at android.os.Looper.loop(Looper.java:123)
03-17 14:39:20.201: E/AndroidRuntime(585):  at android.app.ActivityThread.main(ActivityThread.java:4627)
03-17 14:39:20.201: E/AndroidRuntime(585):  at java.lang.reflect.Method.invokeNative(Native Method)
03-17 14:39:20.201: E/AndroidRuntime(585):  at java.lang.reflect.Method.invoke(Method.java:521)
03-17 14:39:20.201: E/AndroidRuntime(585):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-17 14:39:20.201: E/AndroidRuntime(585):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-17 14:39:20.201: E/AndroidRuntime(585):  at dalvik.system.NativeStart.main(Native Method)
03-17 14:40:25.580: I/Process(585): Sending signal. PID: 585 SIG: 9

i have addressed only one cycle of activity is working...after that i am getting force close...

only one time only the back button is working after that i am getting force close this is my logcat                                                                                03-17 14:59:42.431: I/System.out(640): Activity Being closeActivities.BikeOrder
03-17 14:59:42.431: I/System.out(640): Destroy called
03-17 14:59:43.180: I/System.out(640): Activity Being closeActivities.BikeDetailsDisplay
03-17 14:59:43.180: I/System.out(640): Destroy called
03-17 14:59:44.360: I/System.out(640): Activity Being closeActivities.BikesList
03-17 14:59:44.360: I/System.out(640): Destroy called
03-17 14:59:44.390: D/AndroidRuntime(640): Shutting down VM
03-17 14:59:44.390: W/dalvikvm(640): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
03-17 14:59:44.400: E/AndroidRuntime(640): FATAL EXCEPTION: main
03-17 14:59:44.400: E/AndroidRuntime(640): java.lang.NullPointerException
03-17 14:59:44.400: E/AndroidRuntime(640):  at com.InternetGMBH.ThousandPS.Activities.TabGroupActivity.finishFromChild(TabGroupActivity.java:54)
03-17 14:59:44.400: E/AndroidRuntime(640):  at android.app.Activity.finish(Activity.java:3249)
03-17 14:59:44.400: E/AndroidRuntime(640):  at com.InternetGMBH.ThousandPS.Activities.TabGroupActivity.onBackPressed(TabGroupActivity.java:108)
03-17 14:59:44.400: E/AndroidRuntime(640):  at com.InternetGMBH.ThousandPS.Activities.BikesList$1.onClick(BikesList.java:67)
03-17 14:59:44.400: E/AndroidRuntime(640):  at android.view.View.performClick(View.java:2408)
03-17 14:59:44.400: E/AndroidRuntime(640):  at android.view.View$PerformClick.run(View.java:8816)
03-17 14:59:44.400: E/AndroidRuntime(640):  at android.os.Handler.handleCallback(Handler.java:587)
03-17 14:59:44.400: E/AndroidRuntime(640):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-17 14:59:44.400: E/AndroidRuntime(640):  at android.os.Looper.loop(Looper.java:123)
03-17 14:59:44.400: E/AndroidRuntime(640):  at android.app.ActivityThread.main(ActivityThread.java:4627)
03-17 14:59:44.400: E/AndroidRuntime(640):  at java.lang.reflect.Method.invokeNative(Native Method)
03-17 14:59:44.400: E/AndroidRuntime(640):  at java.lang.reflect.Method.invoke(Method.java:521)
03-17 14:59:44.400: E/AndroidRuntime(640):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-17 14:59:44.400: E/AndroidRuntime(640):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-17 14:59:44.400: E/AndroidRuntime(640):  at dalvik.system.NativeStart.main(Native Method)
03-17 14:59:47.831: I/Process(640): Sending signal. PID: 640 SIG: 9

A: May this will help you. Here I am handling return button in Camera mode.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
    Bitmap photo = (Bitmap) data.getExtras().get("data");

    if(photo != null)
         imageView.setImageBitmap(photo);
}
}

You can also use:
@Override
public void onBackPressed() {
//here is your code
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get next recurrence of a Later schedule I am using later.js in order to create a simple schedule. I am trying to back this up with a mongo database for persistence.
Meteor.startup(function () {
  const current = Schedule.findOne({ name: 'send text reminders' });
  const interval = current.interval || 1;

  const recurrence = Later.parse.recur().every(interval).minute();

  Later.setInterval(function sendReminders() {
    Schedule.update({
      name: 'send text reminders'
    }, {
      $set: {
        nextRunAt: // get the next scheduled time.
      }
    });
  });
});

I've been looking through the docs but haven't found an area where they say how to get the next occurence of a schedule.
Is it possible to get the next scheduled run with later.js?


text:
Q: Highcharts can't read data with commas I have a problem on putting commas on the amount that I've be pulling from my DB.
I've added 'commaSeparateNumber function' and I works, but the problem is Highcharts can't read numbers with commas. I've tried using parsefloat but didn't work for me. Here's my function:
  function Filltbl(data) {

                        $.each(data, function () {
                            var html = "
" + this.SampleNo + "	" + this.SC_Com + "	" + this.SC_AP + "	" + this.SC_Cer + "	" + this.SC_Pd + "
";
                            $('#datatable').append(commaSeparateNumber(html));

                        });
                    }

And this one is for commaSeparateNumber function:
  function commaSeparateNumber(val) {
                while (/(\d+)(\d{3})/.test(val.toString())) {
                    val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
                }
                return val;
            }

And this is what I receive from Highcharts:
Highcharts Error #14

String value sent to series.data, expected Number

This happens if you pass in a string as a data point, for example in a setup like this:

series: [{
    data: ["3", "5", "1", "6"]
}]
Highcharts expects the data values to be numbers. The most common reason for this is that data is parsed from CSV or from a XML source, and the implementer forgot to run parseFloat on the parsed value.

For performance reasons internal type casting is not performed, and only the first value is checked (since 2.3).


text:
Q: Vue-router error: TypeError: Cannot read property 'matched' of undefined I'm trying to write my first Vuejs app. I'm using vue-cli and simple-webpack boilerplate.
When I add vue-router links to my app component I get this error in console

Error in render function: "TypeError: Cannot read property 'matched' of undefined"

Here is my code:
App.vue
<template>

Links

      <router-link to='/'>Home</router-link>
      <router-link to='/query'>Query</router-link>

      <router-view></router-view>

</template>

main.js
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
import routes from './routes.js'
import App from './App.vue'

const app = new Vue({
  el: '#app',
  routes,
  render: h => h(App)
})

routes.js
import VueRouter from 'vue-router';
let routes=[
  {
    path: '/',
    component: require('./Components/Home.vue')
  },
  {
    path: '/query',
    component: require('./Components/Query.vue')
  }
];

export default new VueRouter({routes});

A: On my Vue file I had the following code:
Then, I modified my app.js file, and place the following code:
import router from './Router/router.js'

const app = new Vue({
    el: '#app',
    router
});

A: vue & vue router & match bug & solution
match bugs

solution

name must be router

https://stackoverflow.com/a/44618867/5934465

OK

import default module bug

import default module no need {}!

A: The name when you add it to Vue must be router.
import router from './routes.js'

const app = new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

If, for whatever reason, you want to call the variable routes you could assign it this way.
import routes from './routes.js'

const app = new Vue({
  el: '#app',
  router: routes,
  render: h => h(App)
})

A: Adding to this, if you are putting the routes in the same page instead of importing it, It must be declared before the Vue component render.
Like this:-
const router = new VueRouter({
  mode: 'history',
  routes:[
    { path: '/dashboard', component: Dashboard},
    { path: '/signin', component: Signin}
  ]
});

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

Not like this :
new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

const router = new VueRouter({
  mode: 'history',
  routes:[
    { path: '/dashboard', component: Dashboard},
    { path: '/signin', component: Signin}
  ]
});

A: Just to add my typo that caused this. I forgot the {} on the import
import { router } from './routes.js'  //correct
import router from './routes.js'   //causes same error

A: If you put some customized codes in router/index.js,
make sure you still export default router at the end.
const router = new Router({
  mode: 'history'
});
export default router;

A: I have faced with this issue same as you. Then I realized at the end of the index.js that I forgot to add :
export default router

Then it solves the issue in my case.


text:
Q: Using nightwatch.js how can i select dynamically generated item with a dynamically provided value I've   got a problem to identify dynamically generated(using JQuery or some script) element present in a list box . I want to select a particular market value which i pass dynamically .
the code i've used so far is
browser.useXpath().waitForElementVisible('.//*[@id="NIRPaymentReasonDropDown_1"]', 1000)

browser.useXpath().click('//*[@id="NIRPaymentReasonDropDown_1"]/span[1]/span/span[1]')
           .click('//*[@id="NIRPaymentReason_1_listbox"]/li[text()="' + pageValues.market + '"]')

here pageValues.market is a dynamically provided value.
Inshort , i want to know how to generate click event on the dynamically generated listbox item with a dynamically provided value. using nightwatch.js
kindly help me out to solve this problem

A: After several trial and errors , i succeded with this solution to handle the newly opened tabs of the same webpage
 browser.windowHandles(function(result) {
                            var authorizePopup = result.value[1];
                            this.waitForElementVisible('#confirmation-modal', 2000)
                            this.switchWindow(authorizePopup);
                            this.assert.containsText(".modal-title", "Payment Details");
                            this.click('#confirm-checkbox')
                                .click('#submit-payment-btn')
                        })

I want  a better way to store the inspected elements in page objects for this newly created tab ..can you give me any suggestions or comments


text:
Q: Extracting and Organizing Text From A PDF I'm currently trying to scrape a bunch of information from PDF pages. I have managed to get some text extracted but haven't been able to extract everything or the format has been difficult to work with. I'm using this example to kind of extract traffic data into a dataframe:
https://www.bts.gov/sites/bts.dot.gov/files/states2020/Alabama.pdf
I want to try and get a dataframe that has all the information organised accordingly. For example, from the information on page 1 I want to have a row that contains the following:

State
Miles of Public Road
Major Airports
Bridges
Major Water Ports
Miles of Freight Railroad
Number of MPOs
Miles of Waterway

Alabama
100962
9
16130
2
3272
14
1270

This is just an example, I want to extend this for the whole document. I have 2 different forms of code, the first I think is able to get a good amount of information but is very very jumbled and the second doesn't actually contain all the information:
import fitz

with fitz.open("US PDF/Alabama.pdf") as doc:
    text = []
    for page in doc:
        text += page.getTextBlocks()

# print(text)

Second:
import PyPDF2

def convert_pdf_to_text (document):
    read_pdf = PyPDF2.PdfFileReader(document, strict=False)
    number_of_pages = read_pdf.getNumPages()

    alltext1=""
    for page_number in range(1,2):
        page = read_pdf.getPage(page_number)
        alltext1 += page.extractText()

    return alltext1.replace("\n", "")

convert_pdf_to_text('US PDF/Alabama.pdf')

However, I'm not quite sure how to go about going so I can extract all of the data in a good way. Is there any adaptation or recommendation for me to go about doing this?
Cheers

A: Probably late to answer this. But PyMuPDF has all batteries included to solve your problem: it is just a matter of picking the right text extraction features.
Your file requires to extract text together with all its properties: position information, font size, etc., even text color.
In addition, the file creator has encoded text in non-reading order sequence, so sorting by position is also required.
Having done this, we must find a way to programmatically uncover some structure, by which text has been organized. Looks like a column-based approach leads to the best result.
To find appropriate column borders, I determined the most frequent left border text coordinates and assumed these to be delimiters. For the first page, this looks like so:
Printing the text column-wise yields this result - which is at least a good start for further refinement:
---------- page 0 of Alabama.pdf ----------
Alabama
Transportation by the Numbers
Transportation Infrastructure
January 2020

Miles of Public Road
100,962
ROAD CONDITION
Good or Fair
88.1%
Roads with acceptable pavement
ride quality based on International
Roughness Index

Bridges
16,130
BRIDGE DECK AREA CONDITION
Good
37.5%
Fair
60.0%
Poor
2.5%

Miles of Freight Railroad
3,272

Miles of Waterway
1,270

Major Airports
9
Includes Federal Aviation
Administration Part-139 public use
airports.

Major Water Ports
2
Includes ports ranked in the top 150
ports by tonnage in 2017.

Number of MPOs
NUMBER OF MPOs
14


text:
Q: How to find out what is causing my white screen of death? I have an Ionic app. It's works well for a couple of weeks, then it stops. I get the splash screen followed by the white screen of death. When I debug using chrome://inspect into the app I get the following message in the console:

No Content-Security-Policy meta tag found. Please add one when using
  the cordova-plugin-whitelist plugin.

If I clear all data on my app, it starts working, and I get the same message when I debug a working app on another device, so I don't think it's the plugin at fault. However, I have used the plugin to explore the white-screen problem, because I can get the white screen of death if I add the following to my index.html (a content security policy that prevents loading resources from any source):
<meta http-equiv="Content-Security-Policy" content="default-src 'none'">

When I do that, I get error messages like this in the console:

Refused to load the stylesheet
  'file:///android_asset/www/lib/ionic/css/ionic.min.css' because it
  violates the following Content Security Policy directive: "default-src
  'none'". Note that 'style-src' was not explicitly set, so
  'default-src' is used as a fallback

And when I change the tag to this:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

I get this in my console:

Refused to apply inline style because it violates the..etc

And I also get

EvalError: Refused to evaluate a string as JavaScript because
  'unsafe-eval' is not an allowed source of script...etc"

But now, instead of a white screen, my exception handler is catching the problem and reporting it.
From this, I deduce that the absence of files causes my white screen, because my exception handler works if all files are loaded.
I can get rid of all errors in my console using this security policy:
<meta http-equiv="Content-Security-Policy"
          content="style-src 'self' ionic.bundle.min.js 'unsafe-inline';
                   script-src 'self' console-via-logger.js 'unsafe-eval';
                   img-src 'self' ionic.bundle.min.js data:">

So I am wondering if there is a way to catch the exception in my application at an earlier stage so that I can diagnose the original white-screen problem? I think it must be something in the data preventing a file being loaded, but how could that be?

A: To test Kerri Shotts theory that a JavaScript error is getting in the way of app startup, I added a throw to my app.js file:
(function () {
    'use strict';

    throw ('test');

    //setting up the dependencies
    var app = angular.module('app', [..etc..]
    ]);

})();

Sure enough - white screen of death
Next I added the window.onerror script to my index.html:
<body data-ng-app="app">
    <script>
        (function () {
            window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
                alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber
                + ' Column: ' + column + ' StackTrace: ' + errorObj);
            }
        }());
    </script>
    ....etc

I had to add 'unsafe-inline' to the Content Security Policy to get that script to run, but once I did that I got an alert with the error message instead of just a white screen.
My CSP:
<meta http-equiv="Content-Security-Policy"
          content="style-src 'self' ionic.bundle.min.js 'unsafe-inline';
                   script-src 'self' console-via-logger.js 'unsafe-eval' 'unsafe-inline';
                   img-src 'self' ionic.bundle.min.js data:">


text:
Q: data duplication during parallel calls the same service springboot I have a Controler he call a serviceA
@Autowired
ServiceA serviceA;

public @ResponseBody
ResponseEntity<List<A>> getlistA(@RequestBody RequestA requestA) {
    List<RequestA> requestsListA = new ArrayList<>();
    requestsListA.add(requestA);

    return new ResponseEntity<>(serviceA.getListA(requestsListA), HttpStatus.OK);
}

And the serviceA   is annotated with @Service
@Scope
public class ServiceA {
…
}

When I send two requests in parallel  I find the data from the response of the first request in the response of the second request.
Example :
If I run two requestd not in parallel:

*

*respons of request A:     object1, object2, object3

*respons of request B:     object4 , object5

If I run two requestd in parallel:

*

*Result Query A: object1, object2, object3, object4, object5

*Result Query B: object1, object2, object3, object4, object5

If I have a class that is annotated with @Service, Spring create one instance of this to be shared in the JVM?
Or will every consumer class that autowires the service will get a new instance of the service?

Is it possible that for each time when I call the service it is forced to create a new instance

thank you

when I send two requestd in parallel i have all response merged . it's like singleton

A: It sounds like your issue might be inside of the serviceA. Whenever you use the @Service annotation on a class you can also define the spice of the component bean that service is creating by using the @Scope annotation. Without adding this last scope part the default for service is a singleton bean. If you scope it you can change this to be a prototype and that will give you one instance per request. With all this said, I don't think this is the way to go for you.
The real issue is that it sounds like you have a data leak between API calls which must mean you are updating a global/static variable somewhere which is causing the issue you are seeing. Please provide more detail on the service logic for further help.


text:
Q: Git - what is causing "warning: Negative patterns are ignored in git attributes" When pushing on my server the post-receive hook runs a simple git clone command.
The command returns the following warning and I don't know what it means or how to resolve it. Googling the error gave only results concerning gitattributes and I haven't configured any attributes. My .gitignore file also has no exclamation marks or negative values inside.
remote: Cloning into '/var/www/html/gitrep'...
remote: warning: Negative patterns are ignored in git attributes
remote: Use '\!' for literal leading exclamation.

A: Do not mix gitignore and gitattributes.
One of your gitattributes file use a negative pattern that is not allowed.
Search for one of those files:

*

*.gitattributes inside any folder of your repository

*$GIT_DIR/info/attributes

*$(git config --get core.attributesFile)

*$XDG_CONFIG_HOME/git/attributes

*$HOME/.config/git/attributes

*$(prefix)/etc/gitattributes
One of them use a negative pattern. You just need to fix it (by adapting your gitattributes model or escaping the exclamation point)


text:
Q: Unhandled error in POST /order-products: 500 Error: Navigational properties are not allowed in model data I am using loopback 4 relations. I have three models product, order, and orderProducts. The relationships are as follows

*

*order has many OrderProducts

*Product has many OrderProducts

*OrderProducts belongs to product.

But when I try post request on OrderProducts it is giving this error :

500 Error: Navigational properties are not allowed in model data
  (model "OrderProducts" property "product_id")

Here is my code. Thank you in advance
order.model.ts
import { Entity, model, property, hasMany} from '@loopback/repository';
import {OrderProducts} from './order-products.model';

@model({ settings: { strict: false } })
export class Orders extends Entity {
  @property({
    type: 'number',
    id: true,
    generated: true,
  })
  order_id?: number;

  @property({
    type: 'number',
    required: true,
  })
  total: number;

  @property({
    type: 'string',
  })
  get: string;

  @hasMany(() => OrderProducts, {keyTo: 'order_id'})
  orderProducts: OrderProducts[];
  // Define well-known properties here

  // Indexer property to allow additional data
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [prop: string]: any;

  constructor(data?: Partial<Orders>) {
    super(data);
  }
}

export interface OrdersRelations {
  // describe navigational properties here
}

export type OrdersWithRelations = Orders & OrdersRelations;

product.model.ts
import { Entity, model, property, hasMany } from '@loopback/repository';
import { OrderProducts } from './order-products.model';

@model({ settings: { strict: false } })
export class Product extends Entity {
  @property({
    type: 'number',
    id: true,
    generated: true,
  })
  product_id?: number;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @property({
    type: 'string',
  })
  desc?: string;

  @hasMany(() => OrderProducts, { keyTo: 'product_id' })
  orderProducts: OrderProducts[];
  // Define well-known properties here

  // Indexer property to allow additional data
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [prop: string]: any;

  constructor(data?: Partial<Product>) {
    super(data);
  }
}

export interface ProductRelations {
  // describe navigational properties here
}

export type ProductWithRelations = Product & ProductRelations;

order-product.model.ts
import {Entity, model, property, belongsTo} from '@loopback/repository';
import {Product} from './product.model';

@model({settings: {strict: false}})
export class OrderProducts extends Entity {
  @property({
    type: 'number',
    id: true,
    generated: true,
  })
  o_id?: number;

  @property({
    type: 'number',
    required: true,
  })
  quantity: number;

  @property({
    type: 'number',
  })
  order_id?: number;

  @belongsTo(() => Product)
  product_id: number;
  // Define well-known properties here

  // Indexer property to allow additional data
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [prop: string]: any;

  constructor(data?: Partial<OrderProducts>) {
    super(data);
  }
}

export interface OrderProductsRelations {
  // describe navigational properties here
}

export type OrderProductsWithRelations = OrderProducts & OrderProductsRelations;

A: I think the problem might be caused by the naming convention. LoopBack 4 uses camelCased variable name by default.
For any relation, there are three important attribute: the source key, foreign key, and the relation name.
Here's the link to the related files: Relation Metadata. For hasMany and hasOne relations, the source key defaults to the id property, which is Order.order_id and Product.product_id in you case. And the target key (foreign key) defaults 'TargetModelName' + 'Id'. Which is orderProducts.orderProductsId. And the default relation name is the one you decorated with @hasMany decorator, which is orderProducts in your example.
You have keyFrom to deal with the customized names so the two hasMany relations are fine.
For belongsTo relation, the default source key is the id property of the target model, which is Product.product_id in your case. The source key is the one decorated by @belongsTo decorator, which is OrderProducts.product_id. And the default relation name is .. here is the tricky part, it is product_id in you case. Idealy, the source key is supposed to be OrderProducts.productId, and the default relation name will be product. In your case, the property has the same name as your relation name. This is caused by the way LB4 generates relation names. That's why it complains the navigational properties.
To fix it, you need to change two files, orderProducts.model.ts:
... // other properties

@belongsTo(() => Product, {name: 'product'}) // use a different name from the property name
  product_id: number;                        // let's use 'product' here
...

and OrderProductsRepository:

export class OrderProductsRepository extends DefaultCrudRepository<
  OrderProducts,
  typeof OrderProducts.prototype.o_id,
  OrderProductsRelations
> {
  public readonly product: BelongsToAccessor<  // use the relation name
    Product,
    typeof OrderProducts.prototype.o_id
  >;
  constructor(
    @inject('datasources.db') dataSource: DbDataSource,
    @repository.getter('ProductRepository')
    protected productRepositoryGetter: Getter<ProductRepository>,
  ) {
    super(OrderProducts, dataSource);

// make sure the name is correct
    this.product = this.createBelongsToAccessorFor(
      'product',
      productRepositoryGetter,
    );

// make sure the name is correct
    this.registerInclusionResolver(
      'product',
      this.product.inclusionResolver,
    );
  }
}

Reference: BelongsTo Relation Metadata.
If you have any questions about LB4, you can also open an issue on our GitHub community.


text:
Q: Intersection of plane with quadratic regression surface A quadratic OLS regression with two predictors is defined as:
$Z = b_0 + b_1X + b_2Y + b_3X^2 + b_4XY + b_5Y^2 + e$        (1)
If this regression surface is plotted, it can look like this ($b_0=10, b_1=-.15, b_2=.82, b_3=.15, b_4=.33, b_5=-.30$):

Now I want to derive the two-dimensional functional form of several intersections with a vertical plane. For two special cases, the slopes of this intersection can be easily calculated:

*

*For the solid black line in the first Figure (where X = Y): the linear slope of this line is $a_1 = b_1 + b_2$, and the quadratic component is $a_2 = b_3 + b_4 + b_5$

*For the dashed black line (where X = -Y): the linear slope is $a_3 = b_1 - b_2$, and the quadratic component is $a_4 = b_3 - b_4 + b_5$.

Question: How can I derive the functional form of the intersection with arbitrary vertical planes?
Specifically, I am interested of the intersection at a particular plane. Consider following contour plot of the same regression surface:

The solid black line is the first principal axis, which is defined by following equations ($p_{10}$ = intercept, $p_{11}$ = slope):
$p_{11} = (b_5 - b_3 + \sqrt{(b_3 - b_5)^2 + b_4^2}) / b_4$
$p_{10} = [(b_1 b_4 - 2 b_2 b_3) / (4 b_3 b_5 - b_4^2)] - p_{11} [(b_2 b_4 - 2 b_1 b_5) / (4 b_3 b_5 - b_4^2)]$
In the specific example, $p_{10} = 1.23$ and $p_{11} = 0.33$.
Now, what is the form of the surface along this line?
I am interested in a solution for the first principal axis, as well as a general solution for arbitrary vertical planes.

A: Any vertical plane can be described by an equation of the form $ax+by = c$. Dividing $a,b,c$ by some common number doesn't change the plane. So, after doing this division, if necessary, we can assume that $\sqrt{a^2 + b^2} = 1$.
Points on this plane can be described by parametric equations $x=ca + tb, y=cb - ta$. You can check that points $(x,y)$ given by these equations satisfy the plane equation for all $t$.
If you substitute $X=ca + tb, Y=cb - ta$ into your surface equation, you get a formula for $Z$ as a function of $t$, which represents the curve of intersection.
The curve will be a quadratic function of $t$, actually, which means that it's a parabola.


text:
Q: Can this question be solved using combinatorics or permutations and combinations? How many positive integers less than $1000$ have the property that the sum of the digits of each such number is divisible by $7$ and the number itself is divisible by $3$?
This question has been before, but I saw a solution on Quora which intrigued me.
The solution is-

Thanks for the A2A
This is an awesome question i must say,
But i will make it easier for you. Its said the sum of digits should
  be divisible by $7$ as well as $3$. So sum of digits should be $21$. Only 1
  possible case
So $(9-a) + (9-b) + (9-c) =21$.
We need to find whole number solutions to this
So, $a+b+c = 6$ , hence there will be ${}^8C_2$ possible numbers, or $28$ such
  numbers
Hope it helps

https://www.quora.com/How-many-positive-integers-less-than-1000-have-the-property-that-the-sum-of-the-digits-of-each-such-number-is-divisible-by-7-and-the-number-itself-is-divisible-by-3-1/answer/Atreya-Roy?share=8f02b880&srid=uYqRV
Can someone explain what he did?

A: To start off, the question states that the sum of the digits of the number is divisible by $7$. It also states that the number itself is divisible by $3$. There's a divisibility rule for $3$ which states that if a number is divisible by $3$, the sum of its digits will also be divisible by $3$. Since $3$ and $7$ are co-prime, we can say that the sum of the digits is then divisible by $3 \times 7 = 21$
In the next part, he says that the digits of the number are: $9 - a, 9 - b,$ and $9 -c$. Since the digits of a number range from $0$ to $9$, it's fine to think of the digits as he suggested, because $9 - a$ can take on the same range of values ($0$ to $9$) as just $a$. The one thing to be careful about here is that we need to make sure $9 - a$ does not equal $0$, which happens if $a = 9$, because this will mean our number is actually $2$ digits.
Now that we've chosen our digits to be $9 - a, 9 - b, 9 - c$, we take the sum of these and equate it to $21$. Rearranging a bit, we end up with $a + b + c = 6$. Take note that we eliminate the case that $a = 9$ now, and don't have to consider that case anymore.
Here, we can use the stars and bars method of combinatorics. Consider that there are $6$ stars that we need to distribute between $a, b, c$. We then need $3 - 1 = 2$ bars to distribute them. The total number of ways to distribute $6$ stars and $2$ bars is given as $6 + 2 \choose 2$ = $\frac{8!}{6!2!} = 28$

A: It's a well known trick that a number is divisible by $3$ if and only if the sum of the digits is divisible by $3$.  So saying the sum of the digits is divisible by $7$ and the number "itself" is divisible by $3$ is just an obscure way of saying the sum of the digits is divisible by $3$ and by $7$.
So the sum of the digits is divisible by $21$.  The numbers are less than $1000$ so the sum of the digits is at the very most $9+9+ 9$.  So the sum of the digits are divisible by $21$ but at most $27$ so (assuming we aren't counting $0$) the sum of the digits is exactly $21$.
So the question is simply.  How many numbers less than 1000 have digits that add to $21$.
As $1000$ is obviously not one of them, the number can only have at most three digits, so the poster assumed the three digits were $(9-a),(9-b), (9-c)$ (where $a,b,c$ can be $0$ through $9$).  So the sum of the digits is $9 -a + 9-b + 9-c = 21$.
Or in other words $a + b + c = 6$.
So the answer is the same as how many ways are there to chose $a,b,c$ from $0,1,2,....9$ where $a + b + c =6$.
At this point the poster assumes that answer is well known to be ${8 \choose 2}$
This is determined by the Stars and Bars method. To get $a + b + c= 6$, you can imagine you have six pebbles, and two divider.  You can lay out $a$ pebbles and then place a divider.  That indicates what $a$ is.  Then you can lay out $b$ more pebbles and place the second divider.  This indicates what $b$ is.  You lay out the remaining pebbles (if any) and this indicates what $c$ is.
So you have $6+2=8$ positions, and you have chose $2$ positions to place the dividers and $6$ positions to place the pebbles and there are ${8 \choose 2}$ ways to do this and each one represents a way do choose $a + b + c = 6$.
So there are ${8\choose 2 } = \frac {8*7}2 = 28$ such numbers.
The range from
$a,b,c =(0,0,6)\mapsto 993$
$a,b,c =(0,1,5)\mapsto 984$
......
$a,b,c = (4,1,1)\mapsto  588$
$a,b,c = (4,2,0)\mapsto  579$
$a,b,c = (5,0,1)\mapsto  498$
$a,b,c = (5,1,0)\mapsto  489$
$a,b,c = (6,0,0)\mapsto  399$


text:
Q: Django backend authentication with NextJS frontend form - best practices I have an API hub that I've built in Django and a frontend end application I've built in NextJS. I'm currently working on authenticating to the Django API in Nextjs and I'm curious about best practices.
Currently, the NextJS app posts the users username/password to an endpoint. This endpoint either returns the users token or the error illustrating the issue.
React
  const login = async () => {
    let token = await axios.post('/api/accounts/', {
      email: email,
      password: password
    }).then(r => r.data.token).catch(function (error) { console.log(error) })

      if (token) {
        router.push({
            pathname: '/home/',
            query: { token: token },
          })
        }
      }

nexjs server api/accounts
export default async (req, res) => {
  if (req.method === 'POST') {
    try {
      // retrieve payment intent data
      const {data} = await axios.post('https://website/api/api-token-auth/', req.body)
      res.status(200).send(data)
    } catch (err) {
      res.status(500).json({ statusCode: 500, message: err.message })
    }
  } else {
    res.setHeader('Allow', 'POST')
    res.status(405).end('Method Not Allowed')
  }
}

Django API
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def obtain_auth_token(request):
    email = request.data.get("email")
    password = request.data.get("password")
    if email is None or password is None:
        return Response({'error': 'Please provide both email and password'},
                        status=HTTP_400_BAD_REQUEST)
    user = authenticate(email=email, password=password)
    if not user:
        return Response({'error': 'Invalid Credentials'},
                        status=HTTP_404_NOT_FOUND)

    token, _ = Token.objects.get_or_create(user=user)
    return Response({'token': token.key},
                    status=HTTP_200_OK)

Once I receive the token I push the user to the homepage.
My questions are:

*

*Is how I'm authenticating users a good way to do this? Am I overlooking something? This is the first time I've attempted to authenticate to something I've built so I want to get this right.

*How should I store this token? What is "best practice" when it comes to authentication creds? I've thought about passing the token around to every component that needs it. I've also peeked at using LocalStorage but again am unsure what most people do in these situations.
Any help you all can provide would be much appreciated!
Thanks in advance!


text:
Q: How do I display a generated QR code in flask I am making a web app that generates a QR code using input from the user and saves it into a specified file. After the QR code is saved, It should display the generated QR code in a small box next to the input box.
I am attempting to do this by having a GET submit button that goes to this route but I receive an error every time I click it.
The first block of code is for receiving the input and making a QR code out of it, and the second is my attempt to send back the finished PNG and display it.
Python Code:
@app.route('/', methods= ['POST'])
def textfield():
    text = request.form['text']
    processed_text = text
    if processed_text == '':
       flash("Please enter a value!")
    else:
       QR(processed_text)
    return render_template('base.html')

@app.route('/QR', methods= ['GET'])
def QRimage(text):
    im = Image.open(f'{text}.png')
    data = io.BytesIO()
    im.save(data, "PNG")
    encoded_img_data = base64.b64encode(data.getvalue())
    img_data = encoded_img_data.decode('utf-8')
    return render_template('base.html', value=img_data)

Here is the HTML to attempt to display the image:
<img id="picture" src="data:image/jpeg;base64,{{ img_data }}">

And the GET button that routes to /QR:
<form action="/QR" method="GET">
<button type="submit" type="button">QR Button</button>

A: Flask looks for static files in the static folder which is the default.
use flask.send_from_directory(directory, filename, **options) if you want to serve files from another directory. This is a secure way to quickly expose static files.
 @app.route('/QR', methods= ['GET'])
    def QRimage(text):
        return send_from_directory(app.config['UPLOAD_FOLDER'], filename);

Reference:
API — Flask Documentation (1.1.x) (2021). Available at: https://flask.palletsprojects.com/en/1.1.x/api/#flask.send_from_directory (Accessed: 24 April 2021).


text:
Q: Disable NSLog for CocoaPods I am using several CocoaPods in my project. Some of them are outputting strings to the console via NSLog().
How can I disable all logging from CocoaPods?
Also, is there a way to do so while still keeping all of my NSLogs enabled?
Note: it seems like this feature may resolve the issue, but are there alternatives I can use meanwhile?
Update: looks like this feature was requested.


text:
Q: GOENV can only be set using the OS environment I want to set the GOENV path and use the following command go env -w GOENV=D:\go\env, but he returns go env -w: GOENV can only be set using the OS environment how should I set the GOENV custom path?The computer environment of windows11

A: What shell are you using ? cmd.exe or Powershell ?
In cmd.exe :
set GOENV=D:\go\env

In Powershell :
$env:GOENV="D:\go\env"


text:
Q: Image storage in chrome local storage I'm working on a chrome extension for which I'm fetching image from an api. I'm storing that image in the chrome local storage using the url directly like
localStorage.setItem('image_url', "https://images.unsplash.com/photo-1461456523134-43960ad9fce2?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&s=cd4b561a5816f51c992f7965bbc6b011");
It's working perfectly fine. Like it fetches images instantly from the local storage. But I have read in many stackoverflow solution is to first convert the image to base64 format and then save it in the form of data_url. I wanna know what's the con in the approach I'm following? And what's the difference between the approaches?
And what would be the right approach to follow?


text:
Q: Micro SDHC 32GB -> USB -> Arduino The majority of Arduino Projects I've seen that involve using an SD card use 1 pin for ground and 4 for communicating and 1 for powering(3.3v)(if I'm not mistaken), when you insert said card into an USB adapter and then into the PC it use 1 for ground and 1 for TO and 1 for FROM and 1 to power(5v)(If I'm again, not mistaken)

*

*I wish to attach one female standard USB to an arduino and communicate through that to a micro SD card that sits in an USB adapter. - What obstacles must I overcome?

*Background, I shall remove & attach said USB adapter with SD inside of it a lot, taking it out of SD adapter and then into an USB adapter and then back is going to get annoying very fast.

*If I'm wrong then please correct me.

A: 1) You are mistaken.  USB uses a power, ground, and a differential pair of data signals which are used together as mirror opposites for both sending and receiving.  (They also get used slightly independently for device detection)
2) To host a USB storage device with an Arduino you will need to add an embedded USB host chip or USB host "shield".  This will be a much more expensive solution than simply using a socket for the SD card.
Instead of doing that, you might want to come up with a scheme for transferring data to and from the Arduino by some other means (and potentially having the Arduino write it to the card).  Even with USB, you have to make sure that the system accessing the device (Host shield or PC) has unmounted the device before unplugging it ("safely remove", "eject" etc) - that will be annoying too.


text:
Q: Using Web Setup Project for multiple types of projects I am trying to a create an installer for my web application. My solution contains several projects. They include:

*

*Class library project (referenced by the web application)

*Web Application

*Windows Service

*Web Services project

*Database project (execute update script)

I also have an unmanaged dll (crystal reports) in my web application project, so I might have to do some editing of the registry.
I ideally want to be able to use a web setup project to install the whole solution. Can this be done? Is there a better method/solution?

A: The short answer is "Yes" it can be done.
Other better solution? Well, I'm not a huge fan of VS.NET's installer/setup, can be kind of bulky, 3rd parties could be better at a price. Having said that, it should be able to satisfy your requirements.


text:
Q: don't want to expose $http in the controller There is related question about processing $http in a service, but I wanted to elaborate slightly. I would like my controller to be able to execute service calls using API similar to the Angular $http API:
$scope.login = function(user) {
  securityService.login(user).success(function(data) {
    $scope.data = data;
  }).error(function(data) {
    $scope.error = data;
  });
};

That's a nice readable API. On the surface, all I would need to do in the service API is:
return {
  name : 'User Service',
  login : function(user) {
    return $http.post("/api/login", user);
  }
};

Great, it returns the promise and the success and error messages come with. But... What if I want to deal with the success and failure cases in the service? I want to maintain the nice, readable service API. In this case, maybe I'd want to preserve the user so that I could expose methods like securityService.currentUser() or `securityService.isLoggedIn()'.
I tried the $http.post().then(...) promise API, but those return the entire HTTP response. Again, I want to isolate HTTP to the services and maintain a similar concrete callback API.

A: You could make your own promise in login using angular's $q:
var deferred = $q.defer(),
    promise = deferred.promise;

$http.post("/api/login", user).success(...).error(...)

return promise;

Within the success/failure of the $http promise in your service, resolve/reject your deferred object.
Edit:
Expanding upon the $http.post:
$http.post("/api/login", user).success(function(data) {
  if (data == "foo") { // success case?
    deferred.resolve('you logged in!');
  } else {
    deferred.reject('something really bad happened!');
  }
})

A: I just ran a test case and it seems that if I return the promise from the service API like this:
return $http.post("/api/login", user).success(...).error(...)

I can also do the same in the controller:
service.login(user).success(...).error(...)

and both get called, the service first and the controller second. That's perfect!


text:
Q: Handling iPhone orientation change in OpenGLES I'm having a problem with my OpenGLES views when the device orientation changes. I'm using Jeff Lamarche's Xcode template.
If the AutoresizeMask is set, - (void)layoutSubviews is called on the GLView. When this happens the objects I'm drawing disappear. The OpenGL view is still partly working as I can change the background colour and see the change.
If the AutoresizeMask is not set, the view rotates and the OpenGL objects are still visible but then the view is the wrong size.
This shows that there's something in layoutSubviews that is causing a problem when called more than once.
Here's some very basic code for drawView which shows the problem
- (void)drawView:(UIView *)theView
{
    Vertex3D    vertex1 = Vertex3DMake(0.0, 1.0, -3.0);
    Vertex3D    vertex2 = Vertex3DMake(1.0, 0.0, -3.0);
    Vertex3D    vertex3 = Vertex3DMake(-1.0, 0.0, -3.0);
    Triangle3D  triangle = Triangle3DMake(vertex1, vertex2, vertex3);

    glLoadIdentity();
    glClearColor(0.7, 0.7, 0.7, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColor4f(1.0, 0.0, 0.0, 1.0);
    glVertexPointer(3, GL_FLOAT, 0, &triangle);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableClientState(GL_VERTEX_ARRAY);
}

When the device is rotated with this code the triangle on the screen disappears. Re-orienting back to portrait doesn't make it reappear either.
Should I not allow GLView's to be re-oriented or is this a bug in my OpenGL code?

A: Correct me if I'm wrong, but I believe in layoutSubviews you need to delete and re-create your framebuffer to match the new size.  If you go here (I presume you are enrolled in the Apple developer program) and check out the video "Best Practices for OpenGL on iOS 5" the speaker talks about rotation, how it was previously suggested to do it manually with your OpenGL because of performance issues, but goes on to say that now it can handled easily by using the built-in rotation.  The speaker also mentions that if you are using the GLKView it will resize the framebuffer on your behalf.
Also, I'm not sure what you mean by "a lot of developers are having problems with this".  Some cursory searches with Google and inside Stack Overflow haven't revealed to me anyone else having this problem; I suspect there may be something wrong with your code specifically.
I also followed your link to Jeff Learche's Xcode Template and the link to the Xcode 4 template is broken--this may be because it is from May 2011.  Perhaps simply look into the GLK framework, if your OpenGL needs are not too specialized?


text:
Q: How to subtract two time by converting them to get long
Possible Duplicate:
How can I calculate a time span in Java and format the output?

How to subtract two time by converting them to get long and convert it back to time again?
I tried subtracting two time by converting them to long.
    Long timeSpan = Long.valueOf(timespan.getValue().toString()) * 60;
    Long checkVar = (date.getTime() - testStartTime.getTime()) / 1000;

Now how do i convert the resultant long into time?
That is if the result long is say 30 min i want it to be shown 00:30:00 .
How can i do this?
Thanks in advance

A: It's trivial to convert your time in seconds into the individual HH:MM:SS components:
int h = checkVar / 3600;
int m = (checkVar / 60) % 60;
int s = (checkVar % 60);

String time = String.format("%02d:%02d:%02d", h, m, s);

A: As has already been suggested, take a look at Joda Time
PeriodFormatter timeFormatter = new PeriodFormatterBuilder().printZeroAlways().
                appendHours().appendSeparator(":").
                appendMinutes().appendSeparator(":").
                appendSeconds().toFormatter();

DateTime startTime = new DateTime(1972, 3, 8, 15, 30);
DateTime endTime = new DateTime();

Period period = new Period(startTime, endTime);
int days = period.getDays();
int months = period.getMonths();
int years = period.getYears();

System.out.println(period.toString(timeFormatter));

A: Date elapsed = new Date(checkVar);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String formatedTime = sdf.format(elapsed);


text:
Q: Plone 5 TinyMCE, Can't select a folder for uploading image At Plone 5, I can't select a folder for uploading image.
How can I select another folder for uploading image?

A: I mistook this question. This problem was related my env.


text:
Q: R doesn't work properly with conda installation I tried installing r with conda and every time I try that it doesn't work.
conda create --name test2 -c conda-forge r-base r-seurat

I assumed that by using conda-forge channel, it will install the most updated version. What happened is that it installs the oldest version of R which is 3.6.1
At the same time, the "Seurat" package requires a newer version of R than 3.6.1
So, I specified a version of R in that code and it didn't work too
conda create --name test2 -c conda-forge r-base=4.1.1

This worked for installing a newer R version but when I try activating R on that environment, it gives me an error

Error in library(beepr) : there is no package called 'beepr'

So, I opened rstudio from that environment and tried installing (beepr) package and it didn't work! It tries to install other packages as a requirement for it and at the same time gives the same error of not having "beepr" installed.
That's one of the packages it tried to install.

Warning in install.packages : installation of package 'glue' had non-zero exit status Error in library(beepr) : there is no package called 'beepr' Execution halted

and it does that with the rest of packages required.
That's the error I get from installing beepr

also installing the dependencies 'glue', 'magrittr', 'stringi', 'stringr', 'audio' trying URL 'https://cran.rstudio.com/src/contrib/glue_1.4.2.tar.gz' Content type 'application/x-gzip' length 99049 bytes (96 KB) ================================================== downloaded 96 KB trying URL 'https://cran.rstudio.com/src/contrib/magrittr_2.0.1.tar.gz' Content type 'application/x-gzip' length 265580 bytes (259 KB) ================================================== downloaded 259 KB trying URL 'https://cran.rstudio.com/src/contrib/stringi_1.7.4.tar.gz' Content type 'application/x-gzip' length 7599762 bytes (7.2 MB) ================================================== downloaded 7.2 MB trying URL 'https://cran.rstudio.com/src/contrib/stringr_1.4.0.tar.gz' Content type 'application/x-gzip' length 135777 bytes (132 KB) ================================================== downloaded 132 KB trying URL 'https://cran.rstudio.com/src/contrib/audio_0.1-8.tar.gz' Content type 'application/x-gzip' length 57390 bytes (56 KB) ================================================== downloaded 56 KB trying URL 'https://cran.rstudio.com/src/contrib/beepr_1.3.tar.gz' Content type 'application/x-gzip' length 922244 bytes (900 KB) ================================================== downloaded 900 KB Error in library(beepr) : there is no package called 'beepr' Execution halted Warning in install.packages : installation of package 'glue' had non-zero exit status Error in library(beepr) : there is no package called 'beepr' Execution halted Warning in install.packages : installation of package 'magrittr' had non-zero exit status Error in library(beepr) : there is no package called 'beepr' Execution halted Warning in install.packages : installation of package 'stringi' had non-zero exit status Error in library(beepr) : there is no package called 'beepr' Execution halted Warning in install.packages : installation of package 'audio' had non-zero exit status Error in library(beepr) : there is no package called 'beepr' Execution halted Warning in install.packages : installation of package 'stringr' had non-zero exit status Error in library(beepr) : there is no package called 'beepr' Execution halted Warning in install.packages : installation of package 'beepr' had non-zero exit status The downloaded source packages are in '/tmp/Rtmp0CeBTl/downloaded_packages' Updating HTML index of packages in '.Library' Making 'packages.html' ... done Warning in install.packages : converting NULL pointer to R NULL Warning message: R graphics engine version 14 is not supported by this version of RStudio. The Plots tab will be disabled until a newer version of RStudio is installed.

Did anyone face that issue before?


text:
Q: GDB: programmatically delete a watchpoint Is it possible to delete a watchpoint without knowing the watchpoint number?
I am using commands attached to a breakpoint to set a watchpoint on a memory location. I would like to have the watchpoint cleared at another breakpoint, but I can't figure out how to clear a watchpoint without the watchpoint number. Is there a command that can delete a watchpoint by memory location?

A: the easiest way is to use the $bpnum convenience variable, you'll probably want to store it in another convenience variable so it doesn't change when you create breakpoints/watchpoints later on.
(gdb) watch y
(gdb) set $foo_bp=$bpnum
Hardware watchpoint 2: y
(gdb) p $foo_bp
$1 = 2
(gdb) delete $foo_bp

A: What about saving a watchpoint number and then deleting the watchpoint using this number?
This is an example. I have a C++ program. I set three watchpoints when the breakpoint on the line 5 is hit. For the watchpoint #2 I save a gdb command file in order to delete it later. When the breakpoint on the 9 is hit I just execute this gdb command file:
This is main.cpp:
#include <stdio.h>
int main()
{
  int v3=2, v2=1, v1 =0 ;
  printf("Set a watchpoint\n");

  v1 = 1;
  v1 = 2;
  printf("Clear the watchpoint\n");

  v1 = 3;
  v1 = 4;

  return 0;
}

This is .gdbinit:
file ./a.out
b 5
commands
watch v2
watch v1
set pagination off
shell rm -f all_watchpoints
set logging file all_watchpoints
set logging on
info watchpoints
set logging off
shell rm -f delete_my_watchpoint
shell tail -n 1 all_watchpoints | awk ' {print "delete "$1 }' > delete_my_watchpoint
watch v3
echo Done\n
c
end
b 9
commands
source delete_my_watchpoint
info watchpoints
end
r

This is just a sligtly changed version of the .gdbinit that instead of saving a file with the command to delete the watchpoint saves the watchpoint number:
file ./a.out
b 5
commands
watch v2
watch v1
set pagination off
shell rm -f all_watchpoints
set logging file all_watchpoints
set logging on
info watchpoints
set logging off
shell rm -f delete_my_watchpoint
shell tail -n 1 all_watchpoints | awk ' {print "set $watchpoint_to_delete_later="$1 }' > save_my_watchpoint_number
source save_my_watchpoint_number
shell rm -f save_my_watchpoint_number
shell rm -f all_watchpoints
watch v3
echo Done\n
c
end
b 9
commands
delete $watchpoint_to_delete_later
info watchpoints
end
r

If you set a watchpoint using an address in this way:
(gdb) watch *((int*)0x22ff44)
Hardware watchpoint 3: *((int*)0x22ff44)
(gdb) info watchpoints
Num     Type           Disp Enb Address    What
3       hw watchpoint  keep y              *((int*)0x22ff44)

You can also later find this address since it is dislayed in info watchpoints
(gdb) set logging file all_watchpoints
(gdb) set logging on
Copying output to all_watchpoints.
(gdb) info watchpoints
Num     Type           Disp Enb Address    What
3       hw watchpoint  keep y              *((int*)0x22ff44)
4       hw watchpoint  keep y              *((int*)0x22ff48)
5       hw watchpoint  keep y              *((int*)0x22ff4B)
(gdb) set logging of
Done logging to all_watchpoints.
(gdb) shell grep 0x22ff48 all_watchpoints
4       hw watchpoint  keep y              *((int*)0x22ff48)
(gdb) shell grep 0x22ff48 all_watchpoints | awk ' {print $1}'
4
(gdb) shell grep 0x22ff48 all_watchpoints | awk ' {print "delete "$1}' > delete_watchpoint
(gdb) source delete_watchpoint
(gdb) info watchpoints
Num     Type           Disp Enb Address    What
3       hw watchpoint  keep y              *((int*)0x22ff44)
5       hw watchpoint  keep y              *((int*)0x22ff4B)


text:
Q: Angular NgPrime table get all the data where checkbox is not selected I am using NgPrime Table and I am practicing a School Application. I am working with Attendance Module and I will display all the Students list with a checkbox and they should tick who are present. So I triggered a Click Event on Checkboxes but I am not getting Values where checkbox is not Selected.
          <ng-template pTemplate="body"
              let-student
              let-i="rowIndex"
              >

                  {{i+1}}
                  {{student.regnum}}

          </ng-template>

TS Code:
ngOnInit() {
    //Get students data on page load
    this.http.get('http://localhost:3000/api/student/studentslist').subscribe(res => {
      let data = res.json();
      this.student = data;
    });

    // For ngprime column names
    this.cols = [
      { field: 'S.No', header: 'S.No' },
      { field: 'regnum', header: 'Regnum' },
      { field: 'attendance', header: 'Attendance' }
  ];
  }

  //Save student regnums who are present
  attendance(checkbox, student) {
    if(checkbox.srcElement.checked) {
      this.checkedstudents.push(student.regnum);
    }
    else {
      this.removeStudent(student.regnum);
    }
  }

  //Remove Students who are clicked after unselecting the checkbox
  removeStudent(regnum){
    this.checkedstudents.forEach((item, index) => {
      if(item === regnum) this.checkedstudents.splice(index,1);
    });
 }

As you can see in above code I am just triggering an event on value change of checkboxes so I can get data of only Students present. Just give me some answer to find Students who are absent**(Checkbox with no Tick)**

Solution1:
I can just try in this way but I dont prefer:
On page load I can save all regnum present in an array and when some checkbox is checked I can take it's regnum value and splice it from the previous array. I know it's a long process and foolish kind of thing and I also want to get all the data on Submit Click in ngprime table(which is easy and helps me to learn about handling data in tables)
Solution2: I Tried
<ng-template pTemplate="footer" let-student>

                    <button type="submit" style="width: 50%;"
          class="btn btn-2 btn-2g" (click)="submitattendance(student)">Submit</button>

        </ng-template>

TS file
submitattendance(student) {
   console.log(student);
 }

But console is showing just my Model I created for Student and not the data
Thanks in Advance, Happy Coding

A: If you have any property ex checked ( or you can use new one ) in student object to bind with checkbox then you can bind through ngModel and get the list of all students whose property is checked.

No need to have click event.


text:
Q: Xephyr - Two Displays as extended view I have a wide monitor and I would like to use Xephyr or any other option to create two displays as extended view. Why?
I use to connect to a remote server (RDP) that has two monitors and I am able to see only one remote screen, but if I use two monitors, I can get the two remote views.
I am using Linux Mint (but I can move to any other distro if required).
I have installed Xephyr and it is useful as independent view.
Thanks


text:
Q: React.js, Material Ui Stepper direction I have a weird situation right here where I try to build a stepper component within my app.
everything goes well so far but I try to make this stepper to go from Right to left.
things I have tried:
I tried to instal i18next (translation library) and it didn't work out.
I tried to go from 3 down to 2, and it also is not a satisfying result
here is the result:

and here is my code:
import {
  makeStyles,
  Theme,
  createStyles,
  withStyles,
} from '@material-ui/core/styles';
import clsx from 'clsx';
import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import SettingsIcon from '@material-ui/icons/Settings';
import GroupAddIcon from '@material-ui/icons/GroupAdd';
import VideoLabelIcon from '@material-ui/icons/VideoLabel';
import StepConnector from '@material-ui/core/StepConnector';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import { StepIconProps } from '@material-ui/core/StepIcon';

const ColorlibConnector = withStyles({
  alternativeLabel: {
    top: 22,
  },
  active: {
    '& $line': {
      backgroundImage:
        'linear-gradient( 95deg,rgb(242,113,33) 0%,rgb(233,64,87) 50%,rgb(138,35,135) 100%)',
    },
  },
  completed: {
    '& $line': {
      backgroundImage:
        'linear-gradient( 95deg,rgb(242,113,33) 0%,rgb(233,64,87) 50%,rgb(138,35,135) 100%)',
    },
  },
  line: {
    height: 3,
    border: 0,
    backgroundColor: '#eaeaf0',
    borderRadius: 1,
  },
})(StepConnector);

const useColorlibStepIconStyles = makeStyles({
  root: {
    backgroundColor: '#ccc',
    zIndex: 1,
    color: '#fff',
    width: 50,
    height: 50,
    display: 'flex',
    borderRadius: '50%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  active: {
    backgroundImage:
      'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
    boxShadow: '0 4px 10px 0 rgba(0,0,0,.25)',
  },
  completed: {
    backgroundImage:
      'linear-gradient( 136deg, rgb(242,113,33) 0%, rgb(233,64,87) 50%, rgb(138,35,135) 100%)',
  },
});

function ColorlibStepIcon(props: StepIconProps) {
  const classes = useColorlibStepIconStyles();
  const { active, completed } = props;

  const icons: { [index: string]: React.ReactElement } = {
    1: <SettingsIcon />,
    2: <GroupAddIcon />,
    3: <VideoLabelIcon />,
  };

  return (

      {icons[String(props.icon)]}

  );
}

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      width: '100%',
      display: 'flex',
      alignItems: 'center',
      flexDirection: 'column',
    },
    button: {
      marginRight: theme.spacing(1),
    },
    instructions: {
      marginTop: theme.spacing(1),
      marginBottom: theme.spacing(1),
    },
    stepperContainer: {
      width: '100%',
    },
    contentContainer: {
      width: '50%',
      display: 'flex',
      justifyContent: 'center',
    },
  })
);

function getSteps() {
  return ['Select campaign settings', 'Create an ad group', 'Create an ad'];
}

function getStepContent(step: number) {
  switch (step) {
    case 0:
      return 'Select campaign settings...';
    case 1:
      return 'What is an ad group anyways?';
    case 2:
      return 'This is the bit I really care about!';
    default:
      return 'Unknown step';
  }
}

const SignUp: React.FC = () => {
  const classes = useStyles();
  const [activeStep, setActiveStep] = React.useState(0);
  const steps = getSteps();

  const handleNext = () => {
    setActiveStep((prevActiveStep) => prevActiveStep + 1);
  };

  const handleBack = () => {
    setActiveStep((prevActiveStep) => prevActiveStep - 1);
  };

  const handleReset = () => {
    setActiveStep(0);
  };

  return (

        <Stepper
          dir="rtl"
          alternativeLabel
          activeStep={activeStep}
          connector={<ColorlibConnector />}
        >
          {steps.map((label) => (
            <Step key={label}>
              <StepLabel StepIconComponent={ColorlibStepIcon}>
                {label}
              </StepLabel>
            </Step>
          ))}
        </Stepper>

          {activeStep === steps.length ? (

              <Typography className={classes.instructions}>
                All steps completed - you're finished
              </Typography>
              <Button onClick={handleReset} className={classes.button}>
                Reset
              </Button>

          ) : (

              <Typography className={classes.instructions}>
                {getStepContent(activeStep)}
              </Typography>

                <Button
                  disabled={activeStep === 0}
                  onClick={handleBack}
                  className={classes.button}
                >
                  Back
                </Button>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={handleNext}
                  className={classes.button}
                >
                  {activeStep === steps.length - 1 ? 'Finish' : 'Next'}
                </Button>

          )}

  );
};

export default SignUp;

A: Hi I was fiddling around with the material UI sandbox,
here's the sandbox with working left to right
things I've change, were:

*

*line 43 - initate step to 2

*line 62 - handleNext, prevActiveStep - 1 (from +1)

*line 67 - handleBack, prevActiveStep + 1 (from -1)

*line 86 - setActiveStep(2) (from setActiveStep(0))

*the Stepper component:

<Stepper activeStep={activeStep}>
        {steps.map((label, index) => {
          const stepProps: { completed?: boolean } = {
            completed: activeStep < index //  <<< this setting
          };
          const labelProps: { optional?: React.ReactNode } = {};
          if (isStepOptional(index)) {
            labelProps.optional = (
              <Typography variant="caption">Optional</Typography>
            );
          }
          if (isStepSkipped(index)) {
            stepProps.completed = false;
          }
          return (
            <Step key={label} {...stepProps}>
              <StepLabel {...labelProps}>{label}</StepLabel>
            </Step>
          );
        })}
</Stepper>

hope that helps


text:
Q: how to give parameters when connecting to different webpages in django framework I'm trying to link two webpages in django framework, using anchor tags in template. One of my view takes an argument and I can't figure out how to pass a parameter in template.
This is a url pattern that takes argument.

path("<str:entry>",views.display_entry,name="entry")
corresponding view is:

def display_entry(request,entry):

    text = str(util.get_entry(entry))
    markdown = Markdown()
    html = markdown.convert(text)
    html_file = open(f"encyclopedia/templates/encyclopedia/{entry}.html",'w')
    html_file.write(html)
    html_file.close()

    return render(request, f"encyclopedia/{entry}.html")

and template where I'm trying to access this view is -

        {% for entry in entries %}

{{ entry }}

        {% endfor %}

A: path("<str:entry>", views.display_entry, name="entry-detail")

{% for entry in entries %}
    {{ entry }}
{% endfor %}


text:
Q: Gradient of angle function on sphere has norm 1 In Ballmann's book, it is shown that the internal distance $d(x, y)$ on the unit sphere $S$ in $\mathbb R^{m+1}$ (that is the infimum of lengths of curves on $S$ from $x$ to $y$) is given by the angle from $x$ to $y$.
The proof goes as follows. For a given $x ∈ S$, let $φ(y)$ denote the angle from $x$ to $y$. The idea is to show that $\lVert \operatorname{grad}φ(y) \rVert =1$. From that point on I know how to proceed.
This is the tricky bit.
We can write points $y ∈ S \smallsetminus \{±x\}$
uniquely as
$$
y = \cos(φ)x + \sin(φ)z
$$
with $z = z(y)$ in the equator of $x$, that is $x⋅z = 0$, $\lVert z \rVert =1$, and $φ = φ(y) ∈ (0, π)$. The
function $φ \colon  S \smallsetminus \{±x\} \to (0, π)$ is smooth, with gradient
$$
(\operatorname{grad} φ)(\cos(φ)x + \sin(φ)z) = -\sin(φ)x + \cos(φ)z.
$$
I'm not really sure why $φ$ is smooth and I really can't see how the gradient is computed.
Edit. This is what I thought was done here. If we write $g(φ,z) := \cos(φ)x + \sin(φ)z$, then $g(φ(y),z(y)) = y$. Differentiating both sides and applying the chain rule should yield the desired result, but I don't think it does.


text:
Q: Show that the relation is satisfied $A^2-\text{tr}\left(A\right)A+\det\left(A\right)I=0$ Let $A=\begin{pmatrix}a & b \\c & d\end{pmatrix}\:$ such that $A^2=I\:$.
Show that the following relation is satisfied
$$A^2-\text{tr}\left(A\right)A+\det\left(A\right)I=0$$
I'm never really good at proving things.
I would probably start with changing the $A^2$ with the $I$ in the equation but other than that I'm not too sure how to show this.

A: The characteristic polynomial of $A$ is
$$\chi_A(x)=\det(A-xI)=(a-x)(d-x)-cb=x^2-tr(A)x+\det(A)$$
Now use the Cayley-Hamilton theorem to conclude.


text:
Q: Could someone explain this notation to me? [Linear Algebra] Shown in part (a) in the image below, in which I'm asked to check if a given set forms a basis for $\mathbb R[t]_{\leqslant 3}$. Could someone explain in plain words what is denoted by $\mathbb R[t]_{\leqslant 3}$?

A: It means the set of polynomials in the variable $t$ with real coefficients and degree at most 3:
$$
\mathbb R [t]_{\leq 3} = \left\{ \sum_{i=0}^3 a_i t^i \; \middle| \; a_0, \dots, a_3 \in \mathbb R \right\}
$$

A: $\Bbb R[t]$ (without the $\le\!3$) refers to the set of all polynomials with real coefficients where the variable is $t$:
$$\Bbb R[t]=\{a_0+a_1t+\dotsb+a_nt^n\mid n\in\Bbb N\land a_0,a_1,\dots,a_n\in\Bbb R\}$$
For example, $42.3x^{100}+\sqrt2x^9-x^2-\pi x+3$ is an element of $\Bbb R[t]$.
Given the context, it would seem $\Bbb R[t]_{\le3}$ would be the set of polynomials with real coefficients where the variable is $t$ and the degree is at most $3$:
$$\Bbb R[t]=\{a_0+a_1t+a_2t^2+a_3t^3\mid a_0,a_1,a_2,a_n\in\Bbb R\}$$
For example, $42.3x^3+\sqrt2x^2-\pi x+3$ is an element of $\Bbb R[t]$.


text:
Q: Iterating through every other element within list recursively I have been trying to figure out a clear and concise method to iterate through elements in a list in a form of recursive loop.
For example, if I have a list:
My_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

I would like to extract every other element from the list.
New_list = [2, 6, 10, 14, 18]

I then want to take the discarded values and take every second of those. And so on, recursively.
Since my first run through the list ended at 18, I will skip over 20 and go back to the beginning of the list as I want to extract every other elements.
My_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

# Elements not been used after first operation = [4, 8, 12, 16, 20]

New_list = [2, 6, 10, 14, 18, 4, 12, 20, 8, 16]  # desired output

What methods can I use to loop within a list?

A: you can use python's really cool slicing syntax:
new_list=my_list[::2]
to get every other element.
It means new_list is my_list from the begining to the end with a stride of 2
then your ramainder elements are elements_not_used = [item for item in my_list if item not in new_list] and you can just continue until len(my_list)<2

A: Yes, you can use a while loop with a generator:
L = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

def recursive_odds(x):
    while x:
        yield from x[::2]
        x = x[1::2]

res = list(recursive_odds(L))

[2, 6, 10, 14, 18, 4, 12, 20, 8, 16]

A: using while loop you can do this:
final=[]
while len(mylist)>0:
     final.extend(mylist[::2])
     mylist=mylist[1::2]
print(final)


text:
Q: String contains nothing or the user just presses enter I have been looking for solution and tried it on my code, but still no luck found. What I want to do is to throw an exception if the user inputs nothing and just presses enter and a catch block will be executed once it throws the exception. But in my case, it only executes the second catch-block I have which is the InvalidAnswerException instead of BlankException
Code:
import java.util.Scanner;

public class QnA {

public static void main(String[] args) throws Exception {
    Scanner sc = new Scanner(System.in);

    String[] questions = { "Question-1: Who is the national hero of the Philippines?", "Question-2: What is the national Anthem of the Philippines ?",
            "Question-3: What is the national sport of the philippines ?"};
    String choices[][] = { { "A)Jose Rizal", "B)Andres Bonifacio", "C)Lapu-Lapu" },
             { "A)Paro-Paro G", "B)Bahay kubo", "C)Lupang Hinirang" }, { "A)Basketball", "B)Arnis", "C)Badminton" }, };
    char answers[] = {'A', 'B', 'C'};

    int score = 0;

    for (int i = 0; i < 3; i++) {
        while (true) {
            System.out.println(questions[i]);
            for (int j = 0; j < 3; j++)
                 System.out.println(choices[i][j]);
                 System.out.print("Your Answer : ");
                 String ans = sc.nextLine();
                 try {
                     if (ans.contains("A") || ans.contains("a") || ans.contains("B") || ans.contains("b") || ans.contains("C") || ans.contains("c")) {
                         score++;
                         break;
                     }

                     if (ans.matches("[0-9]") || ans.matches("[!@#$%&*()_+=|<>?{}\\\\[\\\\]~-]")) {
                         throw new InvalidInputException("");
                     }

                     if (!ans.equalsIgnoreCase("A") || !ans.equalsIgnoreCase("B") || !ans.equalsIgnoreCase("C")) {
                         throw new InvalidAnswerException("");
                     }

                     if (ans.length() == 0) {
                         throw new BlankException("");
                     }

                 } catch (InvalidInputException e) {
                     System.out.println("InvalidInputException,Try again..");
                     continue;
                 } catch (InvalidAnswerException e) {
                     System.out.println("InvalidAnswerException,Try again..");
                     continue;
                 } catch(BlankException e) {
                     System.out.println("BlankException,Try again..");
                     continue;
                 }
        }

    }
                 System.out.println("Your score out of " + questions.length + " is : " +score);
                 sc.close();
}
}

class InvalidInputException extends Exception {

    public InvalidInputException(String message) {
        super(message);
    }
}

class InvalidAnswerException extends Exception {

    public InvalidAnswerException(String message) {
        super(message);
    }
}

class BlankException extends Exception {

    public BlankException(String message) {
        super(message);
    }
}

A: As @Ole V.V. pointed out, your last if (ans.legnth() == 0) condition is not applied because it is not even reached by your program. When user inputs nothing "" your ans variable becomes ans="" and then it applies to the third condition if (!ans.equalsIgnoreCase("A") || !ans.equalsIgnoreCase("B") || !ans.equalsIgnoreCase("C")). The simplest solution of this is to put your last if before any other. So, your code may be changed like that:
while (true) {
            System.out.println(questions[i]);
            for (int j = 0; j < 3; j++)
                 System.out.println(choices[i][j]);
                 System.out.print("Your Answer : ");
                 String ans = sc.nextLine();
                 try {
                     if (ans.contains("A") || ans.contains("a") || ans.contains("B") || ans.contains("b") || ans.contains("C") || ans.contains("c")) {
                         score++;
                         break;
                     }

                     if (ans.length() == 0) {
                         throw new BlankException("");
                     }

                     if (ans.matches("[0-9]") || ans.matches("[!@#$%&*()_+=|<>?{}\\\\[\\\\]~-]")) {
                         throw new InvalidInputException("");
                     }

                     if (!ans.equalsIgnoreCase("A") || !ans.equalsIgnoreCase("B") || !ans.equalsIgnoreCase("C")) {
                         throw new InvalidAnswerException("");
                     }

                 } catch (InvalidInputException e) {
                     System.out.println("InvalidInputException,Try again..");
                     continue;
                 } catch (InvalidAnswerException e) {
                     System.out.println("InvalidAnswerException,Try again..");
                     continue;
                 } catch(BlankException e) {
                     System.out.println("BlankException,Try again..");
                     continue;
                 }
        }


text:
Q: How to de-normalize mysql database for user notifications? I think it is necessary to de-normaize database for user notifications. For example, when flagging a post (which should be considered by user), we add a column of flag ENUM('yes', 'no') (or status column). Finding flagged events for a user can be by counting with WHERE clause of user_id='XX' AND flag='yes'.
This normalized structure is fine; but what if we have different types of notifications; e.g. flags for posts, comments, photos ... This means that we need to count several tables when the user is just visiting his profile page. This is more serious for a cross-project like stackexchange, as we get notifications for different sites.
I think de-normalization can help to add notification columns to the user table as
post_flags tinyint(3),
comment_flags tinyint(3),
photo_flags tinyint(3),

In this case, we need to run an additional write query for updating user flag columns on every corresponding actions. For example, when flagging a post: UPDATE users SET post_flags=post_flags+1 WHERE user_id='XX'. My concern is to ensure execution of the latter query to avoid any mismatch between this number and the count of flagged posts; but I think it can be secured by TRANSACTION.
In this way, we get all notification with one query for frequently visited profile pages.
Am I on the right track? or another tricky approach is common for this purpose?

A: Is this de normalising at all? It looks like creating those three columns is a better way to organise and seems more normal to me?

A: You'd probably be better off with a table of user notifications.
create table user_notifications (
  user_id integer primary key, -- ? references users, not shown
  post_flags unsigned tinyint(3) not null default 0,
  comment_flags unsigned tinyint(3) not null default 0,
  photo_flags unsigned tinyint(3) not null default 0
);

A separate, narrower table is both logical and (probably) faster. Unsigned for flags, because negative numbers there make no sense, and MySQL doesn't enforce CHECK constraints.
As far as normalization goes, user_notifications is in 5NF.

A: I don't think this is very effective. Maybe it's useful when you need to find also combinations of flags, for example post_flags OR comment_flags OR photo_flags and the order of the query is also important.


text:
Q: How to use KnockoutJS to observe data on server via AJAX? I've played a little with knockoutjs and have produced the following example, enough to become excited by the idea of building these viewmodels in javascript so that the view can be written in much simpler, declarative manner, i.e. first you define what you want to observe, then with the data-bind attributes define what you want to happen when your viewmodel changes in certain ways.
But all of this is happening only on the client.
How could I extend this example to use knockoutjs to observe the state of objects on the server e.g. via AJAX calls?
index.htm:
<!doctype html>

    <title>Knockout example</title>

        <link rel="stylesheet" href="css/main.css" type="text/css"/>

This is an example with NO names filled.

This is an example with both names filled.

This is an example with only the first name filled.

This is an example with the last name filled but not the first name

First name: <input data-bind="value: firstName, valueUpdate:'afterkeydown'" />

Last name: <input data-bind="value: lastName, valueUpdate:'afterkeydown'" />

Hello, .

Hi there !

Hello, Mr. .

:-( Please fill in both names.

:-) Good job, both names are filled!

:-( Please fill in the last name, too.

:-( Please fill in the first name as well.

main.css:
* { margin: 0; padding: 0}
body { margin: 10px}
p { margin: 10px}
.infobox {
    background-color: #eee;
    width: 300px;
    height: 100px;
    padding: 10px;
}
.informal {
    color: purple;
    font-family: arial;
}
.normal {
    color: black;
    font-family: new courier;
}
.formal {
    color: black;
    font-size: 11pt;
    font-family: times roman;
    background-color: #eee;
}
.good {
    width: 20px;
    background-color: lightgreen;
}
.ok {
    width: 20px;
    background-color: yellow;
}
.bad {
    width: 20px;
    background-color: tomato;
}

main.js:
window.onload= function() {

    var viewModel = {
        firstName : ko.observable(''),
        lastName : ko.observable('')
    };
    viewModel.fullName = ko.dependentObservable(function () {
        return viewModel.firstName() + " " + viewModel.lastName();
    });

    viewModel.bothNamesFilled = ko.dependentObservable(function () {
        return viewModel.firstName().length > 0 && viewModel.lastName().length > 0;
    }, this);
    viewModel.firstNameOnlyFilled = ko.dependentObservable(function () {
        return viewModel.firstName().length > 0 && viewModel.lastName().length == 0;
    }, this);
    viewModel.lastNameOnlyFilled = ko.dependentObservable(function () {
        return viewModel.firstName().length == 0 && viewModel.lastName().length > 0;
    }, this);
    viewModel.noNamesFilled = ko.dependentObservable(function () {
        return viewModel.firstName().length == 0 && viewModel.lastName().length == 0;
    }, this);

    ko.applyBindings(viewModel);
}

A: I would use setTimeout to call a function that uses JQuery to make an $.ajax call.  When it returns JSON data, set that data as your view model and finally, setTimeout again to call the function.

A: Here's an updated example that mainly updates main.js to work with JQuery to do the ajax call.
The HTML file includes Knockout 3 instead of 1.  The HTML also includes JQuery latest to make the JQuery functionality work.
The js/server_data.js is there so you have some valid json data to start with.  You can change the url in the $.ajax settings to any serverside script you have but try to set its content type to application/json.  For example, PHP scripts could set the Content-type header like: header('Content-type: application/json'); before printing out the data in JSON format.
new main.html:
<!doctype html>

    <title>Knockout example</title>

        <link rel="stylesheet" href="css/main.css" type="text/css"/>

This is an example with NO names filled.

This is an example with both names filled.

This is an example with only the first name filled.

This is an example with the last name filled but not the first name

First name: <input data-bind="value: firstName, valueUpdate:'afterkeydown'" />

Last name: <input data-bind="value: lastName, valueUpdate:'afterkeydown'" />

Hello, .

Hi there !

Hello, Mr. .

:-( Please fill in both names.

:-) Good job, both names are filled!

:-( Please fill in the last name, too.

:-( Please fill in the first name as well.

js/main.js:
$(document).ready( function() {

    var viewModel = {
        firstName : ko.observable(''),
        lastName : ko.observable('')
    };
    viewModel.fullName = ko.dependentObservable(function () {
        return viewModel.firstName() + " " + viewModel.lastName();
    });

    viewModel.bothNamesFilled = ko.dependentObservable(function () {
        return viewModel.firstName().length > 0 && viewModel.lastName().length > 0;
    }, this);
    viewModel.firstNameOnlyFilled = ko.dependentObservable(function () {
        return viewModel.firstName().length > 0 && viewModel.lastName().length == 0;
    }, this);
    viewModel.lastNameOnlyFilled = ko.dependentObservable(function () {
        return viewModel.firstName().length == 0 && viewModel.lastName().length > 0;
    }, this);
    viewModel.noNamesFilled = ko.dependentObservable(function () {
        return viewModel.firstName().length == 0 && viewModel.lastName().length == 0;
    }, this);

    ko.applyBindings(viewModel);

    // send request to the server to download the server's model information.
    $.ajax(
    {
        'url': 'js/server_data.js',
        'dataType': 'json',
        'method': 'post',
        'error': function(jqXHR, textStatus, errorThrown)
        {
            // error callback in case you play with this code and run into trouble.
            alert('There was a problem handling the ajax request.  The error information is: jqXHR: '
            +jqXHR+", textStatus: "+textStatus+", errorThrown: "+errorThrown);
        },
        'success': function(data)
        {
            // when it is downloaded and parsed to create the "data" parameter, update the viewModel.
            viewModel.firstName(data.firstName);
            viewModel.lastName(data.lastName);
        }
    }
    );
}
);

js/server_data.js representing dynamically generated data that might be from a database:
{
    "firstName": "John",
    "lastName": "Doe"
}

jsteve has the right general idea but don't use setTimeout if you just want to download the data when the page loads.  Instead, use the JQuery's document ready callback and JQuery's ajax success callback so things run precisely when you want them to.
If you want to continually listen and react to changes to data in the server, look into long poller techniques.  Long poller is more efficient and precisely timed than busy waiting that requires a frequent new request to the server.