问:
How to get the value of a particular textView inside ListView in Android?
In my application I need to move from one activity to another depending on the list clicked. In each listview there will be three textview namely: Emp_id, Emp_name,Emp_address, so whenever I click on a particular list that should move to next activity of the corresponding Emp_id. So here I want to catch the Emp_id, which I am unable. I have tried a lot but got only the first Emp_id not the list that I have clicked.

CODE:

```<code>ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();

        try{
            JSONObject jObj = new JSONObject(Mydetail);
            JSONArray data = jObj.getJSONArray("mydata");

            for(int i=0;i<data.length();i++){
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = data.getJSONObject(i);

                map.put("id", String.valueOf(i));
                map.put("Eid", "" + e.getString("E_id"));
                map.put("Ename", "" + e.getString("E_name"));
                map.put("Eaddress", "" + e.getString("E_address"));
                mylist2.add(map);
            }
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

         ListAdapter adapter = new SimpleAdapter(this, mylist2 , R.layout.datalist,
                                  new String[] { "Eid", "Ename", "Eaddress" },
                                  new int[] {  R.id.TextView1,R.id.TextView2e,R.id.TextView3 });
                                  setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                //String val = o.get("id");

                Pnm = (TextView)findViewById(R.id.TextView1);
                 String str = ((TextView)Pnm).getText().toString();

                Toast.makeText(projects.this, str,Toast.LENGTH_LONG).show();

                Intent newActivitySecond = new Intent(projects.this, modules.class);
                projects.this.startActivity(newActivitySecond);

            }
        });
</code>```

Thanks

答:
You have to use set onclicklistener to all elements inside ListView. I have created a listview. set an adapter to the listview. My adapter is reponsible to show each element of the listview. so inside getView() I will assign onclicklistener to all the elements to whom i want to get the click event

Example

```<code>public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        ViewHolder holder;
        if(convertView==null){
            vi = inflater.inflate(R.layout.item, null);
            holder=new ViewHolder();
            holder.text=(TextView)vi.findViewById(R.id.text);;
            holder.image=(ImageView)vi.findViewById(R.id.image);
            vi.setTag(holder);
        }
        else
            holder=(ViewHolder)vi.getTag();

        holder.text.setText("item "+position);
        holder.image.setTag(data.get(position));
        holder.image.setOnClickListener(this);
        holder.text.setOnClickListener(this);
        imageLoader.DisplayImage(data.get(position), activity, holder.image);
        return vi;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        System.out.println("...clicked view is...."+arg0);
    }
</code>```

Body:
In my application I need to move from one activity to another depending on the list clicked. In each listview there will be three textview namely: Emp_id, Emp_name,Emp_address, so whenever I click on a particular list that should move to next activity of the corresponding Emp_id. So here I want to catch the Emp_id, which I am unable. I have tried a lot but got only the first Emp_id not the list that I have clicked.

CODE:

ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();

        try{
            JSONObject jObj = new JSONObject(Mydetail);
            JSONArray data = jObj.getJSONArray("mydata");

            for(int i=0;i<data.length();i++){
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = data.getJSONObject(i);

                map.put("id", String.valueOf(i));
                map.put("Eid", "" + e.getString("E_id"));
                map.put("Ename", "" + e.getString("E_name"));
                map.put("Eaddress", "" + e.getString("E_address"));
                mylist2.add(map);
            }
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

         ListAdapter adapter = new SimpleAdapter(this, mylist2 , R.layout.datalist,
                                  new String[] { "Eid", "Ename", "Eaddress" },
                                  new int[] {  R.id.TextView1,R.id.TextView2e,R.id.TextView3 });
                                  setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                //String val = o.get("id");

                Pnm = (TextView)findViewById(R.id.TextView1);
                 String str = ((TextView)Pnm).getText().toString();

                Toast.makeText(projects.this, str,Toast.LENGTH_LONG).show();

                Intent newActivitySecond = new Intent(projects.this, modules.class);
                projects.this.startActivity(newActivitySecond);

            }
        });

Thanks

Body:
You have to use set onclicklistener to all elements inside ListView. I have created a listview. set an adapter to the listview. My adapter is reponsible to show each element of the listview. so inside getView() I will assign onclicklistener to all the elements to whom i want to get the click event

Example

public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        ViewHolder holder;
        if(convertView==null){
            vi = inflater.inflate(R.layout.item, null);
            holder=new ViewHolder();
            holder.text=(TextView)vi.findViewById(R.id.text);;
            holder.image=(ImageView)vi.findViewById(R.id.image);
            vi.setTag(holder);
        }
        else
            holder=(ViewHolder)vi.getTag();

        holder.text.setText("item "+position);
        holder.image.setTag(data.get(position));
        holder.image.setOnClickListener(this);
        holder.text.setOnClickListener(this);
        imageLoader.DisplayImage(data.get(position), activity, holder.image);
        return vi;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        System.out.println("...clicked view is...."+arg0);
    }


来源: stackexchange

问:
How to set config variables for cloud functions using gcloud cli
My Firebase default service account ( xxxx@appspot.gserviceaccount.com ) is deleted and cannot be recovered.

Hence I created different service account and now I have to deploy functions using gcloud CLI using
 gcloud beta functions deploy FUNCTION_NAME --service-account=NEW_SERVICE_ACCOUNT command.

How do I set firebase config variable using gcloud CLI which I can access via functions.config().

答:
When you use Cloud Function, you can defined environment variable that you can use like this in Node

```<code>const val = process.env.KEY
</code>```

To set this KEY=val into cloud function, you can use the env vars setter parameter

For reusing the Firebase functions.config(), and by looking the source code, it should work like this (I didn't test)

Define a JSON for your config, as described in the retrieve part of the Firebase doc

```<code>{
  "someservice": {
    "key":"THE API KEY",
    "id":"THE CLIENT ID"
  }
}
</code>```

Make it inline and store it into a CLoud Functions file format. The key of the environment variable must be FIREBASE_CONFIG. The result must be like this (name it config.yaml for example)

```<code>FIREBASE_CONFIG: '{"someservice":{"key":"THE API KEY","id":"THE CLIENT ID"}}'
</code>```

Add the file env vars to the Cloud Function

```<code>gcloud functions deploy --env-vars-file=config.yaml ....
</code>```

Note: Why using a file?

Great question, because you can also use the --set-env-vars param. 2 problems

First, you need to inline the content and to skip the double quote " character. For this, you can do --set-env-vars=TEST=$(echo "'$(cat config.json | sed -z 's/\n//g')'")

The first solution works ONLY if you haven't comma ,. With comma, the gcloud command is lost and, even if you set your json inline content between simple quote ', it considers it as a new env var definition and fail.

Because I didn't have tested, I'm interested to know if this solution works or not!

ContentLicense: CC BY-SA 4.0

Body:
When you use Cloud Function, you can defined environment variable that you can use like this in Node

const val = process.env.KEY

To set this KEY=val into cloud function, you can use the env vars setter parameter

For reusing the Firebase functions.config(), and by looking the source code, it should work like this (I didn't test)

Define a JSON for your config, as described in the retrieve part of the Firebase doc

{
  "someservice": {
    "key":"THE API KEY",
    "id":"THE CLIENT ID"
  }
}

Make it inline and store it into a CLoud Functions file format. The key of the environment variable must be FIREBASE_CONFIG. The result must be like this (name it config.yaml for example)

FIREBASE_CONFIG: '{"someservice":{"key":"THE API KEY","id":"THE CLIENT ID"}}'

Add the file env vars to the Cloud Function

gcloud functions deploy --env-vars-file=config.yaml ....

Note: Why using a file?

Great question, because you can also use the --set-env-vars param. 2 problems

First, you need to inline the content and to skip the double quote " character. For this, you can do --set-env-vars=TEST=$(echo "'$(cat config.json | sed -z 's/\n//g')'")

The first solution works ONLY if you haven't comma ,. With comma, the gcloud command is lost and, even if you set your json inline content between simple quote ', it considers it as a new env var definition and fail.

Because I didn't have tested, I'm interested to know if this solution works or not!


问:
Minimum cabs required (Algorithm)
I am trying to solve this question:

https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/minimum-cabs-0798cfa5/description/

I see a solution here but I don't quite understand it.

```<code>#include <bits/stdc++.h>
using namespace std;
const int MAX = 1500;
int A[MAX];
int main(int argc, char* argv[])
{
    if(argc == 2 or argc == 3) freopen(argv[1], "r", stdin);
    if(argc == 3) freopen(argv[2], "w", stdout);
    ios::sync_with_stdio(false);
    int n, hh1, hh2, mm1, mm2, smins, emins, ans;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> hh1 >> mm1 >> hh2 >> mm2;
        smins = hh1 * 60 + mm1;
        emins = hh2 * 60 + mm2;
        A[smins]++;
        A[emins+1]--;
    }
    ans = A[0];
    for (int i = 1; i < MAX; i++) {
        A[i] += A[i-1];
        ans = max(ans, A[i]);
    }
    cout << ans << endl;
    return 0;

}
</code>```

Could someone explain the algorithm to me?

答:
```<code>class TestClass
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        int arr[] = new int[24*60+1];

        while(t!=0)
        {
            int st = sc.nextInt()*60+sc.nextInt();
            int et = sc.nextInt()*60+sc.nextInt();

            for(int i=st;i<=et;i++)
            {
                arr[i]++;
            }
            t--;
        }

        int max=0;

        for(int i=0;i<arr.length;i++)
        {
            max=Math.max(max,arr[i]);
        }

        System.out.println(max);
    }
}
</code>```

Title: Minimum cabs required (Algorithm)

Body:
I am trying to solve this question:

https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/minimum-cabs-0798cfa5/description/

I see a solution here but I don't quite understand it.

#include <bits/stdc++.h>
using namespace std;
const int MAX = 1500;
int A[MAX];
int main(int argc, char* argv[])
{
    if(argc == 2 or argc == 3) freopen(argv[1], "r", stdin);
    if(argc == 3) freopen(argv[2], "w", stdout);
    ios::sync_with_stdio(false);
    int n, hh1, hh2, mm1, mm2, smins, emins, ans;
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> hh1 >> mm1 >> hh2 >> mm2;
        smins = hh1 * 60 + mm1;
        emins = hh2 * 60 + mm2;
        A[smins]++;
        A[emins+1]--;
    }
    ans = A[0];
    for (int i = 1; i < MAX; i++) {
        A[i] += A[i-1];
        ans = max(ans, A[i]);
    }
    cout << ans << endl;
    return 0;

}

Could someone explain the algorithm to me?


问:
PDF file not opening in release version of android in flutter
In Android Studio Emulator, the pdf file is opening but when I release its .apk file and install it on my phone, pdf file does not open. I used flutter_pdfview package to load pdf file.

This is where the page is shown.

```<code>import 'package:darpandentalhome/services/api_for_report.dart';
import 'package:darpandentalhome/shared/loading.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:google_fonts/google_fonts.dart';

class Report extends StatefulWidget {

  final String url;

  Report({this.url});

  @override
  _ReportState createState() => _ReportState();
}

class _ReportState extends State<Report> {

  String path;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ApiService(pdfURL: widget.url).loadPDF().then((value){
      setState(() {
        path=value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        centerTitle: true,
        title: Text(
            'Report',
          style: GoogleFonts.rubik(
            textStyle: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.w500
            )
          ),
        ),
        leading: IconButton(
            icon: Icon(Icons.arrow_back_ios,color: Colors.black,),
          onPressed: () {
              Navigator.pop(context);
          },
        ),
        backgroundColor: Color(0xfff9f9f9),
      ),
      backgroundColor: Color(0xfff9f9f9),
      body: path != null ? Container(
        child: PDFView(
          filePath: path,
        ),
      ) : Loading(),
      floatingActionButton: IconButton(
        icon: Icon(Icons.refresh,size: 30,),
        onPressed: () {
          setState(() {
            path = null;
            ApiService(pdfURL: widget.url).loadPDF().then((value){
              setState(() {
                path=value;
              });
            });
          });
        },
      ),
    );
  }
}
</code>```

This is for the HTTP API service for fetching pdf file from HTTP URL.

```<code>import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';

class ApiService{

  final String pdfURL;

  ApiService({this.pdfURL});

  Future<String> loadPDF() async {
    var response = await http.get(pdfURL);
    var dir = await getExternalStorageDirectory();
    File file = File(dir.path + "/data.pdf");
    await file.writeAsBytes(response.bodyBytes, flush: true);
    return file.path;
  }

}
</code>```

I thought it was a permission issue of the phone then I used storage permission in AndroidManifest file then manually allowed this permission on my phone but it also didn't work.
What is the problem here?

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

答:
it's because difference between android version
if your android version is 29 use this code in your manifest
android:requestLegacyExternalStorage="true"  </p>

Body:
In Android Studio Emulator, the pdf file is opening but when I release its .apk file and install it on my phone, pdf file does not open. I used flutter_pdfview package to load pdf file.

This is where the page is shown.

import 'package:darpandentalhome/services/api_for_report.dart';
import 'package:darpandentalhome/shared/loading.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:google_fonts/google_fonts.dart';

class Report extends StatefulWidget {

  final String url;

  Report({this.url});

  @override
  _ReportState createState() => _ReportState();
}

class _ReportState extends State<Report> {

  String path;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    ApiService(pdfURL: widget.url).loadPDF().then((value){
      setState(() {
        path=value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        centerTitle: true,
        title: Text(
            'Report',
          style: GoogleFonts.rubik(
            textStyle: TextStyle(
              color: Colors.black,
              fontWeight: FontWeight.w500
            )
          ),
        ),
        leading: IconButton(
            icon: Icon(Icons.arrow_back_ios,color: Colors.black,),
          onPressed: () {
              Navigator.pop(context);
          },
        ),
        backgroundColor: Color(0xfff9f9f9),
      ),
      backgroundColor: Color(0xfff9f9f9),
      body: path != null ? Container(
        child: PDFView(
          filePath: path,
        ),
      ) : Loading(),
      floatingActionButton: IconButton(
        icon: Icon(Icons.refresh,size: 30,),
        onPressed: () {
          setState(() {
            path = null;
            ApiService(pdfURL: widget.url).loadPDF().then((value){
              setState(() {
                path=value;
              });
            });
          });
        },
      ),
    );
  }
}

This is for the HTTP API service for fetching pdf file from HTTP URL.

import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';

class ApiService{

  final String pdfURL;

  ApiService({this.pdfURL});

  Future<String> loadPDF() async {
    var response = await http.get(pdfURL);
    var dir = await getExternalStorageDirectory();
    File file = File(dir.path + "/data.pdf");
    await file.writeAsBytes(response.bodyBytes, flush: true);
    return file.path;
  }

}

I thought it was a permission issue of the phone then I used storage permission in AndroidManifest file then manually allowed this permission on my phone but it also didn't work.
What is the problem here?

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


问:
iPhone4 blurred text/images after content load via ajax
i use phonegap, jqtouch and iScoll for a iphone app.
I load some content via ajax into a div container. After that, sometimes all elements blurred and sometimes not.

Strangely after i make a swap (-webkit-transform: perspective(800);) between pages, all looks sharp.

Is there any solution for my problem?

Thanks Kevin
and sorry for the bas english

答:
I hit a similar problem. The advice here helped...

https://groups.google.com/forum/#!topic/iscroll/DuZ5I-77fxo

ContentLicense: CC BY-SA 3.0


问:
Nested array computations in Python using numpy
I am trying to use numpy in Python in solving my project.

I have a random binary array  rndm = [1, 0, 1, 1] and a resource_arr = [[2, 3], 4, 2, [1, 2]]. What I am trying to do is to multiply the array element wise, then get their sum. As an expected output for the sample above,
output = 5 0 2 3. I find hard to solve such problem because of the nested array/list.

So far my code looks like this:

```<code>   def fitness_score():

   output = numpy.add(rndm * resource_arr)
   return output

   fitness_score()
</code>```

I keep getting

```<code>ValueError: invalid number of arguments.
</code>```

For which I think is because of the addition that I am trying to do. Any help would be appreciated. Thank you!

答:
Numpy treats its arrays as matrices, and resource_arr is not a (valid) matrix. In your case a python list is more suitable:

```<code>def sum_nested(l):
    tmp = []

    for element in l:
        if isinstance(element, list):
            tmp.append(numpy.sum(element))
        else:
            tmp.append(element)

    return tmp
</code>```

In this function we check for each element inside l if it is a list. If so, we sum its elements. On the other hand, if the encountered element is just a number, we leave it untouched. Please note that this only works for one level of nesting.

Now, if we run sum_nested([[2, 3], 4, 2, [1, 2]]) we will get [5 4 2 3]. All that's left is multiplying this result by the elements of rndm, which can be achieved easily using numpy:

```<code>def fitness_score(a, b):
    return numpy.multiply(a, sum_nested(b))
</code>```

Body:
I am trying to use numpy in Python in solving my project.

I have a random binary array  rndm = [1, 0, 1, 1] and a resource_arr = [[2, 3], 4, 2, [1, 2]]. What I am trying to do is to multiply the array element wise, then get their sum. As an expected output for the sample above,
output = 5 0 2 3. I find hard to solve such problem because of the nested array/list.

So far my code looks like this:

   def fitness_score():

   output = numpy.add(rndm * resource_arr)
   return output

   fitness_score()

I keep getting

ValueError: invalid number of arguments.

For which I think is because of the addition that I am trying to do. Any help would be appreciated. Thank you!

Body:
Numpy treats its arrays as matrices, and resource_arr is not a (valid) matrix. In your case a python list is more suitable:

def sum_nested(l):
    tmp = []

    for element in l:
        if isinstance(element, list):
            tmp.append(numpy.sum(element))
        else:
            tmp.append(element)

    return tmp

In this function we check for each element inside l if it is a list. If so, we sum its elements. On the other hand, if the encountered element is just a number, we leave it untouched. Please note that this only works for one level of nesting.

Now, if we run sum_nested([[2, 3], 4, 2, [1, 2]]) we will get [5 4 2 3]. All that's left is multiplying this result by the elements of rndm, which can be achieved easily using numpy:

def fitness_score(a, b):
    return numpy.multiply(a, sum_nested(b))


问:
loggedIn state reverts back to false after Logging in and doesn't allow me to guard route
I'm trying to guard my routes with state: { loggedIn: false }, when I login from my Login.vue component the goal is to trigger an action this.$store.dispatch('setLogin') that mutates the state of  loggedIn to true. There is then navigation guard that is suppose to prevent me form seeing my Login.vue and Regester.vue components. The problem is that it seems like the state changes to true, but not the base state: allowing me to keep hitting the /auth/login and /auth/register routes.

Routes

```<code>const routes = [
  {
    path: '/auth',
    name: 'auth',
    component: Auth,
    children: [
      { name: 'login', path: 'login', component: Login },
      { name: 'register', path: 'register', component: Register },
    ],
    meta: {
      requiresVisitor: true,
    }
  },
  {
    path: '/logout',
    name: 'logout',
    component: Logout
  }
]
</code>```

Login Component

```<code>login() {
    this.$http.get('/sanctum/csrf-cookie').then(response => {
        this.$http.post('/login', {
            email: this.username,
            password: this.password,
        }).then(response2 => {
            this.$store.dispatch('setLogin')
            this.$store.dispatch('getUser')
            alert(this.$store.state.loggedIn)
            this.$router.push({ name: 'Home' })
        }).catch(error => {
            console.log(error.response.data);
            const key = Object.keys(error.response.data.errors)[0]
            this.errorMessage = error.response.data.errors[key][0]
        })
    });
}
</code>```

Vuex

```<code>export default new Vuex.Store({
  state: {
    loggedIn: false,
    user: JSON.parse(localStorage.getItem('user')) || null,
  },
  mutations: {
    setLogin: (state) => {
      state.loggedIn = true
    },
    SET_USER_DATA (state, userData) {
      localStorage.setItem('user', JSON.stringify(userData))
      state.user = userData;
    },
    removeUser(state) {
      localStorage.removeItem('user');
      state.user = null;
    }
  },
  actions: {
    getUser(context) {
      if (context.state.loggedIn) {
        alert('hit');
        return new Promise((resolve, reject) => {
          axios.get('api/user')
            .then(response => {
              context.commit('SET_USER_DATA', response.data.data)
              resolve(response)
            })
            .catch(error => {
              reject(error)
            })
        })
      }
    },
    setLogin(context){
      context.commit('setLogin')
    }
  },
  modules: {
  }
})
</code>```

It's strange because alert(this.$store.state.loggedIn) renders true, but when I go back the auth link there's a mounted state alert that comes back false.

Here's my navigation guards as well:

```<code>router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
      if (!store.state.loggedIn) {
        next({
            name: 'login',
        })
      } else {
      next()
      }
  } else if (to.matched.some(record => record.meta.requiresVisitor)) {
      if (store.state.loggedIn) {
      next({
          name: 'Home',
      })
      return
      } else {
      next()
      }
  } else {
      next()
  }
})
</code>```

答:
You need to store the loggedIn user in local storage:

```<code>setLogin: (state) => {
 state.loggedIn = localStorage.setItem('loggedIn', 'true')
 state.loggedIn = true
},
</code>```

Then your state should look like:

```<code>state: {
    loggedIn: localStorage.getItem('loggedIn') || null,
},
</code>```

Body:
I'm trying to guard my routes with state: { loggedIn: false }, when I login from my Login.vue component the goal is to trigger an action this.$store.dispatch('setLogin') that mutates the state of  loggedIn to true. There is then navigation guard that is suppose to prevent me form seeing my Login.vue and Regester.vue components. The problem is that it seems like the state changes to true, but not the base state: allowing me to keep hitting the /auth/login and /auth/register routes.

Routes

const routes = [
  {
    path: '/auth',
    name: 'auth',
    component: Auth,
    children: [
      { name: 'login', path: 'login', component: Login },
      { name: 'register', path: 'register', component: Register },
    ],
    meta: {
      requiresVisitor: true,
    }
  },
  {
    path: '/logout',
    name: 'logout',
    component: Logout
  }
]

Login Component

login() {
    this.$http.get('/sanctum/csrf-cookie').then(response => {
        this.$http.post('/login', {
            email: this.username,
            password: this.password,
        }).then(response2 => {
            this.$store.dispatch('setLogin')
            this.$store.dispatch('getUser')
            alert(this.$store.state.loggedIn)
            this.$router.push({ name: 'Home' })
        }).catch(error => {
            console.log(error.response.data);
            const key = Object.keys(error.response.data.errors)[0]
            this.errorMessage = error.response.data.errors[key][0]
        })
    });
}

Vuex

export default new Vuex.Store({
  state: {
    loggedIn: false,
    user: JSON.parse(localStorage.getItem('user')) || null,
  },
  mutations: {
    setLogin: (state) => {
      state.loggedIn = true
    },
    SET_USER_DATA (state, userData) {
      localStorage.setItem('user', JSON.stringify(userData))
      state.user = userData;
    },
    removeUser(state) {
      localStorage.removeItem('user');
      state.user = null;
    }
  },
  actions: {
    getUser(context) {
      if (context.state.loggedIn) {
        alert('hit');
        return new Promise((resolve, reject) => {
          axios.get('api/user')
            .then(response => {
              context.commit('SET_USER_DATA', response.data.data)
              resolve(response)
            })
            .catch(error => {
              reject(error)
            })
        })
      }
    },
    setLogin(context){
      context.commit('setLogin')
    }
  },
  modules: {
  }
})

It's strange because alert(this.$store.state.loggedIn) renders true, but when I go back the auth link there's a mounted state alert that comes back false.

Here's my navigation guards as well:

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
      if (!store.state.loggedIn) {
        next({
            name: 'login',
        })
      } else {
      next()
      }
  } else if (to.matched.some(record => record.meta.requiresVisitor)) {
      if (store.state.loggedIn) {
      next({
          name: 'Home',
      })
      return
      } else {
      next()
      }
  } else {
      next()
  }
})

Body:
You need to store the loggedIn user in local storage:

setLogin: (state) => {
 state.loggedIn = localStorage.setItem('loggedIn', 'true')
 state.loggedIn = true
},

Then your state should look like:

state: {
    loggedIn: localStorage.getItem('loggedIn') || null,
},


问:
Can I control the location of .NET user settings to avoid losing settings on application upgrade?
I'm trying to customize the location of the user.config file. Currently it's stored with a hash and version number

```<code>%AppData%\[CompanyName]\[ExeName]_Url_[some_hash]\[Version]\
</code>```

I want to it be agnostic to the version of the application

```<code>%AppData%\[CompanyName]\[ProductName]\
</code>```

Can this be done and how? What are the implications? Will the user lose their settings from the previous version after upgrading?

答:
To answer the first question, you technically can put the file wherever you want, however you will have to code it yourself, as the default place the file goes to is the first of your two examples. (link to how to do it yourself)

As for the second question, it depends on how you deploy the application.  If you deploy via a .msi, then there are two hashes in the properties of the setup project (that the msi is built from), the 'upgrade code' and the 'product code'.  These determine how the msi can be installed, and if it upgrades, overwrites, or installs beside any other version of the same application.

For instance, if you have two versions of your software and they have different 'upgrade' codes, then to windows they are completely different pieces of software regardless of what the name is.  However if the 'upgrade' code is the same, but the 'product' code is different then when you try to install the 2nd msi it will ask you if you want to upgrade, at which time it is supposed to copy the values from the old config to a new config.  If both values are the same, and the version number didn't change then the new config will be in the same location as the old config, and it won't have to do anything.  MSDN Documentation

ClickOnce is a little bit different, because its based more off of the ClickOnce version # and URL path, however I have found that as long as you continue to 'Publish' to the same location the new version of the application will continue to use the existing config. (link to how ClickOnce handles updates)

I also know there is a way to manually merge configs during the install of the msi using custom install scripts, but I don't remember the exact steps to do it... (see this link for how to do it with a web.config)

OwnerDisplayName: Muxa

Body:
I'm trying to customize the location of the user.config file. Currently it's stored with a hash and version number

%AppData%\[CompanyName]\[ExeName]_Url_[some_hash]\[Version]\

I want to it be agnostic to the version of the application

%AppData%\[CompanyName]\[ProductName]\

Can this be done and how? What are the implications? Will the user lose their settings from the previous version after upgrading?

LastEditorDisplayName: Muxa

OwnerDisplayName: uzbones

LastEditorDisplayName: uzbones


问:
Groupby and random sample based on a column value
I have a dataframe which I want to groupby by grp1, grp2 columns and then make random samples from every group based on the column how_many.

This is my sample data

   grp1  grp2  how_many    val
0     a     1         2  2993
1     a     1         2  8244
2     a     2         1  7148
3     a     1         2  5326
4     a     3         2  5577
5     a     3         2  5651
6     a     1         2  6297
7     a     2         1  2657
8     a     2         1  9774
9     a     1         2  4075
10    a     3         2  6780
11    b     1         1  1765
12    b     1         1  5592
13    b     1         1  9936
14    b     2         4  4324
15    b     2         4  6823
16    b     2         4  9184
17    b     2         4  7498
18    b     2         4  3810
```

<p>This is the expected result (random of course):</p>

<pre class="lang-py prettyprint-override"><code>  grp1  grp2  how_many    val
0    a     1         2  2993
1    a     1         2  5326
2    a     2         1  9774
3    a     3         2  6780
4    a     3         2  5651
5    b     1         1  5592
6    b     2         4  6823
7    b     2         4  9184
8    b     2         4  7498
9    b     2         4  3810
</code>```

My approach was to follow these instructions, however, in my case, I do not have a stable sample size, it varies based on a column value.

I also tried to use multi_index on groupby columns, but got an error saying that MemoryError: Unable to allocate 107. GiB for an array with shape (57244869081,) and data type int16. It is just a small sample of my data.

Any help would be appreciated

答:
Both solution working if same values in column how_many per groups.

Create lambda function with DataFrame.sample and call per groups:

```<code>df1= (df.groupby(['grp1','grp2'])
        .apply(lambda x: x.sample(x['how_many'].iat[0]))
        .reset_index(drop=True))
print (df1)
  grp1  grp2  how_many   val
0    a     1         2  2993
1    a     1         2  6297
2    a     2         1  9774
3    a     3         2  5651
4    a     3         2  5577
5    b     1         1  1765
6    b     2         4  6823
7    b     2         4  4324
8    b     2         4  7498
9    b     2         4  9184
</code>```

Solution out of box for improve performance:

First create random all rows by frac=1 in DataFrame.sample, then create counter by GroupBy.cumcount and compare by Series.le for <=, last if necessary sorting by groups:

```<code>df1 = df.sample(frac=1)
df1 = df1[df1.groupby(['grp1','grp2']).cumcount().add(1).le(df1['how_many'])]
df1 = df1.sort_values(['grp1','grp2'])
print (df1)
   grp1  grp2  how_many   val
0     a     1         2  2993
1     a     1         2  8244
2     a     2         1  7148
5     a     3         2  5651
4     a     3         2  5577
13    b     1         1  9936
16    b     2         4  9184
17    b     2         4  7498
15    b     2         4  6823
14    b     2         4  4324
</code>```

Details:

First are randomly changed order of columns:

```<code>df1 = df.sample(frac=1)
print (df1)
   grp1  grp2  how_many   val
15    b     2         4  6823
18    b     2         4  3810
10    a     3         2  6780
11    b     1         1  1765
14    b     2         4  4324
2     a     2         1  7148
16    b     2         4  9184
7     a     2         1  2657
9     a     1         2  4075
1     a     1         2  8244
13    b     1         1  9936
17    b     2         4  7498
8     a     2         1  9774
4     a     3         2  5577
12    b     1         1  5592
0     a     1         2  2993
5     a     3         2  5651
6     a     1         2  6297
3     a     1         2  5326
</code>```

Then is created counter per groups and filtered by mask - compared by column how_many are returned first rows, but becuse randoch changed order are returned random rows:

```<code>print (df1.assign(counter=df1.groupby(['grp1','grp2']).cumcount().add(1),
                  mask=df1.groupby(['grp1','grp2']).cumcount().add(1).le(df1['how_many'])))
   grp1  grp2  how_many   val  counter   mask
15    b     2         4  6823        1   True
18    b     2         4  3810        2   True
10    a     3         2  6780        1   True
11    b     1         1  1765        1   True
14    b     2         4  4324        3   True
2     a     2         1  7148        1   True
16    b     2         4  9184        4   True
7     a     2         1  2657        2  False
9     a     1         2  4075        1   True
1     a     1         2  8244        2   True
13    b     1         1  9936        2  False
17    b     2         4  7498        5  False
8     a     2         1  9774        3  False
4     a     3         2  5577        2   True
12    b     1         1  5592        3  False
0     a     1         2  2993        3  False
5     a     3         2  5651        3  False
6     a     1         2  6297        4  False
3     a     1         2  5326        5  False
</code>```

Filtering:

```<code>df1 = df1[df1.groupby(['grp1','grp2']).cumcount().add(1).le(df1['how_many'])]
print (df1)
   grp1  grp2  how_many   val
15    b     2         4  6823
18    b     2         4  3810
10    a     3         2  6780
11    b     1         1  1765
14    b     2         4  4324
2     a     2         1  7148
16    b     2         4  9184
9     a     1         2  4075
1     a     1         2  8244
4     a     3         2  5577
</code>```

If necessary, sorting:

```<code>df1 = df1.sort_values(['grp1','grp2'])
print (df1)
   grp1  grp2  how_many   val
9     a     1         2  4075
1     a     1         2  8244
2     a     2         1  7148
10    a     3         2  6780
4     a     3         2  5577
11    b     1         1  1765
15    b     2         4  6823
18    b     2         4  3810
14    b     2         4  4324
16    b     2         4  9184
</code>```

Body:
I have a dataframe which I want to groupby by grp1, grp2 columns and then make random samples from every group based on the column how_many.

This is my sample data

   grp1  grp2  how_many    val
0     a     1         2  2993
1     a     1         2  8244
2     a     2         1  7148
3     a     1         2  5326
4     a     3         2  5577
5     a     3         2  5651
6     a     1         2  6297
7     a     2         1  2657
8     a     2         1  9774
9     a     1         2  4075
10    a     3         2  6780
11    b     1         1  1765
12    b     1         1  5592
13    b     1         1  9936
14    b     2         4  4324
15    b     2         4  6823
16    b     2         4  9184
17    b     2         4  7498
18    b     2         4  3810

This is the expected result (random of course):

  grp1  grp2  how_many    val
0    a     1         2  2993
1    a     1         2  5326
2    a     2         1  9774
3    a     3         2  6780
4    a     3         2  5651
5    b     1         1  5592
6    b     2         4  6823
7    b     2         4  9184
8    b     2         4  7498
9    b     2         4  3810

My approach was to follow these instructions, however, in my case, I do not have a stable sample size, it varies based on a column value.

I also tried to use multi_index on groupby columns, but got an error saying that MemoryError: Unable to allocate 107. GiB for an array with shape (57244869081,) and data type int16. It is just a small sample of my data.

Any help would be appreciated

Body:
Both solution working if same values in column how_many per groups.

Create lambda function with DataFrame.sample and call per groups:

df1= (df.groupby(['grp1','grp2'])
        .apply(lambda x: x.sample(x['how_many'].iat[0]))
        .reset_index(drop=True))
print (df1)
  grp1  grp2  how_many   val
0    a     1         2  2993
1    a     1         2  6297
2    a     2         1  9774
3    a     3         2  5651
4    a     3         2  5577
5    b     1         1  1765
6    b     2         4  6823
7    b     2         4  4324
8    b     2         4  7498
9    b     2         4  9184

Solution out of box for improve performance:

First create random all rows by frac=1 in DataFrame.sample, then create counter by GroupBy.cumcount and compare by Series.le for <=, last if necessary sorting by groups:

df1 = df.sample(frac=1)
df1 = df1[df1.groupby(['grp1','grp2']).cumcount().add(1).le(df1['how_many'])]
df1 = df1.sort_values(['grp1','grp2'])
print (df1)
   grp1  grp2  how_many   val
0     a     1         2  2993
1     a     1         2  8244
2     a     2         1  7148
5     a     3         2  5651
4     a     3         2  5577
13    b     1         1  9936
16    b     2         4  9184
17    b     2         4  7498
15    b     2         4  6823
14    b     2         4  4324

Details:

First are randomly changed order of columns:

df1 = df.sample(frac=1)
print (df1)
   grp1  grp2  how_many   val
15    b     2         4  6823
18    b     2         4  3810
10    a     3         2  6780
11    b     1         1  1765
14    b     2         4  4324
2     a     2         1  7148
16    b     2         4  9184
7     a     2         1  2657
9     a     1         2  4075
1     a     1         2  8244
13    b     1         1  9936
17    b     2         4  7498
8     a     2         1  9774
4     a     3         2  5577
12    b     1         1  5592
0     a     1         2  2993
5     a     3         2  5651
6     a     1         2  6297
3     a     1         2  5326

Then is created counter per groups and filtered by mask - compared by column how_many are returned first rows, but becuse randoch changed order are returned random rows:

print (df1.assign(counter=df1.groupby(['grp1','grp2']).cumcount().add(1),
                  mask=df1.groupby(['grp1','grp2']).cumcount().add(1).le(df1['how_many'])))
   grp1  grp2  how_many   val  counter   mask
15    b     2         4  6823        1   True
18    b     2         4  3810        2   True
10    a     3         2  6780        1   True
11    b     1         1  1765        1   True
14    b     2         4  4324        3   True
2     a     2         1  7148        1   True
16    b     2         4  9184        4   True
7     a     2         1  2657        2  False
9     a     1         2  4075        1   True
1     a     1         2  8244        2   True
13    b     1         1  9936        2  False
17    b     2         4  7498        5  False
8     a     2         1  9774        3  False
4     a     3         2  5577        2   True
12    b     1         1  5592        3  False
0     a     1         2  2993        3  False
5     a     3         2  5651        3  False
6     a     1         2  6297        4  False
3     a     1         2  5326        5  False

Filtering:

df1 = df1[df1.groupby(['grp1','grp2']).cumcount().add(1).le(df1['how_many'])]
print (df1)
   grp1  grp2  how_many   val
15    b     2         4  6823
18    b     2         4  3810
10    a     3         2  6780
11    b     1         1  1765
14    b     2         4  4324
2     a     2         1  7148
16    b     2         4  9184
9     a     1         2  4075
1     a     1         2  8244
4     a     3         2  5577

If necessary, sorting:

df1 = df1.sort_values(['grp1','grp2'])
print (df1)
   grp1  grp2  how_many   val
9     a     1         2  4075
1     a     1         2  8244
2     a     2         1  7148
10    a     3         2  6780
4     a     3         2  5577
11    b     1         1  1765
15    b     2         4  6823
18    b     2         4  3810
14    b     2         4  4324
16    b     2         4  9184


问:
How do I show the name of a page I am on in a Rails application
I have a header as follows

          Home

But I want the name of the current page to be dynamic. For example when I visit the articles page the title should say articles, and The locations pages should say locations.

I am new to Ruby and Rails so this is probably very easy but I don't know how. Thanks in advance!

James

答:
Inside app/views/layouts/application.html.erb replace <title>...</title> by

```<code><title>
  <% if content_for?(:title) %>
    <%= yield :title %>
  <% end %>
</title>
</code>```

You'll be able to change the title dynamically from any other view, for instance:

```<code># app/views/articles/index.html.erb

<% content_for(:title) do %>
  Articles
<% end %>
</code>```

```<code># app/views/locations/index.html.erb

<% content_for(:title) do %>
  Locations
<% end %>
</code>```

Let's assume that you have @article object with name field

```<code># app/views/articles/show.html.erb

<% content_for(:title) do %>
  @article.name
<% end %>
</code>```

UPD

As suggested by @engineersmnky you can pass the title as a parameter content_for(:title, 'Articles')

https://apidock.com/rails/ActionView/Helpers/CaptureHelper/content_for

Body:
Inside app/views/layouts/application.html.erb replace <title>...</title> by

<title>
  <% if content_for?(:title) %>
    <%= yield :title %>
  <% end %>
</title>

You'll be able to change the title dynamically from any other view, for instance:

# app/views/articles/index.html.erb

<% content_for(:title) do %>
  Articles
<% end %>

# app/views/locations/index.html.erb

<% content_for(:title) do %>
  Locations
<% end %>

Let's assume that you have @article object with name field

# app/views/articles/show.html.erb

<% content_for(:title) do %>
  @article.name
<% end %>

UPD

As suggested by @engineersmnky you can pass the title as a parameter content_for(:title, 'Articles')

https://apidock.com/rails/ActionView/Helpers/CaptureHelper/content_for


问:
How to list opened sql server connections and close the specific one
We have a remote SQL server and c# ERP client programs that use it. Sometimes people are opening the program and forget to close it. In that situation, their SQL connections are staying opened and I won't be able to do some operations.

Yes, I can do this from the client side by setting a timer and keep checking if they do any operations or they are AFK but, I want the power to close the connections without the client side's volition.

To sum up,
1- Is there any way to check the open all connections to the server and list them by a SQL query or command.
2- Force to close the specific connection I want even they are sleeping or not?

Any help would be appreciated. Thank you so much.

答:
For Listing:

```<code>select *
from sys.dm_exec_sessions
</code>```

For Killing specific connection by id:

```<code>declare @session_id     int;
set          @session_id= ''

select
    @session_id=cast(req.session_id as int) from sys.dm_exec_requests req where req.command='DbccSpaceReclaim'group by req.session_id

begin

declare @sql nvarchar(1000)
select @sql = 'kill ' +  cast(@session_id  as varchar(50))
 exec sp_executesql  @sql
end
</code>```

Body:
For Listing:

select *
from sys.dm_exec_sessions

For Killing specific connection by id:

declare @session_id     int;
set          @session_id= ''

select
    @session_id=cast(req.session_id as int) from sys.dm_exec_requests req where req.command='DbccSpaceReclaim'group by req.session_id

begin

declare @sql nvarchar(1000)
select @sql = 'kill ' +  cast(@session_id  as varchar(50))
 exec sp_executesql  @sql
end


问:
Get value of element created at "future"
How to check element value if it will be create at the "future" on page.  I know about live method but it works with an event.</p>

答:
Since live requires an event, you could have a look at the livequery plugin for jQuery.

Let's say you want to alert the value of a every dynamically created <input type="text"> with a class of foo, you'd do something like this:

```<code>$('input[type=text].foo').livequery(function(){
  alert($(this).val());
});
</code>```

Here's a working example: http://jsfiddle.net/W7xqk/

Body:
Since live requires an event, you could have a look at the livequery plugin for jQuery.

Let's say you want to alert the value of a every dynamically created <input type="text"> with a class of foo, you'd do something like this:

$('input[type=text].foo').livequery(function(){
  alert($(this).val());
});

Here's a working example: http://jsfiddle.net/W7xqk/


问:
Formatting and Setting Phone Number in input field in reactjs
Hello I am quite a beginner in reactjs.

My current use case is very simple, I have an input field that is to accept a phone number and format it as the user is typing.Unfortunately it turns out that the input fields freezes and refuses to accept further inputs as I start formatting

Here is my code

```<code>import { parsePhoneNumberFromString } from 'libphonenumber-js';

export default function UpdatePhoneDetails() {
  const [phoneNumber, setPhoneNumber] = useState('');

  const updatePhoneNumber = (value) => {
    const newPhoneNumber = parsePhoneNumberFromString(value, 'NG');
    if (newPhoneNumber) {
      const formattedNumber = newPhoneNumber.number;
      const valid = newPhoneNumber.isValid();
      if (valid) {
        setPhoneNumber(formattedNumber); //The input field seems to be freezing here
      }
    }
  };

  return (
    <TextField
      variant="outlined"
      required
      fullWidth
      id="phonenumber"
      label="Phone Number"
      name="phonenumber"
      autoFocus
      value={phoneNumber}
      defaultValue={phoneNumber}
      disabled={updating}
      autoComplete="phonenumber"
      onChange={(event) => updatePhoneNumber(event.target.value)}
    />
  );
}
</code>```

Thanks for your anticipated help.

答:
updatePhoneNumber function only updates value if phone number is valid so when the user is still typing it won't let you do any changes.

You can set error if phone number is invalid and replace text with newPhoneNumber.number otherwise

const { TextField } = window.MaterialUI;
const { useState, useEffect } = React;
const { parsePhoneNumberFromString } = libphonenumber;
//console.log(Object.keys(libphonenumber));

const App = () => {
  const [text, setText] = useState('');
  const [error, setError] = useState(null);

  const onChange = ({target: {value}}) => {
    let valid = true;
    const newPhoneNumber = parsePhoneNumberFromString(value, "NG");

    if (newPhoneNumber) {
      valid = newPhoneNumber.isValid();

      if(valid) {
        value = newPhoneNumber.number;
      }
    }

    setError(!valid);
    setText(value);
  }

return

  <TextField
    variant="outlined"
    required
    fullWidth
    id="phonenumber"
    label="Phone Number"
    name="phonenumber"
    error={!!error}
    helperText={error && 'Invalid phone number'}
    autoFocus
    value={text}
    onChange={onChange}>
  </TextField>

}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/libphonenumber-js/1.7.52/libphonenumber-js.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
<script src="https://unpkg.com/material-ui-lab-umd@4.0.0-alpha.32/material-ui-lab.development.js"></script>
<div id="root"></div></code>```

Body:
Hello I am quite a beginner in reactjs.

My current use case is very simple, I have an input field that is to accept a phone number and format it as the user is typing.Unfortunately it turns out that the input fields freezes and refuses to accept further inputs as I start formatting

Here is my code

import { parsePhoneNumberFromString } from 'libphonenumber-js';

export default function UpdatePhoneDetails() {
  const [phoneNumber, setPhoneNumber] = useState('');

  const updatePhoneNumber = (value) => {
    const newPhoneNumber = parsePhoneNumberFromString(value, 'NG');
    if (newPhoneNumber) {
      const formattedNumber = newPhoneNumber.number;
      const valid = newPhoneNumber.isValid();
      if (valid) {
        setPhoneNumber(formattedNumber); //The input field seems to be freezing here
      }
    }
  };

  return (
    <TextField
      variant="outlined"
      required
      fullWidth
      id="phonenumber"
      label="Phone Number"
      name="phonenumber"
      autoFocus
      value={phoneNumber}
      defaultValue={phoneNumber}
      disabled={updating}
      autoComplete="phonenumber"
      onChange={(event) => updatePhoneNumber(event.target.value)}
    />
  );
}

Thanks for your anticipated help.

Body:
updatePhoneNumber function only updates value if phone number is valid so when the user is still typing it won't let you do any changes.

You can set error if phone number is invalid and replace text with newPhoneNumber.number otherwise

const { TextField } = window.MaterialUI;
const { useState, useEffect } = React;
const { parsePhoneNumberFromString } = libphonenumber;
//console.log(Object.keys(libphonenumber));

const App = () => {
  const [text, setText] = useState('');
  const [error, setError] = useState(null);

  const onChange = ({target: {value}}) => {
    let valid = true;
    const newPhoneNumber = parsePhoneNumberFromString(value, "NG");

    if (newPhoneNumber) {
      valid = newPhoneNumber.isValid();

      if(valid) {
        value = newPhoneNumber.number;
      }
    }

    setError(!valid);
    setText(value);
  }

return <div>
  <TextField
    variant="outlined"
    required
    fullWidth
    id="phonenumber"
    label="Phone Number"
    name="phonenumber"
    error={!!error}
    helperText={error && 'Invalid phone number'}
    autoFocus
    value={text}
    onChange={onChange}>
  </TextField>
</div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/libphonenumber-js/1.7.52/libphonenumber-js.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
<script src="https://unpkg.com/material-ui-lab-umd@4.0.0-alpha.32/material-ui-lab.development.js"></script>
<div id="root"></div>


问:
MDX query in SSAS calculated member
I tried the MDX Query in SQL correctly
But I will insert that query in the VisualStudio(SSAS) in the Calculated Members section, but the process time will be faulty

```<code>Select
[Measures].[Fact Student Status Count]on columns
From [Cube_REG_Amozesh DW]
Where ( [Dim Student Status].[Student Status Key].[Student Status Key]-[Dim Student Status].[Student Status Key].&[0])
</code>```

I get the following error:

Severity  Code    Description Project File    Line    Suppression State
  Error     MdxScript(Cube_REG_Amozesh DW) (2, 5) Parser: The syntax for
  'Select' is incorrect. (CREATE DYNAMIC SET CURRENTCUBE.[RegSt]  AS
  Select   [Measures].[Fact Student Status Count]on columns from
  [Cube_REG_Amozesh DW] where ( [Dim Student Status].[Student Status
  Key].[Student Status Key]-[Dim Student Status].[Student Status
  Key].&[0]), DISPLAY_FOLDER = 'شاخص'  ; ).         0

答:
Based on your query, this is what you should be putting in Calculated measure

```<code>Sum({[Dim Student Status].[Student Status Key].[Student Status Key]-[Dim Student Status].[Student Status Key].&[0]},[Measures].[Fact Student Status Count]).
</code>```

Plus make sure you uses Calculated measure not Set

Title: MDX query in SSAS calculated member

Body:
I tried the MDX Query in SQL correctly
But I will insert that query in the VisualStudio(SSAS) in the Calculated Members section, but the process time will be faulty

Select
[Measures].[Fact Student Status Count]on columns
From [Cube_REG_Amozesh DW]
Where ( [Dim Student Status].[Student Status Key].[Student Status Key]-[Dim Student Status].[Student Status Key].&[0])

I get the following error:

Severity  Code    Description Project File    Line    Suppression State
  Error     MdxScript(Cube_REG_Amozesh DW) (2, 5) Parser: The syntax for
  'Select' is incorrect. (CREATE DYNAMIC SET CURRENTCUBE.[RegSt]  AS
  Select   [Measures].[Fact Student Status Count]on columns from
  [Cube_REG_Amozesh DW] where ( [Dim Student Status].[Student Status
  Key].[Student Status Key]-[Dim Student Status].[Student Status
  Key].&[0]), DISPLAY_FOLDER = 'شاخص'  ; ).         0

Body:
Based on your query, this is what you should be putting in Calculated measure

Sum({[Dim Student Status].[Student Status Key].[Student Status Key]-[Dim Student Status].[Student Status Key].&[0]},[Measures].[Fact Student Status Count]).

Plus make sure you uses Calculated measure not Set


问:
How do i assign a variable to a eval / exec value?
is it possible to assign a variable to a exec / eval value?
this is what i tried

def execute ():
    run_wn = tk.Tk()
    des1 = tk.Label(run_wn, text = "------------------------------").pack()
    run_value = exec(cmd.get("1.0", "end"))
    value = tk.Label(run_wn, text = run_value)
    des2 = tk.Label(run_wn, text = "------------------------------").pack()
    run_wn.mainloop
bt = tk.Button(wn, text = "run", command = execute).pack()

```

the cmd is a text box..
when i execute this code then it does not return anything in the run screen.
it prints it
is there any way you can asign a value to a exec / eval value and and use it as text in a Label??

this is just a experimental project..

help will be very appreciated!!

thanks

答:
exec takes two other positional arguments, dictionaries for globals and locals, so you could exec like this to capture results in a dict:

In [1]: ns = {}
In [2]: exec("p = 1 + 2", globals(), ns)

In [3]: ns
Out[3]: {'p': 3}
```

Exec'ing untrusted code is dangerous. Don't do it if you're mixing user input into the commands unless you really know what you're doing.

Body:
is it possible to assign a variable to a exec / eval value?
this is what i tried

def execute ():
    run_wn = tk.Tk()
    des1 = tk.Label(run_wn, text = "------------------------------").pack()
    run_value = exec(cmd.get("1.0", "end"))
    value = tk.Label(run_wn, text = run_value)
    des2 = tk.Label(run_wn, text = "------------------------------").pack()
    run_wn.mainloop
bt = tk.Button(wn, text = "run", command = execute).pack()

the cmd is a text box..
when i execute this code then it does not return anything in the run screen.
it prints it
is there any way you can asign a value to a exec / eval value and and use it as text in a Label??

this is just a experimental project..

help will be very appreciated!!

thanks

Body:
exec takes two other positional arguments, dictionaries for globals and locals, so you could exec like this to capture results in a dict:

In [1]: ns = {}
In [2]: exec("p = 1 + 2", globals(), ns)

In [3]: ns
Out[3]: {'p': 3}

Exec'ing untrusted code is dangerous. Don't do it if you're mixing user input into the commands unless you really know what you're doing.


问:
Should <EOS> and <BOS> tags be explictly added to vocabulary after using keras.preprocessing.text Tokenizer?
In Keras we have keras.preprocessing.text to tokenize the text on our requirement and generate a voabulary.

```<code>tokenizer = tf.keras.preprocessing.text.Tokenizer(split=' ',  oov_token=1)
tokenizer.fit_on_texts(["Hello world"])
seqs = tokenizer.texts_to_sequences(["Hello world"])
</code>```

What I am not sure is whether to add End of Sequence (EOS) tag and Beginning of Sequence (BOS) tags explicitly if we are feeding the generated seqs to a neural network like RNN after padding the seq to fixed length. Or, does Keras do it for us? (I have not seen any example of adding EOS and BOS explicitly when using Keras tokenizer)

答:
No, it is not required to add <EOS> <BOS> for the tf.keras.preprocessing.text.Tokenizer

Since the index_word mapping works in the order starting with the oov_token and next preference is for the words having highest frequency and followed by words in the same order as the input.
This helps Keras API to process the mapping internally unlike other text preprocessing API's which uses <START> and <END> tag.

Below is the example with the sample sentences to show index_word mapping.

```<code>text_data = ["this is the sample sentence",
            "one more sentence"]

lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(oov_token="<UNK>")
lang_tokenizer.fit_on_texts(text_data)
lang_tokenizer.index_word
</code>```

index_word:

```<code>{1: '<UNK>',
 2: 'sentence',
 3: 'this',
 4: 'is',
 5: 'the',
 6: 'sample',
 7: 'one',
 8: 'more'}
</code>```

Testing:

```<code>res = lang_tokenizer.texts_to_sequences(["testing with sample sentence"])
</code>```

[[1, 1, 6, 2]]

Hope this answeres your question, Happy Learning!

Body:
In Keras we have keras.preprocessing.text to tokenize the text on our requirement and generate a voabulary.

tokenizer = tf.keras.preprocessing.text.Tokenizer(split=' ',  oov_token=1)
tokenizer.fit_on_texts(["Hello world"])
seqs = tokenizer.texts_to_sequences(["Hello world"])

What I am not sure is whether to add End of Sequence (EOS) tag and Beginning of Sequence (BOS) tags explicitly if we are feeding the generated seqs to a neural network like RNN after padding the seq to fixed length. Or, does Keras do it for us? (I have not seen any example of adding EOS and BOS explicitly when using Keras tokenizer)

Body:
No, it is not required to add <EOS> <BOS> for the tf.keras.preprocessing.text.Tokenizer

Since the index_word mapping works in the order starting with the oov_token and next preference is for the words having highest frequency and followed by words in the same order as the input.
This helps Keras API to process the mapping internally unlike other text preprocessing API's which uses <START> and <END> tag.

Below is the example with the sample sentences to show index_word mapping.

text_data = ["this is the sample sentence",
            "one more sentence"]

lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(oov_token="<UNK>")
lang_tokenizer.fit_on_texts(text_data)
lang_tokenizer.index_word

index_word:

{1: '<UNK>',
 2: 'sentence',
 3: 'this',
 4: 'is',
 5: 'the',
 6: 'sample',
 7: 'one',
 8: 'more'}

Testing:

res = lang_tokenizer.texts_to_sequences(["testing with sample sentence"])

[[1, 1, 6, 2]]

Hope this answeres your question, Happy Learning!


问:
How to generate random color names in C#
I need to generate random color names e.g. "Red", "White" etc. How can I do it? I am able to generate random color like this:

```<code>Random randonGen = new Random();
Color randomColor = Color.FromArgb(randonGen.Next(255), randonGen.Next(255),
randonGen.Next(255));
</code>```

but I need the names and not all colors generated like this have a known name.

Thanks

答:
If you wanted to get random color from specific colors list,

then try below one

```<code>Color[] colors = new[] { Color.Red, Color.Blue, Color.FromArgb(128, 128, 255) };    //Add your favorite colors list
Random randonGen = new Random();
Color randomColor = colors[Generator.Next(0, colors.Length)];    //It will choose random color from "colors" array
</code>```

Body:
I need to generate random color names e.g. "Red", "White" etc. How can I do it? I am able to generate random color like this:

Random randonGen = new Random();
Color randomColor = Color.FromArgb(randonGen.Next(255), randonGen.Next(255),
randonGen.Next(255));

but I need the names and not all colors generated like this have a known name.

Thanks

Body:
If you wanted to get random color from specific colors list,

then try below one

Color[] colors = new[] { Color.Red, Color.Blue, Color.FromArgb(128, 128, 255) };    //Add your favorite colors list
Random randonGen = new Random();
Color randomColor = colors[Generator.Next(0, colors.Length)];    //It will choose random color from "colors" array


问:
ERROR ITMS-90685: "CFBundleIdentifier Collision. There is more than one bundle"
When I am try to submit my app to app store, I am getting the error:

ERROR ITMS-90685: "CFBundleIdentifier Collision. There is more than
  one bundle with the CFBundleIdentifier value
  com.companyname.projectName under the application ProjectName.app"

Can any one help me?

答:
This seems to be a long standing bug that is even present with Swift Package Manager. For the build phase of the extensions, I added this "Run Script" as the last step:

```<code>cd "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/"
if [[ -d "Frameworks" ]]; then
    rm -fr Frameworks
fi
</code>```

This removes the duplicate framework it's complaining about during archiving, which will be linked from the host target anyway. We just need it to be linked in Xcode for the extension so we can compile at development time.

Body:
This seems to be a long standing bug that is even present with Swift Package Manager. For the build phase of the extensions, I added this "Run Script" as the last step:

cd "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/"
if [[ -d "Frameworks" ]]; then
    rm -fr Frameworks
fi

This removes the duplicate framework it's complaining about during archiving, which will be linked from the host target anyway. We just need it to be linked in Xcode for the extension so we can compile at development time.


问:
Extending, instead of overwriting, the prototype
In our current codebase, we are creating classes like this

```<code>my_class = function(){
  //do some constructor stuff
}

my_class.prototype = {
  var1 : 'value',
  var2 : 'value',
  var3 : 'value'
  .
  .
  .
  //etc
}
</code>```

There are several classes like this that I would like to inherit a super class.  However, if I do something like this, I end up overwriting the superclass' prototype.

```<code>my_super_class = function(){

}

my_super_class.prototype.generic_function = function(){
  //all subclasses should have this function
}

my_subclass = function(){
  //constructory stuff
}

//inherit the superclass
my_class.prototype = new my_super_class();

my_class.prototype = {
  //oops, there goes my superclass prototype...
  var1 : 'value',
  var2 : 'value',
  var3 : 'value'
  .
  .
  .
  //etc
}
</code>```

Is there a better way to do this than do my_class.prototype.val1 = 'value'; ... etc after inheriting the superclass?  I would like to follow the convention from our current codebase because it is short and to the point.

答:
I'm also struggling to find a nice syntax for those things in JavaScript, but I've seen something like this:

```<code>// inherit the superclass
myClass.prototype = new mySuperClass();

(function() {
    this.var1 = 'value';
    this.var2 = 'value';
    // etc.
}).call(myClass.prototype);
</code>```

Which seems nicer than writing myClass.prototype all the time.

ContentLicense: CC BY-SA 2.5

Body:
In our current codebase, we are creating classes like this

my_class = function(){
  //do some constructor stuff
}

my_class.prototype = {
  var1 : 'value',
  var2 : 'value',
  var3 : 'value'
  .
  .
  .
  //etc
}

There are several classes like this that I would like to inherit a super class.  However, if I do something like this, I end up overwriting the superclass' prototype.

my_super_class = function(){

}

my_super_class.prototype.generic_function = function(){
  //all subclasses should have this function
}

my_subclass = function(){
  //constructory stuff
}

//inherit the superclass
my_class.prototype = new my_super_class();

my_class.prototype = {
  //oops, there goes my superclass prototype...
  var1 : 'value',
  var2 : 'value',
  var3 : 'value'
  .
  .
  .
  //etc
}

Is there a better way to do this than do my_class.prototype.val1 = 'value'; ... etc after inheriting the superclass?  I would like to follow the convention from our current codebase because it is short and to the point.

Body:
I'm also struggling to find a nice syntax for those things in JavaScript, but I've seen something like this:

// inherit the superclass
myClass.prototype = new mySuperClass();

(function() {
    this.var1 = 'value';
    this.var2 = 'value';
    // etc.
}).call(myClass.prototype);

Which seems nicer than writing myClass.prototype all the time.


问:
Supressing stdout in particular process
I have a Python script that executes two main tasks:

Execute code from the script itself

Launch a background process with multiprocessing.Process(target=...)

My question is: Is there any way of muting the stdout from that particular process without affecting the main process? I've tried to change it through sys.stdout, but it affects every single process and the main process (every instance of the program points to the same object):

>>> import multiprocessing
>>> import sys
>>> def a():
...     print('{} - {}'.format(sys.stdout, id(sys.stdout)))
...
>>> for i in range(5):
...     multiprocessing.Process(target=a).start()
...
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
>>> <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232

>>> a()
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
```

It is not possible to delete all print() statements from the function being executed by the process, since another routine of the program calls that function on the main process and it needs those print statements.

I also noticed that I could use a boolean flag to indicate whether the print should be executed or not, but I was hoping that anyone could give me a better approach.

Thank you very much!

答:
You have to do it inside the process, after fork. This is a bit crude, but seems to be working:

#!/usr/bin/env python3

import multiprocessing
import sys

class SinkLogger(object):
    def __init__(self):
        pass

    def write(self, message):
        pass

    def flush(self):
        pass

def a(i):
    if (i % 2 == 1):
        sys.stdout = SinkLogger()
    print('{} - {} - {}'.format(i, sys.stdout, id(sys.stdout)))

for i in range(5):
    multiprocessing.Process(target=a, args=(i,)).start()

print("done")
```

Source of the idea: How to redirect stdout to both file and console with scripting?

Title: Supressing stdout in particular process

Body:
I have a Python script that executes two main tasks:

Execute code from the script itself

Launch a background process with multiprocessing.Process(target=...)

My question is: Is there any way of muting the stdout from that particular process without affecting the main process? I've tried to change it through sys.stdout, but it affects every single process and the main process (every instance of the program points to the same object):

>>> import multiprocessing
>>> import sys
>>> def a():
...     print('{} - {}'.format(sys.stdout, id(sys.stdout)))
...
>>> for i in range(5):
...     multiprocessing.Process(target=a).start()
...
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232
>>> <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232

>>> a()
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> - 140230387621232

It is not possible to delete all print() statements from the function being executed by the process, since another routine of the program calls that function on the main process and it needs those print statements.

I also noticed that I could use a boolean flag to indicate whether the print should be executed or not, but I was hoping that anyone could give me a better approach.

Thank you very much!

Body:
You have to do it inside the process, after fork. This is a bit crude, but seems to be working:

#!/usr/bin/env python3

import multiprocessing
import sys

class SinkLogger(object):
    def __init__(self):
        pass

    def write(self, message):
        pass

    def flush(self):
        pass

def a(i):
    if (i % 2 == 1):
        sys.stdout = SinkLogger()
    print('{} - {} - {}'.format(i, sys.stdout, id(sys.stdout)))

for i in range(5):
    multiprocessing.Process(target=a, args=(i,)).start()

print("done")

Source of the idea: How to redirect stdout to both file and console with scripting?


问:
How to link source files into Eclipse based IDE
I am now at the beginning of software project for Xilinx Zynq SoC hardware platform. Xilinx company offers for software development their own Eclipse based IDE called Vitis. Due to version control reasons I need to have application source codes and custom IP peripheral drivers source codes in separate directories  (let´s say App_src and Drivers_src) and I need to link the Vitis project with the aforementioned source codes in such a manner that the source codes modification occurs in the directory which is under version control. It means that I need to prevent any copying of source codes into the workspace. Can anybody tell me how to resolve that in system manner i.e. with respect to the version control system usage? Thanks in advance for any ideas. </p>

答: When you import an existing project (File > Import... > Existing Project into Workspace) do not check the Copy projects into workspace checkbox to import the project into Eclipse IDE's workspace without moving its sources.


问:
How to use a semi circle inside a container like in this image in flutter?
I'm trying to make semi circle like in image inside container i have tried a lot but couldn't figure out how to make this

Now let me explain what i have tried so far and how i got the result

I have tried using custompainter class but am getting result like this:

```<code>enum CircleAlignment {
  topLeft,
  topRight,
  bottomLeft,
  bottomRight,
}

class QuarterCirclePainter extends CustomPainter {
  final CircleAlignment circleAlignment;
  final Color color;

  const QuarterCirclePainter({this.circleAlignment, this.color});

  @override
  void paint(Canvas canvas, Size size) {
    final radius = math.min(size.height, size.width-80);
    final offset = circleAlignment == CircleAlignment.topLeft
        ? Offset(.0, .0)
        : circleAlignment == CircleAlignment.topRight
        ? Offset(size.width, 5)
        : circleAlignment == CircleAlignment.bottomLeft
        ? Offset(.0, size.height+10)
        : Offset(size.width, size.height);
    canvas.drawCircle(offset, radius, Paint()..color = color);
  }

  @override
  bool shouldRepaint(QuarterCirclePainter oldDelegate) {
    return color == oldDelegate.color &&
        circleAlignment == oldDelegate.circleAlignment;
  }
}
</code>```

But am getting result like this:

Anyone got idea how to do this?

答:
Below is an example of a text being at the centre of a circle.

You can just replace the text with your image, can also choose where you would like to align the child in your case the image widget

```<code>class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 500,
      height: 250,
      color: Colors.pink,
      child: Align(
        alignment: Alignment.topRight,
        child: Container(
            width: 100,
            height: 100,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(90)),
                border: Border.all(width: 3, color: Colors.green, style: BorderStyle.solid)),
            child: Align(alignment: Alignment.center, child: Text('asdasd'))),
      ),
    );
  }
}
</code>```

I have edited so that curve is only one side of the border now. on the top left as you expect

Edit:

Not ideal semi curve on top right, however close, I think you can play around with the radius values, and find what you want @M.Yogeshwaran

```<code>class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return         Container(
      width: 500,
      height:250,
      color: Colors.pink,
      child: Align(
        alignment: Alignment.topRight,
        child: RotatedBox(
          quarterTurns: 1,
          child: Container(
                      width: 115,
                      height: 125,

                      decoration: BoxDecoration(
                        color: Colors.orange,
          borderRadius: BorderRadius.only(bottomLeft:  Radius.circular(60), bottomRight:  Radius.circular(80), topRight:  Radius.circular(60)),
          border: Border.all(width: 3,color: Colors.green,style: BorderStyle.none)
          ),
                      child: Align(
                        alignment: Alignment.center,
                        child: Text('asdasd'))),
        ),
      ),
    );
  }
}
</code>```

Body:
I'm trying to make semi circle like in image inside container i have tried a lot but couldn't figure out how to make this

Now let me explain what i have tried so far and how i got the result

I have tried using custompainter class but am getting result like this:

enum CircleAlignment {
  topLeft,
  topRight,
  bottomLeft,
  bottomRight,
}

class QuarterCirclePainter extends CustomPainter {
  final CircleAlignment circleAlignment;
  final Color color;

  const QuarterCirclePainter({this.circleAlignment, this.color});

  @override
  void paint(Canvas canvas, Size size) {
    final radius = math.min(size.height, size.width-80);
    final offset = circleAlignment == CircleAlignment.topLeft
        ? Offset(.0, .0)
        : circleAlignment == CircleAlignment.topRight
        ? Offset(size.width, 5)
        : circleAlignment == CircleAlignment.bottomLeft
        ? Offset(.0, size.height+10)
        : Offset(size.width, size.height);
    canvas.drawCircle(offset, radius, Paint()..color = color);
  }

  @override
  bool shouldRepaint(QuarterCirclePainter oldDelegate) {
    return color == oldDelegate.color &&
        circleAlignment == oldDelegate.circleAlignment;
  }
}

But am getting result like this:

Anyone got idea how to do this?

Body:
Below is an example of a text being at the centre of a circle.

You can just replace the text with your image, can also choose where you would like to align the child in your case the image widget

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 500,
      height: 250,
      color: Colors.pink,
      child: Align(
        alignment: Alignment.topRight,
        child: Container(
            width: 100,
            height: 100,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(90)),
                border: Border.all(width: 3, color: Colors.green, style: BorderStyle.solid)),
            child: Align(alignment: Alignment.center, child: Text('asdasd'))),
      ),
    );
  }
}

I have edited so that curve is only one side of the border now. on the top left as you expect

Edit:

Not ideal semi curve on top right, however close, I think you can play around with the radius values, and find what you want @M.Yogeshwaran

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return         Container(
      width: 500,
      height:250,
      color: Colors.pink,
      child: Align(
        alignment: Alignment.topRight,
        child: RotatedBox(
          quarterTurns: 1,
          child: Container(
                      width: 115,
                      height: 125,

                      decoration: BoxDecoration(
                        color: Colors.orange,
          borderRadius: BorderRadius.only(bottomLeft:  Radius.circular(60), bottomRight:  Radius.circular(80), topRight:  Radius.circular(60)),
          border: Border.all(width: 3,color: Colors.green,style: BorderStyle.none)
          ),
                      child: Align(
                        alignment: Alignment.center,
                        child: Text('asdasd'))),
        ),
      ),
    );
  }
}


问:
How to create a json object from two arrays in JavaScript
I have the following arrays

```<code>['a','b','c','d','e','f']

[1762, 770, 93, 474, 323, 351]
</code>```

I would like to convert them into a list of json objects so that I end up with an object that looks a bit like this

```<code>{
  "SomeObject": [
    {
      "name": "a",
      "value": 1762
    },
    {
      "name": "b",
      "value": 770
    },
    {
      "name": "c",
      "value": 93
    },
    {
      "name": "d",
      "value": 474
    },
    {
      "name": "e",
      "value": 323
    },
    {
      "name": "f",
      "value": 351
    }
  ]
}
</code>```

How can I concert these arrays to the above object in JavaScript.

Thank you in advance

答:
const keys = ['a','b','c','d','e','f'];
const values = [1762, 770, 93, 474, 323, 351];

const result = keys.map((key, i) => ({ name: key, value: values[i] }));

console.log(result);```

Body:
I have the following arrays

['a','b','c','d','e','f']

[1762, 770, 93, 474, 323, 351]

I would like to convert them into a list of json objects so that I end up with an object that looks a bit like this

{
  "SomeObject": [
    {
      "name": "a",
      "value": 1762
    },
    {
      "name": "b",
      "value": 770
    },
    {
      "name": "c",
      "value": 93
    },
    {
      "name": "d",
      "value": 474
    },
    {
      "name": "e",
      "value": 323
    },
    {
      "name": "f",
      "value": 351
    }
  ]
}

How can I concert these arrays to the above object in JavaScript.

Thank you in advance


问:
Return React component as object value and bind props to it
There's one global hook which returns react components when used:

const { SomeComponent1, SomeComponent2 } = useHook({ prop1, prop2 })
```

<p>How do I pass props to the components I am returning from the hook?</p>

<pre class="lang-js prettyprint-override"><code>const useHook = ({ prop1, prop2 }) => {

  return {
    SomeComponent1, // <-- I'd like to 'bind' props to the component here
    SomeComponent2,
    // THE CODE BELOW IS INCORRECT
    // it's a way to illustrate what I am after:
    // SomeComponent1: <SomeComponent1 prop1={prop1} />
  }
}
</code>```

Passing the props down to destructed react components is a no-go for me:

const { Comp1, Comp2 } = useHook()

return (
  <Comp1 prop={prop1} />
)
```

答:
The most common and elegant solution will be conditional based rendering. You can use a ternary based operator to display your component For eg. </p>

```<code>import React,{useState} from "react";
import {Comp1} from "./comp1";
import {Comp2} from "./comp2";
function Test(){
    const [display,setDisplay] = useState(true);
    render(){
        <>
            {display ? <Comp1 props={props} /> : <Comp2 props={props} /> }
        </>
    }
}
</code>```

Body:
There's one global hook which returns react components when used:

const { SomeComponent1, SomeComponent2 } = useHook({ prop1, prop2 })

How do I pass props to the components I am returning from the hook?

const useHook = ({ prop1, prop2 }) => {

  return {
    SomeComponent1, // <-- I'd like to 'bind' props to the component here
    SomeComponent2,
    // THE CODE BELOW IS INCORRECT
    // it's a way to illustrate what I am after:
    // SomeComponent1: <SomeComponent1 prop1={prop1} />
  }
}

Passing the props down to destructed react components is a no-go for me:

const { Comp1, Comp2 } = useHook()

return (
  <Comp1 prop={prop1} />
)

Body:
The most common and elegant solution will be conditional based rendering. You can use a ternary based operator to display your component For eg.

import React,{useState} from "react";
import {Comp1} from "./comp1";
import {Comp2} from "./comp2";
function Test(){
    const [display,setDisplay] = useState(true);
    render(){
        <>
            {display ? <Comp1 props={props} /> : <Comp2 props={props} /> }
        </>
    }
}


问:
Determine the number of "clumps" in array of integers
A clump in an array is defined as a series of 2 or more adjacent elements of the same value. For example:

```<code>{3, 4, 5, 5, 5, 6, 2, 2}
</code>```

contains 2 clumps comprising 1 clump of 5's and one of 2's. (assume every array has at least 1 element)

I need to write a method to return the number of clumps in a given array:

```<code>public int countClumps(int[] nums) {
    int totalClumps = 0;
    for (int i = 0; i < nums.length; i++) {
        int a = 1;
        while (nums[i] == nums[i+a] && (i+a) < nums.length) {
            a++;
        }
        if (a != 1) {
            totalClumps++;
            i += (a - 1);
        }
        a = 1;
    }
}
</code>```

This is the closest I have gotten to solving.  What would I change so that it works?

答:
Please try the below one.

```<code>int[] arr = new int[]{3, 4, 5, 5, 5, 6, 2, 2};

IntStream.of(arr).filter( data -> Collections.frequency(Arrays.asList(arr), data) >1)
.distinct()
.forEach( data -> { System.out.println(data );} );
</code>```

Output is 5 and 2

Body:
A clump in an array is defined as a series of 2 or more adjacent elements of the same value. For example:

{3, 4, 5, 5, 5, 6, 2, 2}

contains 2 clumps comprising 1 clump of 5's and one of 2's. (assume every array has at least 1 element)

I need to write a method to return the number of clumps in a given array:

public int countClumps(int[] nums) {
    int totalClumps = 0;
    for (int i = 0; i < nums.length; i++) {
        int a = 1;
        while (nums[i] == nums[i+a] && (i+a) < nums.length) {
            a++;
        }
        if (a != 1) {
            totalClumps++;
            i += (a - 1);
        }
        a = 1;
    }
}

This is the closest I have gotten to solving.  What would I change so that it works?

Body:
Please try the below one.

int[] arr = new int[]{3, 4, 5, 5, 5, 6, 2, 2};

IntStream.of(arr).filter( data -> Collections.frequency(Arrays.asList(arr), data) >1)
.distinct()
.forEach( data -> { System.out.println(data );} );

Output is 5 and 2


问:
How to set an "Access-Control-Allow-Origin" header to only allow one certain computer
I have a some node.js code in a glitch server (not in my own computer) :

let http = require("http");
http.createServer((req, res) => {
  res.writeHead(200, {
    "Allow-Access-Control-Origin": "http://my-localhost-IP-Address"
  });
  res.end(someData)
})
```

That doesn't seem to work for me.
I can't do it from my localhost, nor can I do it in the file: protocol, but I can make it by simply typing the url in the browser.

Setting Access-Control-Allow-Origin to http://localhost doesn't work either.

Is there a way I can set the "Access-Control-Allow-Origin" header to only allow some specific computers to access it.

Note: Again, the code is in a server in the internet, not in my own computer.

答:
You can use CORS

```<code>let cors = require("cors");

app.use(cors(), function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
</code>```

In this, you can also add multiple URLs.

Body:
I have a some node.js code in a glitch server (not in my own computer) :

let http = require("http");
http.createServer((req, res) => {
  res.writeHead(200, {
    "Allow-Access-Control-Origin": "http://my-localhost-IP-Address"
  });
  res.end(someData)
})

That doesn't seem to work for me.
I can't do it from my localhost, nor can I do it in the file: protocol, but I can make it by simply typing the url in the browser.

Setting Access-Control-Allow-Origin to http://localhost doesn't work either.

Is there a way I can set the "Access-Control-Allow-Origin" header to only allow some specific computers to access it.

Note: Again, the code is in a server in the internet, not in my own computer.

Body:
You can use CORS

let cors = require("cors");

app.use(cors(), function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:4200"); // update to match the domain you will make the request from
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

In this, you can also add multiple URLs.


问:
Is there a way to use Sharepoint version history to make a calculated column value?
I cannot see a way to do this natively, but essentially I would like to tap into the version history for a specific field value to calculate the difference between the current value and the last entered value.

Scenario:
Business user will update a numeric value in a column for each list item once a week to a cumulative amount. (i.e. Sales made to date)

I am currently able to see in the version history what the last entered value was, who entered it, and when it was entered. I want to know if there is a way to access this information in the form of a calculated column to find this difference (i.e. sales made this week). The solution I am thinking is adding another column for "Total Sales Last Week" and have the user manually update that when they update "Total Sales This Week" then have a calculated column to just subtract these values. However, this seems tedious since the information is already in Sharepoint. If there is a way to do this either with a calculated column, PowerAutomate flow or another method please let me know.

答:
It is not possible to capture the Version History using calculated column. REST API is the only option that will be helpful to fetch these details. Considering this, there are two solutions that I can suggest here:

Using REST API

Create an additional column in your list and update it with the data that you will capture from version history using SharePoint REST API. Here, Rest API will be used to fetch the version history and also to update the list item.

As a trigger event to execute this code, Either you can setup a button on the page (if using any custom screen) or set this to execute periodically.

Using REST API in Power Automate (Recommended)

Power Automate/MS Flow doesn't provide any direct connector to fetch the version history but you can use the HTTP request connector which will help you to execute the SP rest call to fetch the version history.

Once you have version history data from your HTTP request call, you can use that to update the column in your list using the same power automate in next action.

This solution will be more useful as you don't need to setup any trigger event as mentioned in the first solution but instead of that you can simply configure this Power Automate to run as and when list item is updated and you will be having immediate result in your list.

You can refer to this link to check how to get data from HTTP request using Power automate and you can also refer to this link which will help you to understand how to get version history using SharePoint rest API.

I hope this will be useful information for you to achieve your goal.


问:
Getting filenames in the right alphanumerical order
I'm having trouble with this command (suspect it's bash related, and not program specific)

```<code>montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#ffffff' -fill 'gray' -auto-orient  -tile 8x6 -geometry 200x200+2+2 ./*.bluemap.jpg /media/
</code>```

The problem is that it starts with the file 100002.bluemap.jpg, not the lowest  number which is 2016.bluemap.jpg

All numbers don't exist, for example the next after 2016 is 6438, 6685,9879

Is there anyway to get it to do the job correctly, the right order?

Or do I need to create some list or something?

I'm little lost..

答:
A variant of @oguz ismail's answer using xargs to stream the file-names arguments rather than a Bash array.

printf '%s\0' ./*.bluemap.jpg |
  sort -z -t/ -k2n |
    xargs -0 sh -c '
montage \
 -verbose \
 -label "%f" \
 -font "Helvetica" \
 -pointsize 10 \
 -background "#ffffff" \
 -fill "gray" \
 -auto-orient \
 -tile 8x6 \
 -geometry 200x200+2+2 \
 "$@" \
 /media/
' _
```

<p>Split explanation of <code>xargs -0 sh -c</code>:</p>

<ul>
<li><code>-0</code>: The entries in the input stream are delimited by <code>null</code>.</li>
<li><code>sh -c 'script' _</code>: The command executed by <code>xargs</code> is an inline shell script whith the arguments from the input stream.</li>
</ul>

<p>Alternatively to an inline shell script:</p>

<pre class="lang-sh prettyprint-override"><code>{
  # Create the null-delimited list of input file names
  # matching the globbing pattern ./*.bluemap.jpg
  printf '%s\0' ./*.bluemap.jpg |
    # Sort the null delimited list of file names
    sort -z -t/ -k2n;
  # At this point, the null-delimited list contains the sorted input files
  # Append the `/media/` destination argument as last entry
  printf '/media/\0';
} | xargs -0 \
      montage \
        -verbose \
        -label "%f" \
        -font "Helvetica" \
        -pointsize 10 \
        -background "#ffffff" \
        -fill "gray" \
        -auto-orient \
        -tile 8x6 \
        -geometry 200x200+2+2
</code>```

Body:
I'm having trouble with this command (suspect it's bash related, and not program specific)

montage -verbose -label '%f' -font Helvetica -pointsize 10 -background '#ffffff' -fill 'gray' -auto-orient  -tile 8x6 -geometry 200x200+2+2 ./*.bluemap.jpg /media/

The problem is that it starts with the file 100002.bluemap.jpg, not the lowest  number which is 2016.bluemap.jpg

All numbers don't exist, for example the next after 2016 is 6438, 6685,9879

Is there anyway to get it to do the job correctly, the right order?

Or do I need to create some list or something?

I'm little lost..

Body:
A variant of @oguz ismail's answer using xargs to stream the file-names arguments rather than a Bash array.

printf '%s\0' ./*.bluemap.jpg |
  sort -z -t/ -k2n |
    xargs -0 sh -c '
montage \
 -verbose \
 -label "%f" \
 -font "Helvetica" \
 -pointsize 10 \
 -background "#ffffff" \
 -fill "gray" \
 -auto-orient \
 -tile 8x6 \
 -geometry 200x200+2+2 \
 "$@" \
 /media/
' _

Split explanation of xargs -0 sh -c:

-0: The entries in the input stream are delimited by null.

sh -c 'script' _: The command executed by xargs is an inline shell script whith the arguments from the input stream.

Alternatively to an inline shell script:

{
  # Create the null-delimited list of input file names
  # matching the globbing pattern ./*.bluemap.jpg
  printf '%s\0' ./*.bluemap.jpg |
    # Sort the null delimited list of file names
    sort -z -t/ -k2n;
  # At this point, the null-delimited list contains the sorted input files
  # Append the `/media/` destination argument as last entry
  printf '/media/\0';
} | xargs -0 \
      montage \
        -verbose \
        -label "%f" \
        -font "Helvetica" \
        -pointsize 10 \
        -background "#ffffff" \
        -fill "gray" \
        -auto-orient \
        -tile 8x6 \
        -geometry 200x200+2+2