问:
Realm access from incorrect thread while using realm with coroutines
I'm trying to use realm with kotlin coroutines and make queries inside a new thread using withContext()

What I observe is that threads are switching in the loop making realm throws this exception: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.

```<code>withContext(Dispatchers.IO) {
            val realm = Realm.getDefaultInstance()
            val images = mutableListOf<String>("id1", "id2", ...)
            for (imageId in images) {
                 println("THREAD : ${Thread.currentThread().name}")
                 val image = realm.where<Image>().equalTo("imageId", imageId).findFirst()
                 delay(1000) // Can lead to an actual switching to another thread
            }
            realm.close()
}
</code>```

As the dispatchers.IO documentation mention here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html

"This dispatcher shares threads with a [Default][Dispatchers.Default] dispatcher, so using
     * withContext(Dispatchers.IO) { ... } does not lead to an actual switching to another thread;
     * typically execution continues in the same thread."

I don't understand why thread are switching in the loop.
How to manage realm instance with coroutine properly ?

答:
You can run Realm in another new single thread in a Coroutine. For example</p>

```<code>val dispatcher =  Executors.newSingleThreadExecutor().asCoroutineDispatcher()
jobs.launch(dispatcher) {
  // create new Realm instance
}
</code>```

Body:
I'm trying to use realm with kotlin coroutines and make queries inside a new thread using withContext()

What I observe is that threads are switching in the loop making realm throws this exception: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.

withContext(Dispatchers.IO) {
            val realm = Realm.getDefaultInstance()
            val images = mutableListOf<String>("id1", "id2", ...)
            for (imageId in images) {
                 println("THREAD : ${Thread.currentThread().name}")
                 val image = realm.where<Image>().equalTo("imageId", imageId).findFirst()
                 delay(1000) // Can lead to an actual switching to another thread
            }
            realm.close()
}

As the dispatchers.IO documentation mention here: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html

"This dispatcher shares threads with a [Default][Dispatchers.Default] dispatcher, so using
     * withContext(Dispatchers.IO) { ... } does not lead to an actual switching to another thread;
     * typically execution continues in the same thread."

I don't understand why thread are switching in the loop.
How to manage realm instance with coroutine properly ?

Body:
You can run Realm in another new single thread in a Coroutine. For example

val dispatcher =  Executors.newSingleThreadExecutor().asCoroutineDispatcher()
jobs.launch(dispatcher) {
  // create new Realm instance
}


来源: stackexchange

问:
Application not terminated after all code executed
I'm about to learn the java threading facility.

I have 2 classes:

```<code>public class Main {
    public static void main(String[] arg) throws Exception {

        Timer timer = new Timer();
        timer.schedule(new ExecuteTimer(Thread.currentThread()), 2000);

        try {
            Thread.currentThread().join();
        } catch (InterruptedException ex) {
            System.out.println("timer stopped");
        }
        System.out.println("try block executed");
    }
}
</code>```

and the timer class:

```<code>public class ExecuteTimer extends TimerTask {
    public ExecuteTimer(Thread thread) {
        creatingThread = thread;
    }
    private Thread creatingThread;

    @Override
    public void run() {
        System.out.println("I'm executed!");
        creatingThread.interrupt();

    }

}
</code>```

When I debug the code. I have following output:

```<code>I'm executed!
timer stopped
try block executed
</code>```

Everything seems to be final except the app didn't exit after I have the output above. The eclipse remain in debug mode and no exception has been thrown.

答: After you no longer need the Timer to run tasks, you should call timer.cancel() to release its thread.

ContentLicense: CC BY-SA 3.0

Body:
I'm about to learn the java threading facility.

I have 2 classes:

public class Main {
    public static void main(String[] arg) throws Exception {

        Timer timer = new Timer();
        timer.schedule(new ExecuteTimer(Thread.currentThread()), 2000);

        try {
            Thread.currentThread().join();
        } catch (InterruptedException ex) {
            System.out.println("timer stopped");
        }
        System.out.println("try block executed");
    }
}

and the timer class:

public class ExecuteTimer extends TimerTask {
    public ExecuteTimer(Thread thread) {
        creatingThread = thread;
    }
    private Thread creatingThread;

    @Override
    public void run() {
        System.out.println("I'm executed!");
        creatingThread.interrupt();

    }

}

When I debug the code. I have following output:

I'm executed!
timer stopped
try block executed

Everything seems to be final except the app didn't exit after I have the output above. The eclipse remain in debug mode and no exception has been thrown.


问:
Android property animation: how to increase view height?
How to increase the view height using Property Animations in Android?

```<code>ObjectAnimator a = ObjectAnimator.ofFloat(viewToIncreaseHeight, "translationY", -100);
a.setInterpolator(new AccelerateDecelerateInterpolator());
a.setDuration(1000);
a.start();
</code>```

The translationY actually moves the view not increase the height. How can I increase the height of the view?

答:
Use this method in kotlin:</p>

```<code>private fun increaseViewSize(view: View) {
    val valueAnimator = ValueAnimator.ofInt(view.measuredHeight, view.measuredHeight+20)
    valueAnimator.duration = 500L
    valueAnimator.addUpdateListener {
        val animatedValue = valueAnimator.animatedValue as Int
        val layoutParams = view.layoutParams
        layoutParams.height = animatedValue
        view.layoutParams = layoutParams
    }
    valueAnimator.start()
}
</code>```

Body:
How to increase the view height using Property Animations in Android?

ObjectAnimator a = ObjectAnimator.ofFloat(viewToIncreaseHeight, "translationY", -100);
a.setInterpolator(new AccelerateDecelerateInterpolator());
a.setDuration(1000);
a.start();

The translationY actually moves the view not increase the height. How can I increase the height of the view?

Body:
Use this method in kotlin:

private fun increaseViewSize(view: View) {
    val valueAnimator = ValueAnimator.ofInt(view.measuredHeight, view.measuredHeight+20)
    valueAnimator.duration = 500L
    valueAnimator.addUpdateListener {
        val animatedValue = valueAnimator.animatedValue as Int
        val layoutParams = view.layoutParams
        layoutParams.height = animatedValue
        view.layoutParams = layoutParams
    }
    valueAnimator.start()
}

ContentLicense: CC BY-SA 4.0


问:
How to count matches in different querysets
I want to count different querysets in my template after doing a search over all models but it seems that the different querysets are in a list of lists.

my view function:

```<code>class Search(ListView):

template_name='artdb/searchResult.html'

def get_queryset(self): # override get_queryset() has to have that name...

    q=self.request.GET.get('seastr')
    models=[Person,Activity,Member,Comment]
    fields=[l._meta.fields for l in models]
    res=[]

    for i,j in enumerate(models):
        sq=[Q(**{x.name + "__icontains" : q}) for x in fields[i] if not isinstance(x,ForeignKey)]
        res+=[j.objects.filter(k) or None for k in sq]

    res=[k for k in res if k]

    if q:
        return res
    else:
        return Person.objects.none()  # SELECT ... WHERE headline ILIKE '%Lennon%';

def get_context_data(self,*args,**kwargs):

    #q=self.request.GET.get('seastr')
    context=super().get_context_data(*args,**kwargs)
    context['member']=Member.objects.all()
    return context
</code>```

context dict:

```<code>{'page_obj': None, 'view': <artdb.views.Search object at 0x7f415ec88080>, 'is_paginated': False, 'object_list': [<QuerySet [<Person: David Bolander>, <Person: adam something>]>, <QuerySet [<Comment: david bolander comment>]>], 'member': <QuerySet [<Member: 2019-11-21>, <Member: 2020-02-10>]>, 'paginator': None}
</code>```

my template:

```<code>{% extends "artdb/index.html" %}

{% block sr1 %}
    <ul>
      <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}">
        Persons: {{object_list.count}}
      </a>
      <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}">
    Activities: {{activity.count}}
      </a>
      <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}">
    Members: {{member.count}}
      </a>
      <a class="btn btn-light btn-outline-success my-2 my-sm-0" role="button" href="{% url 'artdb:search' %}">
    Comments: {{comment.count}}
      </a>
      <br></br>
</ul>
{% endblock sr1 %
</code>```

As can be seen in the template, I want to count the matches in the  tag but the querysets are stacked as lists of lists in the context dictionary. For example, member can be counted because it was added later and it is not in a list of lists. how do I solve this?

答:
ok, I found a solution to this. I insert the object_list again in the context dict:

```<code>def get_context_data(self,*args,**kwargs):

        context=super().get_context_data(*args,**kwargs)

        c=context['object_list']
        cname=[l.model.__name__ for l in c]

        for l in zip(cname,c):
            context[l[0].lower()]=l[1]

        return context
</code>```

it's not the most elegant solution and if anyone else has another solution, please share it.

Body:
I want to count different querysets in my template after doing a search over all models but it seems that the different querysets are in a list of lists.

my view function:

class Search(ListView):

template_name='artdb/searchResult.html'

def get_queryset(self): # override get_queryset() has to have that name...

    q=self.request.GET.get('seastr')
    models=[Person,Activity,Member,Comment]
    fields=[l._meta.fields for l in models]
    res=[]

    for i,j in enumerate(models):
        sq=[Q(**{x.name + "__icontains" : q}) for x in fields[i] if not isinstance(x,ForeignKey)]
        res+=[j.objects.filter(k) or None for k in sq]

    res=[k for k in res if k]

    if q:
        return res
    else:
        return Person.objects.none()  # SELECT ... WHERE headline ILIKE '%Lennon%';

def get_context_data(self,*args,**kwargs):

    #q=self.request.GET.get('seastr')
    context=super().get_context_data(*args,**kwargs)
    context['member']=Member.objects.all()
    return context

context dict:

{'page_obj': None, 'view': <artdb.views.Search object at 0x7f415ec88080>, 'is_paginated': False, 'object_list': [<QuerySet [<Person: David Bolander>, <Person: adam something>]>, <QuerySet [<Comment: david bolander comment>]>], 'member': <QuerySet [<Member: 2019-11-21>, <Member: 2020-02-10>]>, 'paginator': None}

my template:

{% extends "artdb/index.html" %}

{% block sr1 %}

        Persons: {{object_list.count}}

    Activities: {{activity.count}}

    Members: {{member.count}}

    Comments: {{comment.count}}

{% endblock sr1 %

As can be seen in the template, I want to count the matches in the  tag but the querysets are stacked as lists of lists in the context dictionary. For example, member can be counted because it was added later and it is not in a list of lists. how do I solve this?

Body:
ok, I found a solution to this. I insert the object_list again in the context dict:

def get_context_data(self,*args,**kwargs):

        context=super().get_context_data(*args,**kwargs)

        c=context['object_list']
        cname=[l.model.__name__ for l in c]

        for l in zip(cname,c):
            context[l[0].lower()]=l[1]

        return context

it's not the most elegant solution and if anyone else has another solution, please share it.


问:
How to set UINavigationController as root from UITabBarController.?
I am working on App where Login is shown to user, after successful login user is landed on dashboard. where 4 tabs are shown to navigate to respective use.
I have to use, UITabBarController for four tabs from dashboard and UINavigationController for navigation from LoginView.

I set my UITabBarController to navigationController, when user successfully logged in.
Each view will have one logout button, on click of which I have to set my navigationcontroller back to root.

Here is code sample which I have done.

My UITabBarController

class TabBarVC: UITabBarController {

```<code>let dashboardViewObj = DashboardVC()
let registerViewObj = RegisterVC()
let alertViewObj = AlertVC()
let historyViewObj = HistoryVC()
override func viewDidLoad() {
    super.viewDidLoad()
    self.viewControllers = [dashboardViewObj, registerViewObj,historyViewObj,alertViewObj]
    // Do any additional setup after loading the view.

    dashboardViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)
    registerViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 0)
    historyViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 0)
    alertViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 0)
}
</code>```

In my LoginViewContoller

let tabbarObj = TabBarVC()

```<code>@IBAction func loginBtnClicked(_ sender: Any) {
            self.navigationController?.setViewControllers([tabbarObj], animated: true)
        }
</code>```

Now on click of logout button from any of these views, I need to set navigationController as root.
How to do it...?

Following chart will help to understand what I need.
Any help will be appeciated.

答:
You can use unwind segue easily instead of setting the root view controller or pop view controller or even dismiss methods!

See  this for full description

Body:
I am working on App where Login is shown to user, after successful login user is landed on dashboard. where 4 tabs are shown to navigate to respective use.
I have to use, UITabBarController for four tabs from dashboard and UINavigationController for navigation from LoginView.

I set my UITabBarController to navigationController, when user successfully logged in.
Each view will have one logout button, on click of which I have to set my navigationcontroller back to root.

Here is code sample which I have done.

My UITabBarController

class TabBarVC: UITabBarController {

let dashboardViewObj = DashboardVC()
let registerViewObj = RegisterVC()
let alertViewObj = AlertVC()
let historyViewObj = HistoryVC()
override func viewDidLoad() {
    super.viewDidLoad()
    self.viewControllers = [dashboardViewObj, registerViewObj,historyViewObj,alertViewObj]
    // Do any additional setup after loading the view.

    dashboardViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)
    registerViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 0)
    historyViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .contacts, tag: 0)
    alertViewObj.tabBarItem = UITabBarItem(tabBarSystemItem: .bookmarks, tag: 0)
}

In my LoginViewContoller

let tabbarObj = TabBarVC()

@IBAction func loginBtnClicked(_ sender: Any) {
            self.navigationController?.setViewControllers([tabbarObj], animated: true)
        }

Now on click of logout button from any of these views, I need to set navigationController as root.
How to do it...?

Following chart will help to understand what I need.
Any help will be appeciated.


问:
Automatic download of mp3 file
I need some help please.

I run a radio station which uses a downloadable news feed. At the moment I download it every hour manually.

I would like a script, preferably cmd, so nothing fancy needed to run it, that will download the file once an hour (using windows task scheduler) and put it in a certain folder. The download is not user/PW protected, it is free and copyrighted as such.

Can some kind soul please kick-start me?

Thanks.

答:
If you want to use pure batch, you might want to use:

CERTUTIL

```<code>certutil -urlcache -split -f <url>
</code>```

BITSADMIN

```<code>bitsadmin /transfer myDownloadJob /download /priority normal <url> <destination>
</code>```

To automate tasks, use schtasks:

```<code>schtasks /create /tn "MyTask" /sc hourly /mo 1 /tr "certutil -urlcache -split -f <url>"
</code>```

Title: Automatic download of mp3 file

Body:
If you want to use pure batch, you might want to use:

CERTUTIL

certutil -urlcache -split -f <url>

BITSADMIN

bitsadmin /transfer myDownloadJob /download /priority normal <url> <destination>

To automate tasks, use schtasks:

schtasks /create /tn "MyTask" /sc hourly /mo 1 /tr "certutil -urlcache -split -f <url>"


问:
How does a vector as a key works internally in C++?
This SO answers says that STL Map with a Vector for the Key the vector can be used as a key. So when we use a vector as a key. How does that actually work since the key needs to be unique so when we insert another vector with the same elements will the map check for duplicate element by element or the name of the vector does specify something? Like the name of the array represents the base address. So an array can be used as a key since the base address can be used as a key in this case but what is the key in case of a vector. How does it work internally.

Because when I print the name of the vector, I do get an error

```<code>vector<int> v;
cout<<v; //error
</code>```

答:
There is an overloaded operator < for the class template std::vector.

```<code>template <class T,
class Allocator>
bool operator< (const vector<T, Allocator>& x, const vector<T, Allocator>& y);
</code>```

that is based on the standard algorithm std::lexicographical_compare.

Here is a demonstrative program.

```<code>#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::vector<int> v1 = { 1, 2 };
    std::vector<int> v2 = { 1, 2, 3 };
    std::vector<int> v3 = { 2 };

    std::cout << std::boolalpha << ( v1 < v2 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v1 ), std::end( v1 ),
                                               std::begin( v2 ), std::end( v2 ) )
             << '\n';

    std::cout << std::boolalpha << ( v1 < v3 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v1 ), std::end( v1 ),
                                               std::begin( v3 ), std::end( v3 ) )
             << '\n';

    std::cout << std::boolalpha << ( v2 < v3 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v2 ), std::end( v2 ),
                                               std::begin( v3 ), std::end( v3 ) )
             << '\n';

    return 0;
}
</code>```

Its output is

```<code>true
true
true
true
true
true
</code>```

So the class can be used as a key in map.

By default the class template map uses the function object std::less that in turn uses the operator <

```<code>template <class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class map
{
    //...
};
</code>```

However there is no overloaded operator << for the class template std::vector.

Body:
This SO answers says that STL Map with a Vector for the Key the vector can be used as a key. So when we use a vector as a key. How does that actually work since the key needs to be unique so when we insert another vector with the same elements will the map check for duplicate element by element or the name of the vector does specify something? Like the name of the array represents the base address. So an array can be used as a key since the base address can be used as a key in this case but what is the key in case of a vector. How does it work internally.

Because when I print the name of the vector, I do get an error

vector<int> v;
cout<<v; //error

Body:
There is an overloaded operator < for the class template std::vector.

template <class T,
class Allocator>
bool operator< (const vector<T, Allocator>& x, const vector<T, Allocator>& y);

that is based on the standard algorithm std::lexicographical_compare.

Here is a demonstrative program.

#include <iostream>
#include <iomanip>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::vector<int> v1 = { 1, 2 };
    std::vector<int> v2 = { 1, 2, 3 };
    std::vector<int> v3 = { 2 };

    std::cout << std::boolalpha << ( v1 < v2 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v1 ), std::end( v1 ),
                                               std::begin( v2 ), std::end( v2 ) )
             << '\n';

    std::cout << std::boolalpha << ( v1 < v3 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v1 ), std::end( v1 ),
                                               std::begin( v3 ), std::end( v3 ) )
             << '\n';

    std::cout << std::boolalpha << ( v2 < v3 ) << '\n';
    std::cout << std::lexicographical_compare( std::begin( v2 ), std::end( v2 ),
                                               std::begin( v3 ), std::end( v3 ) )
             << '\n';

    return 0;
}

Its output is

true
true
true
true
true
true

So the class can be used as a key in map.

By default the class template map uses the function object std::less that in turn uses the operator <

template <class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T>>>
class map
{
    //...
};

However there is no overloaded operator << for the class template std::vector.


问:
How to save multiple location coordinates in your project?
I'm fetching some of the locations from the server and need to point them as markers in the google map, so what i did was i created a model of the locations and used the volley library to fetch the details from the server and saved them in a variable and post it in the map. But I'm getting an error as java.lang.NumberFormatException: multiple points.
So need some assistance.
This is my model

```<code>public class LocationModel
private String pdLatitude;
private String pdLongitude;

public LocationModel(String pdLatitude, String pdLongitude){
this.pdLatitude = pdLatitude;
this.pdLongitude = pdLongitude; }

public String getPdLatitude() {
return pdLatitude;
}

public String getPdLongitude() {
return pdLongitude;
}
</code>```

This is my Activity where i'm retreiving the information from the server

```<code>private void findRoute(){
        StringRequest request = new StringRequest(Request.Method.GET,
                Constant.Route_URL + "/" + driverschoolname + "/" + driverid,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String pdlatitude = "";
                        String pdlongitude = "";
                        try{
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("res");
                            for (int i=0; i<array.length(); i++){
                                JSONObject object = array.getJSONObject(i);
                                StudentsPickDropModel pickDropModel = new StudentsPickDropModel(
                                        object.getString("pdloc_latitude"),
                                        object.getString("pdloc_longitude")
                                );
                                pdlatitude += pickDropModel.getPdLatitude();
                                pdlongitude += pickDropModel.getPdLongitude();
                                Toast.makeText(StudentsPickDropActivity.this, pickDropModel.getPdName(), Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(Activity.this, GetRoute.class);
                                intent.putExtra("pd_latitude", pdlatitude);
                                intent.putExtra("pd_longitude", pdlongitude);
                                startActivity(intent);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    }
</code>```

And this is how i'm posting my coordiantes in Google maps

```<code>Bundle bundle = getIntent().getExtras();
        schoollat = bundle.getString("school_lat");
        schoollng = bundle.getString("school_lng");
        pdlat = bundle.getString("pd_latitude");
        pdlng = bundle.getString("pd_longitude");

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                Location location = task.getResult();
                if (location == null){
                    requestNewLocationData();
                } else {
                    currentLat = location.getLatitude();
                    currentLng = location.getLongitude();
                    System.out.println("Current Latitude: "+location.getLatitude());
                    System.out.println("Current Longitude: "+location.getLongitude());
                }
            }
        });

        Double clat = currentLat;
        System.out.println("Current Latitude : "+clat);

        Double schoollatitude = new Double(schoollat);
        Double schoollongitude = new Double(schoollng);
        System.out.println("School latitude : "+schoollatitude + ", School Longitude : "+schoollongitude);
        Double pdlatitude = new Double(pdlat);
        Double pdlongitude = new Double(pdlng);

        getDirections = findViewById(R.id.getdirection);
        getDirections.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new FetchURL(GetRoute.this).execute(getUrl(placeOne.getPosition(), placeTwo.getPosition(), "driving"), "driving");
            }
        });

        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);

        places = new MarkerOptions().position(new LatLng(pdlatitude, pdlongitude)).title("Office");
</code>```

And this is my JSON

```<code>  "res": [
        {
            "pdloc_latitude": "12.3111356",
            "pdloc_longitude": "76.6075989",
        },
        {
            "pdloc_latitude": "88.568645787",
            "pdloc_longitude": "75.54544454887",
        }
</code>```

答:
Use Double.parseDouble() for better efficiency

The core method is parseDouble() which is specially designed to parse
  a String containing floating point value into the Double object. Rest
  of the methods e.g. valueOf() and constructor uses parseDouble()
  internally.

and be sure that the pdlat value you are passing is a valid double number and not just plain characters

This( Double.parseDouble()) method will throw NullPointerException if the string you are passing is null and NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters.

Just debug Double pdlatitude = new Double(pdlat); line to be sure.

Body:
I'm fetching some of the locations from the server and need to point them as markers in the google map, so what i did was i created a model of the locations and used the volley library to fetch the details from the server and saved them in a variable and post it in the map. But I'm getting an error as java.lang.NumberFormatException: multiple points.
So need some assistance.
This is my model

public class LocationModel
private String pdLatitude;
private String pdLongitude;

public LocationModel(String pdLatitude, String pdLongitude){
this.pdLatitude = pdLatitude;
this.pdLongitude = pdLongitude; }

public String getPdLatitude() {
return pdLatitude;
}

public String getPdLongitude() {
return pdLongitude;
}

This is my Activity where i'm retreiving the information from the server

private void findRoute(){
        StringRequest request = new StringRequest(Request.Method.GET,
                Constant.Route_URL + "/" + driverschoolname + "/" + driverid,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String pdlatitude = "";
                        String pdlongitude = "";
                        try{
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray array = jsonObject.getJSONArray("res");
                            for (int i=0; i<array.length(); i++){
                                JSONObject object = array.getJSONObject(i);
                                StudentsPickDropModel pickDropModel = new StudentsPickDropModel(
                                        object.getString("pdloc_latitude"),
                                        object.getString("pdloc_longitude")
                                );
                                pdlatitude += pickDropModel.getPdLatitude();
                                pdlongitude += pickDropModel.getPdLongitude();
                                Toast.makeText(StudentsPickDropActivity.this, pickDropModel.getPdName(), Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(Activity.this, GetRoute.class);
                                intent.putExtra("pd_latitude", pdlatitude);
                                intent.putExtra("pd_longitude", pdlongitude);
                                startActivity(intent);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Activity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    }

And this is how i'm posting my coordiantes in Google maps

Bundle bundle = getIntent().getExtras();
        schoollat = bundle.getString("school_lat");
        schoollng = bundle.getString("school_lng");
        pdlat = bundle.getString("pd_latitude");
        pdlng = bundle.getString("pd_longitude");

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                Location location = task.getResult();
                if (location == null){
                    requestNewLocationData();
                } else {
                    currentLat = location.getLatitude();
                    currentLng = location.getLongitude();
                    System.out.println("Current Latitude: "+location.getLatitude());
                    System.out.println("Current Longitude: "+location.getLongitude());
                }
            }
        });

        Double clat = currentLat;
        System.out.println("Current Latitude : "+clat);

        Double schoollatitude = new Double(schoollat);
        Double schoollongitude = new Double(schoollng);
        System.out.println("School latitude : "+schoollatitude + ", School Longitude : "+schoollongitude);
        Double pdlatitude = new Double(pdlat);
        Double pdlongitude = new Double(pdlng);

        getDirections = findViewById(R.id.getdirection);
        getDirections.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new FetchURL(GetRoute.this).execute(getUrl(placeOne.getPosition(), placeTwo.getPosition(), "driving"), "driving");
            }
        });

        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);

        places = new MarkerOptions().position(new LatLng(pdlatitude, pdlongitude)).title("Office");

And this is my JSON

  "res": [
        {
            "pdloc_latitude": "12.3111356",
            "pdloc_longitude": "76.6075989",
        },
        {
            "pdloc_latitude": "88.568645787",
            "pdloc_longitude": "75.54544454887",
        }


问:
How to close p-dropdown on p-dialog close?
I have an angular component consisting of ngprime p-dialog. In the body of this dialog there is p-dropdown. When I click on dropdown options are shown, but there is situation that user accidentally can click on closing dialog. The second time when dialog is opened, the dropdown options are available after double click, because the onHide event is executed on first click. Is there any way to close p-dropdown options on closing the dialog? Here's code

HTML

```<code><p-dialog #dialog [closeOnEscape]="closeDialog" [responsive]="true" [modal]="true" [(visible)]="shown" styleClass="modal"
          [maximizable]="false" [baseZIndex]="1000" minWidth="200px" [width]="669"
          (onHide)="hideModal()" [draggable]="false">
  <p-header class="modal__header">{{category.name}}</p-header>
  <div class="modal__subcategory">
    <p-dropdown #dropdown  placeholder="Choose a sub-category"
      [options]="subcategories" optionLabel="name [(ngModel)]="selectedSubcategory">
    </p-dropdown>
  </div>
</p-dialog>
</code>```

TS

```<code>export class SuggestionsComponent implements OnInit {
    @Input()
    category: CategoryDTO;
    @Input()
    shown: boolean;
    @Output()
    onHideModal: EventEmitter<boolean> = new EventEmitter<boolean>();
    subcategories: SubcategoryDTO[];
    selectedSubcategory: SubcategoryDTO;
    newQuestion: string = '';

    constructor(private categoryService: CategoryService, private surveyService: SurveyService,
        private toastNotificationService: ToastNotificationService,
        private internetConnectionService: InternetConnectionService,
        private loadingService: LoadingService) {
        this.onHideModal = new EventEmitter<boolean>();
    }

    ngOnInit() {

        if (this.category.id != null) {
            this.categoryService.getSubcategoriesByCategory(this.category).subscribe(
                subcategories => {
                    this.onHideModal.emit(true);
                    this.subcategories = subcategories.value;
                },
                (error) => {
                    this.internetConnectionService.showToastWhenErrorOccurred(error, " get subcategories");
                }
            );

        }
    }

    hideModal() {
        this.shown = false;
        this.newQuestion = "";
        this.selectedSubcategory = null;
        this.onHideModal.emit(true);
    }
}
</code>```

答:
p-dropdown has a method focus() you can call it after your modal was opened. (Use the onShow() Event of your p-dialog to call the

Controller

onModalShow() Method

```<code>import { Component, ViewChild } from '@angular/core';

@ViewChild('dropdown') dropdown;

onModalShow() {
    this.dropdown.focus();
}
</code>```

Template

```<code><p-dialog #dialog [closeOnEscape]="closeDialog" [responsive]="true" [modal]="true" [(visible)]="shown" styleClass="modal"
        [maximizable]="false" [baseZIndex]="1000" minWidth="200px" [width]="669"
        (onHide)="hideModal()" [draggable]="false" (onShow)="onModalShow()">
<p-header class="modal__header">{{category.name}}</p-header>
<div class="modal__subcategory">
    <p-dropdown #dropdown  placeholder="Choose a sub-category"
    [options]="subcategories" optionLabel="name [(ngModel)]="selectedSubcategory">
    </p-dropdown>
</div>
</p-dialog>
</code>```

Body:
I have an angular component consisting of ngprime p-dialog. In the body of this dialog there is p-dropdown. When I click on dropdown options are shown, but there is situation that user accidentally can click on closing dialog. The second time when dialog is opened, the dropdown options are available after double click, because the onHide event is executed on first click. Is there any way to close p-dropdown options on closing the dialog? Here's code

HTML

{{category.name}}

TS

export class SuggestionsComponent implements OnInit {
    @Input()
    category: CategoryDTO;
    @Input()
    shown: boolean;
    @Output()
    onHideModal: EventEmitter<boolean> = new EventEmitter<boolean>();
    subcategories: SubcategoryDTO[];
    selectedSubcategory: SubcategoryDTO;
    newQuestion: string = '';

    constructor(private categoryService: CategoryService, private surveyService: SurveyService,
        private toastNotificationService: ToastNotificationService,
        private internetConnectionService: InternetConnectionService,
        private loadingService: LoadingService) {
        this.onHideModal = new EventEmitter<boolean>();
    }

    ngOnInit() {

        if (this.category.id != null) {
            this.categoryService.getSubcategoriesByCategory(this.category).subscribe(
                subcategories => {
                    this.onHideModal.emit(true);
                    this.subcategories = subcategories.value;
                },
                (error) => {
                    this.internetConnectionService.showToastWhenErrorOccurred(error, " get subcategories");
                }
            );

        }
    }

    hideModal() {
        this.shown = false;
        this.newQuestion = "";
        this.selectedSubcategory = null;
        this.onHideModal.emit(true);
    }
}

Body:
p-dropdown has a method focus() you can call it after your modal was opened. (Use the onShow() Event of your p-dialog to call the

Controller

onModalShow() Method

import { Component, ViewChild } from '@angular/core';

@ViewChild('dropdown') dropdown;

onModalShow() {
    this.dropdown.focus();
}

Template

<p-dialog #dialog [closeOnEscape]="closeDialog" [responsive]="true" [modal]="true" [(visible)]="shown" styleClass="modal"
        [maximizable]="false" [baseZIndex]="1000" minWidth="200px" [width]="669"
        (onHide)="hideModal()" [draggable]="false" (onShow)="onModalShow()">
<p-header class="modal__header">{{category.name}}</p-header>
<div class="modal__subcategory">
    <p-dropdown #dropdown  placeholder="Choose a sub-category"
    [options]="subcategories" optionLabel="name [(ngModel)]="selectedSubcategory">
    </p-dropdown>
</div>
</p-dialog>


问:
how to add nested object with new object
Actually, I want to add hats object to clothing object, i don't want to change object to array of object.
Can anyone help me how to add hats in my scenario.</p>

```<code>const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
  {
    id: 01,
    name:'plain shirt',
  },
  {
    id: 02,
    name: 'stripe shirt',
  },
 ],
},

tshirt: {
id: 2,
title: 't-shirt',
item: [
  {
    id: 03,
    name: 'plain t-shirt',
  },
  {
    id: 04,
    name: 'stripe t-shirt',
   }
  ],
 },
}

const newClothing = {...clothing};
newClothing[{hats:{id:3, title:'hats', item:[{id:05, name:'blue hats'}]}}];

console.log(newClothing.hats);
</code>```

答:
From what I understand, I don't think you need to do anything fancy here. Simply add a property as follows: </p>

```<code>clothing.hats = {
    id:3,
    title:'hats',
    item:[{id:05, name:'blue hats'}]
   }
</code>```

Body:
Actually, I want to add hats object to clothing object, i don't want to change object to array of object.
Can anyone help me how to add hats in my scenario.

const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
  {
    id: 01,
    name:'plain shirt',
  },
  {
    id: 02,
    name: 'stripe shirt',
  },
 ],
},

tshirt: {
id: 2,
title: 't-shirt',
item: [
  {
    id: 03,
    name: 'plain t-shirt',
  },
  {
    id: 04,
    name: 'stripe t-shirt',
   }
  ],
 },
}

const newClothing = {...clothing};
newClothing[{hats:{id:3, title:'hats', item:[{id:05, name:'blue hats'}]}}];

console.log(newClothing.hats);

Body:
From what I understand, I don't think you need to do anything fancy here. Simply add a property as follows:

clothing.hats = {
    id:3,
    title:'hats',
    item:[{id:05, name:'blue hats'}]
   }


问:
Fuzzy match in a column in a dataframe in python
I have a column that has strings. I want to do a fuzzy match and mark those which have an 80% match in a column next to it. I can do it with the following code on a smaller dataset but my original dataset is too big for this to work efficiently. Is there a better way to do this? This is what I have done.</p>

```<code>import pandas as pd

l = [[1,'a','b','c','help pls'],[2,'a','c','c','yooo'],[3,'a','c','c','you will not pass'],[4,'a','b','b','You shall not pass'],[5,'a','c','c','You shall not pass!']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df['yes/no 2'] = ""

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (i != j):
            if (fuzz.token_sort_ratio(df.iloc[i,df.shape[1]-2],df.iloc[j,df.shape[1]-2]) > 80):
                df.iloc[i,df.shape[1]-1] = "yes"
</code>```

答:
```<code>import pandas as pd
from fuzzywuzzy import fuzz,process

l = [[1,'a','b','c','help pls'],[2,'a','c','c','yooo'],[3,'a','c','c','you will not pass'],[4,'a','b','b','You shall not pass'],[5,'a','c','c','You shall not pass!']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four']).reset_index()

def match(df,col):
    thresh = 80
    return df[col].apply(lambda x:"Yes" if len(process.extractBests(x[1],[xx[1] for i,xx in enumerate(df[col]) if i!=x[0]],
            scorer=fuzz.token_sort_ratio,score_cutoff=thresh+1,limit=1))>0 else "No")

df["five"] = df.apply(lambda x:(x["index"],x["four"]),axis=1)
df["Yes/No"] = df.pipe(match,"five")
print(df)

   index  Serial No one two three                 four                      five Yes/No
0      0          1   a   b     c             help pls             (0, help pls)     No
1      1          2   a   c     c                 yooo                 (1, yooo)     No
2      2          3   a   c     c    you will not pass    (2, you will not pass)    Yes
3      3          4   a   b     b   You shall not pass   (3, You shall not pass)    Yes
4      4          5   a   c     c  You shall not pass!  (4, You shall not pass!)    Yes
</code>```

Body:
I have a column that has strings. I want to do a fuzzy match and mark those which have an 80% match in a column next to it. I can do it with the following code on a smaller dataset but my original dataset is too big for this to work efficiently. Is there a better way to do this? This is what I have done.

import pandas as pd

l = [[1,'a','b','c','help pls'],[2,'a','c','c','yooo'],[3,'a','c','c','you will not pass'],[4,'a','b','b','You shall not pass'],[5,'a','c','c','You shall not pass!']]
df = pd.DataFrame(l,columns = ['Serial No','one','two','three','four'])

df['yes/no 2'] = ""

for i in range(0, df.shape[0]):
    for j in range(0, df.shape[0]):
        if (i != j):
            if (fuzz.token_sort_ratio(df.iloc[i,df.shape[1]-2],df.iloc[j,df.shape[1]-2]) > 80):
                df.iloc[i,df.shape[1]-1] = "yes"


问:
ThreadAbortException vs graceful event handle exit in C#
When aborting the execution of a thread I'm always doubting between a graceful exit with an event handler like this:

```<code>int result = WaitHandle.WaitAny(handles);
if (result = WAIT_FINALIZE)
  FinalizeAndExit();
</code>```

and using the event to signal the thread it must terminate

or just handling the ThreadAbortException to finalize the thread...

```<code>try
{
  // Main execution
}
catch(ThreadAbortException e)
{
  // FinalizeAndExit();
}
finally
{
}
</code>```

I'm usually inclined to use the ThreadAbortException approach since it can be handled but it is re-raised at the end of the catch block, and it also avoids the thread from being kept alive by "treacherous" methods, but I've seen both approaches.

What's your opinion? Is there any situation where it's best to use one over another, or is it best to use always approach x?

答:
Generally, the first method it preferrable.

It's hard (if not impossible) to write code that will always handle a ThreadAbortException gracefully. The exception can occur in the middle of whatever the thread happens to be doing, so some situations can be hard to handle.

For example, the exception can occur after you have created a FileStream object, but before the reference is assigned to a variable. That means that you have an object that should be disposed, but the only reference to it is lost on the stack somewhere...

OwnerDisplayName: Jorge Córdoba

Body:
When aborting the execution of a thread I'm always doubting between a graceful exit with an event handler like this:

int result = WaitHandle.WaitAny(handles);
if (result = WAIT_FINALIZE)
  FinalizeAndExit();

and using the event to signal the thread it must terminate

or just handling the ThreadAbortException to finalize the thread...

try
{
  // Main execution
}
catch(ThreadAbortException e)
{
  // FinalizeAndExit();
}
finally
{
}

I'm usually inclined to use the ThreadAbortException approach since it can be handled but it is re-raised at the end of the catch block, and it also avoids the thread from being kept alive by "treacherous" methods, but I've seen both approaches.

What's your opinion? Is there any situation where it's best to use one over another, or is it best to use always approach x?

OwnerDisplayName: Guffa

ContentLicense: CC BY-SA 2.5


问:
how to convert Final_Unique column into a header values in pandas
sample image to check the data

SAMPLE DATA

```<code>Actual_Data     Final_Unique
8,8,8,8,8,8,        8,8
6,7,7,7,6,7,        6,7
2,12,3,4,12,12,     7,7
14,14,14,14,14,14,  7,6
1,1,12,2,2,4,       2,12
6,8,8,8,8,12,       12,3
6,6,6,6,3,14,       3,4
1,14,14,1,1,2,      4,12
1,1,1,1,1,14,       12,12
</code>```

i am trying this

newdf = a.pivot(index='Actual_Data', columns='Final_Unique')

i have 2 column actual data and final_unique column in actual i have 44000 rows and final_unique has 266 rows i want to get the 266 column and actual data to stay same as it and count how many time actual data appears in the header

error getting

duplicate data exist can't reshape

output expected

```<code>ACTUAL DATA          8,8  6,7  7,7   7,6  2,12

8,8,8,8,8,8,          3   0    0      0    0

6,7,7,7,6,7,          0    2    1     1    0

2,12,3,4,12,12,       0    0    0     0    1
</code>```

答:
I would do the following:

```<code>import re
l1 = list(a['Actual_Data'])
l2 = list(a['Final_Unique'])
d = {i: [len(re.findall(i,j)) for j in l1] for i in l2}
newdf = pd.DataFrame(d,index=l1)
</code>```

if you have an issue with data types:

```<code>import re
l1 = list(a['Actual_Data'])
l2 = list(a['Final_Unique'])
d = {i: [len(re.findall(str(i),str(j))) for j in l1] for i in l2}
newdf = pd.DataFrame(d,index=l1)
</code>```

What I've done here is forced every value of Actual_Data and Final_Unqiue into a string.

Body:
sample image to check the data

SAMPLE DATA

Actual_Data     Final_Unique
8,8,8,8,8,8,        8,8
6,7,7,7,6,7,        6,7
2,12,3,4,12,12,     7,7
14,14,14,14,14,14,  7,6
1,1,12,2,2,4,       2,12
6,8,8,8,8,12,       12,3
6,6,6,6,3,14,       3,4
1,14,14,1,1,2,      4,12
1,1,1,1,1,14,       12,12

i am trying this

newdf = a.pivot(index='Actual_Data', columns='Final_Unique')

i have 2 column actual data and final_unique column in actual i have 44000 rows and final_unique has 266 rows i want to get the 266 column and actual data to stay same as it and count how many time actual data appears in the header

error getting

duplicate data exist can't reshape

output expected

ACTUAL DATA          8,8  6,7  7,7   7,6  2,12

8,8,8,8,8,8,          3   0    0      0    0

6,7,7,7,6,7,          0    2    1     1    0

2,12,3,4,12,12,       0    0    0     0    1

Body:
I would do the following:

import re
l1 = list(a['Actual_Data'])
l2 = list(a['Final_Unique'])
d = {i: [len(re.findall(i,j)) for j in l1] for i in l2}
newdf = pd.DataFrame(d,index=l1)

if you have an issue with data types:

import re
l1 = list(a['Actual_Data'])
l2 = list(a['Final_Unique'])
d = {i: [len(re.findall(str(i),str(j))) for j in l1] for i in l2}
newdf = pd.DataFrame(d,index=l1)

What I've done here is forced every value of Actual_Data and Final_Unqiue into a string.


问:
C++ template packed parameters
I'm wondering how I can specify a template type as "parameter pack".

The commented line doesn't work because it can't deduce T (it has the same template parameters). On the next line I can fix that by supplying T but I'm stuck at how I should supply the parameter pack type (where the question marks are.).

```<code>template<typename T, typename... Args> T& Entity::addComponent(Args&&... args) const
{
    //return entityManager->addComponent(std::forward<Args>(args)...);
    return entityManager->addComponent<T, ?????>(std::forward<Args>(args)...);
}
</code>```

I want to use Args as that type.

答:
You don't need to specify the parameter pack template argument because it could be deduced from function arguments. So just specify the 1st template argument (and you have to do this because T can be deduced from nowhere). e.g.

```<code>return entityManager->addComponent<T>(std::forward<Args>(args)...);
//                                ^^^
</code>```

If you want to specify the parameter pack template argument explicitly you could write it as

```<code>return addComponent<T, Args...>(std::forward<Args>(args)...);
//                     ^^^^^^^
</code>```

Title: C++ template packed parameters

Body:
I'm wondering how I can specify a template type as "parameter pack".

The commented line doesn't work because it can't deduce T (it has the same template parameters). On the next line I can fix that by supplying T but I'm stuck at how I should supply the parameter pack type (where the question marks are.).

template<typename T, typename... Args> T& Entity::addComponent(Args&&... args) const
{
    //return entityManager->addComponent(std::forward<Args>(args)...);
    return entityManager->addComponent<T, ?????>(std::forward<Args>(args)...);
}

I want to use Args as that type.

Body:
You don't need to specify the parameter pack template argument because it could be deduced from function arguments. So just specify the 1st template argument (and you have to do this because T can be deduced from nowhere). e.g.

return entityManager->addComponent<T>(std::forward<Args>(args)...);
//                                ^^^

If you want to specify the parameter pack template argument explicitly you could write it as

return addComponent<T, Args...>(std::forward<Args>(args)...);
//                     ^^^^^^^


问:
Docker: COPY failed to find Gemfile: no such file or directory
I'm currently working on setting up a Rails boilerplate via docker. When I try to run docker build . I get the following error:

```<code>Step 5/8 : COPY Gemfile /app/
COPY failed: stat /var/lib/docker/tmp/docker-builder090950451/Gemfile: no such file or directory
</code>```

I'm following the directions in the documentation but I still have not been able to build the image.

Here is my Dockerfile

```<code>FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

WORKDIR /app

# Copy the existing Gemfile
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock

# Install Gems
RUN bundle install
COPY . /app
</code>```

I also have the following docker-compose.yml file:

```<code>version: '3'
services:
  db:
    image: postgres # To Edit - Default is postgresql.
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/app
    ports:
      - "3000:3000"
    depends_on:
      - db
</code>```

I generated the Rails application by running docker-compose run web rails new app --force --database=postgresql which does generates the rails application with its Gemfile as shown in the image below.

However after generating the rails application and running docker-compose build I get the following error:

```<code>db uses an image, skipping
Building web
Step 1/7 : FROM ruby:2.5
 ---> 55fb4a37704e
Step 2/7 : RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
 ---> Using cache
 ---> afb6f347904c
Step 3/7 : WORKDIR /app
 ---> Using cache
 ---> 1fdbd260685d
Step 4/7 : COPY Gemfile /app/Gemfile
ERROR: Service 'web' failed to build: COPY failed: stat /var/lib/docker/tmp/docker-builder885442968/Gemfile: no such file or directory
</code>```

答:
The issue here is that if you have the line:
WORKDIR /app you are already in the polder app. So when you COPY something into docker container you do not need to write ./app or /app because . means that this is an app already. And if you write such a thing it will be copied to the new app dir inside your WORKDIR and the path will be /app/app.
In your case the Dockerfile should look like:

```<code>FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

WORKDIR /app

# Copy the existing Gemfile
COPY Gemfile Gemfile.lock .

# Install Gems
RUN bundle install
COPY . .
</code>```

Body:
I'm currently working on setting up a Rails boilerplate via docker. When I try to run docker build . I get the following error:

Step 5/8 : COPY Gemfile /app/
COPY failed: stat /var/lib/docker/tmp/docker-builder090950451/Gemfile: no such file or directory

I'm following the directions in the documentation but I still have not been able to build the image.

Here is my Dockerfile

FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

WORKDIR /app

# Copy the existing Gemfile
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock

# Install Gems
RUN bundle install
COPY . /app

I also have the following docker-compose.yml file:

version: '3'
services:
  db:
    image: postgres # To Edit - Default is postgresql.
  web:
    build: .
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/app
    ports:
      - "3000:3000"
    depends_on:
      - db

I generated the Rails application by running docker-compose run web rails new app --force --database=postgresql which does generates the rails application with its Gemfile as shown in the image below.

However after generating the rails application and running docker-compose build I get the following error:

db uses an image, skipping
Building web
Step 1/7 : FROM ruby:2.5
 ---> 55fb4a37704e
Step 2/7 : RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
 ---> Using cache
 ---> afb6f347904c
Step 3/7 : WORKDIR /app
 ---> Using cache
 ---> 1fdbd260685d
Step 4/7 : COPY Gemfile /app/Gemfile
ERROR: Service 'web' failed to build: COPY failed: stat /var/lib/docker/tmp/docker-builder885442968/Gemfile: no such file or directory

Body:
The issue here is that if you have the line:
WORKDIR /app you are already in the polder app. So when you COPY something into docker container you do not need to write ./app or /app because . means that this is an app already. And if you write such a thing it will be copied to the new app dir inside your WORKDIR and the path will be /app/app.
In your case the Dockerfile should look like:

FROM ruby:2.5
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs

WORKDIR /app

# Copy the existing Gemfile
COPY Gemfile Gemfile.lock .

# Install Gems
RUN bundle install
COPY . .


问:
Placing the modal at the bottom for all resolutions
I'm using react-bootstrap modal in my project. I need to place the modal at bottom of all the resolutions. For example, I can place the modal at bottom by changing css bottom property to -74% in 1080x1920 resolutions. But for other devices it is not the same.

```<code><div role="dialog" aria-modal="true" class="fade modal show" tabindex="-1" style="display: block; padding-left: 0px;">
   <div role="document" class="modal-dialog sc-modal">
      <div class="modal-content">...
      </div>
   </div>
</div>

.sc-modal{
    width:100% !important;
    top: unset;
    bottom:0%;
    max-width: 1080px;
    left: 50%;
    transform: translate(-50%, 0) !important;
}
</code>```

How to place the modal at the bottom for all device resolutions ?

答:
position should help you fix the modal at the bottom of the window.

```<code>.modal.in .modal-dialog {
   position: fixed;
   bottom: 0;
   left: 50%;
   transform: translate(-50%);
}
</code>```

Body:
I'm using react-bootstrap modal in my project. I need to place the modal at bottom of all the resolutions. For example, I can place the modal at bottom by changing css bottom property to -74% in 1080x1920 resolutions. But for other devices it is not the same.

...

.sc-modal{
    width:100% !important;
    top: unset;
    bottom:0%;
    max-width: 1080px;
    left: 50%;
    transform: translate(-50%, 0) !important;
}

How to place the modal at the bottom for all device resolutions ?

Body:
position should help you fix the modal at the bottom of the window.

.modal.in .modal-dialog {
   position: fixed;
   bottom: 0;
   left: 50%;
   transform: translate(-50%);
}


问:
How would I use PHP substr?
I am trying to figure out how to use substr in my program to get the appropriate data from a table.

User picks 'Letters' "AA", "AB", "AC", "AD", "AE" or "all"

Then I need to compare if the 'panelID' has the 'Letters' I assume using substr.

panelID example: 1122AA-0010

```<code>$_SESSION['yield'] = "
from (select distinct panelID from DATABASE.TABLE) s, DATABASE.TABLE p
where p.panelID = s.panelID and p.laminationts > '$start_date' and p.laminationts < '$end_date'
group by week(p.laminationts)";
</code>```

Something like this

```<code>"where substr(p.panelID,4,2) = substr(s.panelID,4,2) and p.laminationts > '$start_date' and p.laminationts < ..."
</code>```

答:
You need substr(p.panelID,5,2), because the first character is at position 1, not 0.

Also, beware that using functions in WHERE clause avoids using any indexes on those fields. Maybe you could restructure your DB (for example split the panelID in multiple fields and create a composite PK on those fields) to allow the usage of indexes

Title: How would I use PHP substr?

Body:
I am trying to figure out how to use substr in my program to get the appropriate data from a table.

User picks 'Letters' "AA", "AB", "AC", "AD", "AE" or "all"

Then I need to compare if the 'panelID' has the 'Letters' I assume using substr.

panelID example: 1122AA-0010

$_SESSION['yield'] = "
from (select distinct panelID from DATABASE.TABLE) s, DATABASE.TABLE p
where p.panelID = s.panelID and p.laminationts > '$start_date' and p.laminationts < '$end_date'
group by week(p.laminationts)";

Something like this

"where substr(p.panelID,4,2) = substr(s.panelID,4,2) and p.laminationts > '$start_date' and p.laminationts < ..."


问:
How to add filter row inside material table?
I'm using angular material table and I try to use filter option. In documentation I find filter example but for my case I need to add textInputs after each headers. How can I do it ?
My example

```<code><table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!-- Id Column -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> ID</th>
    <td mat-cell *matCellDef="let element"> {{element.id}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</code>```

I need table like this.

答:
I think this is the perfect case for you. Check below example:

https://stackblitz.com/edit/angular-hbakxo-5jeaic

Body:
I'm using angular material table and I try to use filter option. In documentation I find filter example but for my case I need to add textInputs after each headers. How can I do it ?
My example

  <ng-container matColumnDef="id">
     ID
     {{element.id}}
  </ng-container>

  <ng-container matColumnDef="name">
     Name
     {{element.name}}
  </ng-container>

I need table like this.


问:
Uncaught Exception: DateTime::__construct(): Failed to parse time string
I'm using the function below to calculate the age (in years) of people from birthdays dates (in european format DD/MM/YYYY) that are stored as text in Wordpress Advanced Custom Fields

```<code>function get_age($birthDate_old) {
    $birthDate = ($birthDate_old);
    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}
</code>```

In the majority of cases it works fine but in some cases I got the error below :

```<code> Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/01/1958) at position 0 (2): Unexpected character in /home/XXXX/functions.php:99 Stack trace: #0 /home/XXXX/functions.php(99): DateTime->__construct('26/01/1958') #1 /home/XXXX/single.php(69): get_age('26/01/1958') #2 /home/XXX/wp-includes/template-loader.php(98): include('/home/XXX/...') #3 /home/XXX/wp-blog-header.php(19): require_once('/home/XXX/...') #4 /home/XXX/index.php(17): require('/home/monmaire/...') #5 {main} thrown in /home/XXXX/functions.php on line 99
</code>```

Example of data that works fine :
       $age = get_age($birthday);

For $birthday value = 05/04/1946 it works fine but for $birthday value = 26/01/1958 I get the error above.
I don't undertand why as the data seems to me the same format in the 2 cases.

Do you have any clue why ?

Thanks.
Regards.

答:
Problem is the date format. I believe you are switching between "/" and "-". If you are dealing with large data, it will be difficult to have to fix the whole database so my best advise is to do a preg_replace in order to always make sure what you are taking from the user/DB is in a correct format. Find example code below.

```<code>function get_age($birthDate_old) {
    $birthDate = ($birthDate_old);
    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}

$birthDate = "26/01/1958";
$birthDate = preg_replace("(/)", "-", $birthDate);

echo get_age($birthDate);
</code>```

I hope it helps! Let me know

Body:
I'm using the function below to calculate the age (in years) of people from birthdays dates (in european format DD/MM/YYYY) that are stored as text in Wordpress Advanced Custom Fields

function get_age($birthDate_old) {
    $birthDate = ($birthDate_old);
    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}

In the majority of cases it works fine but in some cases I got the error below :

 Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/01/1958) at position 0 (2): Unexpected character in /home/XXXX/functions.php:99 Stack trace: #0 /home/XXXX/functions.php(99): DateTime->__construct('26/01/1958') #1 /home/XXXX/single.php(69): get_age('26/01/1958') #2 /home/XXX/wp-includes/template-loader.php(98): include('/home/XXX/...') #3 /home/XXX/wp-blog-header.php(19): require_once('/home/XXX/...') #4 /home/XXX/index.php(17): require('/home/monmaire/...') #5 {main} thrown in /home/XXXX/functions.php on line 99

Example of data that works fine :
       $age = get_age($birthday);

For $birthday value = 05/04/1946 it works fine but for $birthday value = 26/01/1958 I get the error above.
I don't undertand why as the data seems to me the same format in the 2 cases.

Do you have any clue why ?

Thanks.
Regards.

Body:
Problem is the date format. I believe you are switching between "/" and "-". If you are dealing with large data, it will be difficult to have to fix the whole database so my best advise is to do a preg_replace in order to always make sure what you are taking from the user/DB is in a correct format. Find example code below.

function get_age($birthDate_old) {
    $birthDate = ($birthDate_old);
    return date_diff(new DateTime($birthDate), new DateTime('today'))->y;
}

$birthDate = "26/01/1958";
$birthDate = preg_replace("(/)", "-", $birthDate);

echo get_age($birthDate);

I hope it helps! Let me know


答:
Use . notation to add the hats object

const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
  {
    id: 01,
    name:'plain shirt',
  },
  {
    id: 02,
    name: 'stripe shirt',
  },
 ],
},

tshirt: {
id: 2,
title: 't-shirt',
item: [
  {
    id: 03,
    name: 'plain t-shirt',
  },
  {
    id: 04,
    name: 'stripe t-shirt',
   }
  ],
 },
}

clothing.hats={id:3, title:'hats', item:[{id:05, name:'blue hats'}]};
console.log(clothing.hats);```

Title: how to add nested object with new object


答:
I would drop creating Step and just use your dates directly as the X-value in your plot.
The reason R won't subset is because it considers your 50 dates as 50 strings.
Convert to a datettime class and manipulate it with scale_x_datetime():

```<code>Value <- runif(50,0,10)
Final <- data.frame(Value, Date)
Final$Date = as.POSIXct(Date)

ggplot(Final, aes(x = Date, y = Value, group = 1)) +
  geom_line(size = 1) +
  geom_point()  +
  scale_x_datetime(date_breaks = "2 hours", date_labels = "%H:%M")
</code>```

Title: Using date in scale_x_continuous with breaks

Body:
I am trying to replace the x-axis values created using step, which are values 1:50.
I can replace these easily using scale_x_continuous but when I use breaks I get the error below. I cannot use date and time in the plot function I am using so looking for a work around to get date on my axis

 Date =      c( "2018-10-18 00:00:00 BST", "2018-10-18 00:10:00 BST", "2018-10-18 00:20:00 BST", "2018-10-18 00:30:00 BST", "2018-10-18 00:40:00 BST", "2018-10-18 00:50:00 BST",
                 "2018-10-18 01:00:00 BST", "2018-10-18 01:10:00 BST", "2018-10-18 01:20:00 BST", "2018-10-18 01:30:00 BST", "2018-10-18 01:40:00 BST", "2018-10-18 01:50:00 BST",
                 "2018-10-18 02:00:00 BST", "2018-10-18 02:10:00 BST", "2018-10-18 02:20:00 BST", "2018-10-18 02:30:00 BST", "2018-10-18 02:40:00 BST", "2018-10-18 02:50:00 BST",
                 "2018-10-18 03:00:00 BST", "2018-10-18 03:10:00 BST", "2018-10-18 03:20:00 BST", "2018-10-18 03:30:00 BST", "2018-10-18 03:40:00 BST", "2018-10-18 03:50:00 BST",
                 "2018-10-18 04:00:00 BST", "2018-10-18 04:10:00 BST", "2018-10-18 04:20:00 BST", "2018-10-18 04:30:00 BST", "2018-10-18 04:40:00 BST", "2018-10-18 04:50:00 BST",
                 "2018-10-18 05:00:00 BST", "2018-10-18 05:10:00 BST", "2018-10-18 05:20:00 BST", "2018-10-18 05:30:00 BST", "2018-10-18 05:40:00 BST", "2018-10-18 05:50:00 BST",
                 "2018-10-18 06:00:00 BST", "2018-10-18 06:10:00 BST", "2018-10-18 06:20:00 BST", "2018-10-18 06:30:00 BST", "2018-10-18 06:40:00 BST", "2018-10-18 06:50:00 BST",
                 "2018-10-18 07:00:00 BST", "2018-10-18 07:10:00 BST", "2018-10-18 07:20:00 BST", "2018-10-18 07:30:00 BST", "2018-10-18 07:40:00 BST", "2018-10-18 07:50:00 BST",
                 "2018-10-18 08:00:00 BST", "2018-10-18 08:10:00 BST")

  Step  <- c(1:50)
  Value <- runif(50,0,10)
  Final <- data.frame(Step, Value)

                      ggplot(Final, aes(x = Step, y = Value)) +
                        geom_line(size = 1) +
                        geom_point() +
                        scale_x_continuous(labels=Date,breaks = seq(1, 50))       #works
                        scale_x_continuous(labels=Date,breaks = seq(1, 50,by=10)) #doesntwork

Error: `breaks` and `labels` must have the same length

Body:
I would drop creating Step and just use your dates directly as the X-value in your plot.
The reason R won't subset is because it considers your 50 dates as 50 strings.
Convert to a datettime class and manipulate it with scale_x_datetime():

Value <- runif(50,0,10)
Final <- data.frame(Value, Date)
Final$Date = as.POSIXct(Date)

ggplot(Final, aes(x = Date, y = Value, group = 1)) +
  geom_line(size = 1) +
  geom_point()  +
  scale_x_datetime(date_breaks = "2 hours", date_labels = "%H:%M")


问:
Override values.yaml in helm chart using nexus
Helm Chart Structure

```<code>web-service
  |_ _ _ templates
  |_ _ _ Chart.yaml
  |_ _ _ values.yaml
</code>```

I have helm chart setup in which my helm charts for my application are packaged .tgz
and pushed to nexus repo consider https://localhost:50714/#browse/browse:helm

Which is added to helm repositories.yaml using

```<code>helm repo add nexus https://localhost:50714/
</code>```

Once Repo is added I can see the chart

```<code>helm search
NAME                                    CHART VERSION   APP VERSION     DESCRIPTION
nexus/web-service                   1.0.0-k8s                       Custom microservice Helm chart
</code>```

To Install I Fire the below command

```<code>helm install nexus/ioc-web-service --version 1.0.0-k8s
</code>```

and application get deployed. So the application is deployed using default values.yaml
I need to make this configurable so that my default values.yaml is overridden by another file lets say
values-override.yaml

```<code>web-service
  |_ _ _ templates
  |_ _ _ Chart.yaml
  |_ _ _ values.yaml
  |_ _ _ values-override.yaml
</code>```

I used helm provision of passing extra file using -f command but it gives values-override.yaml file not found

```<code>helm install nexus/web-service -f values-override.yaml --version 1.0.0-k8s
</code>```

Need Some input on how to get the pass the override values in file format. As the override values can be dynamic. On one environment it can be 1 variable in another there are be 10 variable which needs to be overridden

答: You do not add the values-overwrite.yaml in the chart. Its a file locally where you run the command. Usually created by a templating taskrunner engine like Ansible or similar on the fly.

Body:
Helm Chart Structure

web-service
  |_ _ _ templates
  |_ _ _ Chart.yaml
  |_ _ _ values.yaml

I have helm chart setup in which my helm charts for my application are packaged .tgz
and pushed to nexus repo consider https://localhost:50714/#browse/browse:helm

Which is added to helm repositories.yaml using

helm repo add nexus https://localhost:50714/

Once Repo is added I can see the chart

helm search
NAME                                    CHART VERSION   APP VERSION     DESCRIPTION
nexus/web-service                   1.0.0-k8s                       Custom microservice Helm chart

To Install I Fire the below command

helm install nexus/ioc-web-service --version 1.0.0-k8s

and application get deployed. So the application is deployed using default values.yaml
I need to make this configurable so that my default values.yaml is overridden by another file lets say
values-override.yaml

web-service
  |_ _ _ templates
  |_ _ _ Chart.yaml
  |_ _ _ values.yaml
  |_ _ _ values-override.yaml

I used helm provision of passing extra file using -f command but it gives values-override.yaml file not found

helm install nexus/web-service -f values-override.yaml --version 1.0.0-k8s

Need Some input on how to get the pass the override values in file format. As the override values can be dynamic. On one environment it can be 1 variable in another there are be 10 variable which needs to be overridden


问:
Java jax-ws catalog files: difference between PUBLIC and SYSTEM entries
Can somebody explain the difference between SYSTEM and PUBLIC entries in the following TR9401 catalog format (which I use with Java jax-ws tools like xjc, wsimport etc.) The same concepts (SYSTEM and PUBLIC) appear in the other XML catalog formats as well.

In other words, I see the catalog file as a map: namespace (key) to location (value). What does it mean for a key-value pair in that map to be "SYSTEM" as opposed to "PUBLIC" ?

```<code>SYSTEM "http://www.w3.org/2001/xml.xsd" "xml.xsd"
SYSTEM "http://www.ivoa.net/xml/STC/STCregion/v1.10" "STCregion-v1.10.xsd"
PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "XMLSchema.dtd"
PUBLIC "http://www.ivoa.net/xml/STC/STCcoords/v1.10" "STCcoords-v1.10-mod.xsd"
</code>```

I've experimented a bit and have found that I can change certain entries from PUBLIC to SYSTEM and it still works, while the same change on other lines breaks the build.

答:
I'd think it comes from SGML/DTD where every document-type can have a PUBLIC-ID and a SYSTEM-ID. The former is just a sequence of characters (e.g. -//W3C//DTD HTML 4.01//EN), the latter is a filename or an URL.

In XML, xmlns is more or less the public-id while schemaLocation can be regarded as system-id.

An example I've just found on my computer: there is a /usr/share/xml/schema/xml-core/tr9401.dtd file that has a public-id -//GlobalTransCorp//DTD XML Catalogs V1.0-Based Extension V1.0//EN and a system-id http://globaltranscorp.org/oasis/catalog/xml/tr9401.dtd.

Now the catalog.xml file contains these lines:

```<code><public publicId="-//GlobalTransCorp//DTD XML Catalogs V1.0-Based Extension V1.0//EN" uri="tr9401.dtd"/>
<system systemId="http://globaltranscorp.org/oasis/catalog/xml/tr9401.dtd" uri="tr9401.dtd"/>
</code>```

The first resolves the public-id into an actual local file; the second resolves the system-id into an actual local file.

Body:
Can somebody explain the difference between SYSTEM and PUBLIC entries in the following TR9401 catalog format (which I use with Java jax-ws tools like xjc, wsimport etc.) The same concepts (SYSTEM and PUBLIC) appear in the other XML catalog formats as well.

In other words, I see the catalog file as a map: namespace (key) to location (value). What does it mean for a key-value pair in that map to be "SYSTEM" as opposed to "PUBLIC" ?

SYSTEM "http://www.w3.org/2001/xml.xsd" "xml.xsd"
SYSTEM "http://www.ivoa.net/xml/STC/STCregion/v1.10" "STCregion-v1.10.xsd"
PUBLIC "-//W3C//DTD XMLSCHEMA 200102//EN" "XMLSchema.dtd"
PUBLIC "http://www.ivoa.net/xml/STC/STCcoords/v1.10" "STCcoords-v1.10-mod.xsd"

I've experimented a bit and have found that I can change certain entries from PUBLIC to SYSTEM and it still works, while the same change on other lines breaks the build.

Body:
I'd think it comes from SGML/DTD where every document-type can have a PUBLIC-ID and a SYSTEM-ID. The former is just a sequence of characters (e.g. -//W3C//DTD HTML 4.01//EN), the latter is a filename or an URL.

In XML, xmlns is more or less the public-id while schemaLocation can be regarded as system-id.

An example I've just found on my computer: there is a /usr/share/xml/schema/xml-core/tr9401.dtd file that has a public-id -//GlobalTransCorp//DTD XML Catalogs V1.0-Based Extension V1.0//EN and a system-id http://globaltranscorp.org/oasis/catalog/xml/tr9401.dtd.

Now the catalog.xml file contains these lines:

<public publicId="-//GlobalTransCorp//DTD XML Catalogs V1.0-Based Extension V1.0//EN" uri="tr9401.dtd"/>
<system systemId="http://globaltranscorp.org/oasis/catalog/xml/tr9401.dtd" uri="tr9401.dtd"/>

The first resolves the public-id into an actual local file; the second resolves the system-id into an actual local file.


问:
SAPUI5 Table: unbindRows & destroyColumns cause error: Cannot read property 'shouldRender' of undefined
I am using the Table object from the SAPUI5's sap.ui.table namespace:

var oTableOverview = new sap.ui.table.Table();

On rowSelectionChange, when selecting one row I populate another table, let's call it oTableDetail, that is filled with some data.

When deselecting the row from the first table, I want to clear the content of the second, and for that I use:

oTableDetail.destroyColumns();

oTableDetail.unbindRows();

When deselecting the row I get the following error:

TableRenderer.js:6 Uncaught TypeError: Cannot read property 'shouldRender' of undefined

I found the method shouldRender of the sap.ui.table.Column class, but I am not sure why would the cells be rerendered in this case.

I also noticed that if I use either oTable.destroyColumns(), or oTable.unbindRows() separately, the error does not appear.

I am using the "1.38.11" version of SAPUI5.

Can you please help me identify why this happens?

EDIT 1:  A possible workaround would be to use:

oTableDetail.setModel(new sap.ui.model.json.JSONModel({}));

oTableDetail.destroyColumns();

Although I still don't know why the code mentioned before is not working.

EDIT 2: A behavior that I find a bit weird:

trying to add a setTimeout like this works (the error is not happening):

oTable.destroyColumns();

setTimeout(function(){  oTable.unbindRows();  }, 50);

but this other way it doesn't work (the error still appears) even if the delay is longer:

oTable.unbindRows();

setTimeout(function(){  oTable.destroyColumns();  }, 50);

答:
So if you don't want to set a new model, then just try to clean oData of an existing model.</p>

```<code>var oTable = this.byId("oTable")
//your model with new dynamic data
var oModel = oTable.getModel();

oModel.setData(null);
// then if its needed, use updateBindings method to refresh
oModel.updateBindings();
</code>```

Body:
So if you don't want to set a new model, then just try to clean oData of an existing model.

var oTable = this.byId("oTable")
//your model with new dynamic data
var oModel = oTable.getModel();

oModel.setData(null);
// then if its needed, use updateBindings method to refresh
oModel.updateBindings();


问:
How do you install something directly from the GitHub repo?
I am a beginner, and tried to install PyDictionary with pip. It installed, but I had the same issue as this thread - it did not work:
    How to get rid of the BeautifulSoup html parser error when I'm not using BeautifulSoup
Someone on here suggested installing if directly from the GitHub repo, but I'm not sure which file to download and what to do next.

UPDATE 1

I've updated pip, and used:

python3 -m pip install PyDictionary

(I needed python3 for some reason). I then used this program:

```<code>from PyDictionary import PyDictionary
dictionary = PyDictionary()
print (dictionary.synonym("Life"))
</code>```

But got:

Warning (from warnings module): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PyDictionary/utils.py", line 5 return BeautifulSoup(requests.get(url).text) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 5 of the file /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PyDictionary/utils.py.

To get rid of this warning, pass the additional argument 'features="lxml"' to the BeautifulSoup constructor. Life has no Synonyms in the API None –

UPDATE 2

```<code>python3 -m pip install git+https://github.com/geekpradd/PyDictionary
</code>```

returns:

Collecting git+github.com/geekpradd/PyDictionary Cloning github.com/geekpradd/PyDictionary to /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt Running command git clone -q github.com/geekpradd/PyDictionary /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxtERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'"'"'; file__='"'"'/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/pip-egg-info cwd: /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/ Complete output (5 lines): Traceback (most recent call last):
  File "", line 1, in  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'
  ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output

答:
You can normally install directly using the github repos with

```<code>python3 -m pip install git+https://github.com/geekpradd/PyDictionary
</code>```

But this repository has no setup.py file that's why it fails.
To me it's more likely a problem with conflicting python versions, so:

python3 -m pip install PyDictionary
```

Is enough

Body:
I am a beginner, and tried to install PyDictionary with pip. It installed, but I had the same issue as this thread - it did not work:
    How to get rid of the BeautifulSoup html parser error when I'm not using BeautifulSoup
Someone on here suggested installing if directly from the GitHub repo, but I'm not sure which file to download and what to do next.

UPDATE 1

I've updated pip, and used:

python3 -m pip install PyDictionary

(I needed python3 for some reason). I then used this program:

from PyDictionary import PyDictionary
dictionary = PyDictionary()
print (dictionary.synonym("Life"))

But got:

Warning (from warnings module): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PyDictionary/utils.py", line 5 return BeautifulSoup(requests.get(url).text) UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("lxml"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 5 of the file /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PyDictionary/utils.py.

To get rid of this warning, pass the additional argument 'features="lxml"' to the BeautifulSoup constructor. Life has no Synonyms in the API None –

UPDATE 2

python3 -m pip install git+https://github.com/geekpradd/PyDictionary

returns:

Collecting git+github.com/geekpradd/PyDictionary Cloning github.com/geekpradd/PyDictionary to /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt Running command git clone -q github.com/geekpradd/PyDictionary /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxtERROR: Command errored out with exit status 1: command: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'"'"'; file__='"'"'/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/pip-egg-info cwd: /private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/ Complete output (5 lines): Traceback (most recent call last):
  File "", line 1, in  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tokenize.py", line 392, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: '/private/var/folders/sn/081bt1wd0d3gy2styt2_l1vw0000gn/T/pip-req-build-73cegdxt/setup.py'
  ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output

Body:
You can normally install directly using the github repos with

python3 -m pip install git+https://github.com/geekpradd/PyDictionary

But this repository has no setup.py file that's why it fails.
To me it's more likely a problem with conflicting python versions, so:

python3 -m pip install PyDictionary

Is enough


问:
C++ D&D Point Buy - Point Tracking?
I'm teaching myself C++ by coding a D&D 5E character creator.  I'm aware that it will be at least a three-step process, where I (1) learn the language, (2) implement data validation, then (3) learn and implement proper conventions.

I'm trying to only use standard libraries.  Right now I'm working on the ability score point buy system.  It might be that I'm exhausted, but I'm not sure how to properly track point expenditure.

See, in the point buy system, you can allocate 27 points among your six ability scores.  They each start at 8.  It costs one point per increase, up to 13, then two points per increase, up to 15.  Values above 15 and below 8 are impermissible.

I've gotten points to be tracked, and the upper and lower bounds recognized. I just can't figure any way (let alone a simple and elegant one like I'd prefer) to adjust the point costs for scores entering or leaving 14 or 15.

```<code>#include <iostream>
#include <string>

using namespace std;

int main()
{
    const string abilities[6] = { "STR", "DEX", "CON", "INT", "WIS", "DEX" };

    bool editing = 1;

    int stats[6] = { 8, 8, 8, 8, 8, 8 };
    int points = 27;

    while (editing == 1)
    {
        int select = 0;
        int adjust = 0;
        int result = 0;
        int remainder = 0;

        cout << "You have " << points << " points to spend on your ability scores." << endl;
        cout << "Select a number to adjust that ability's score:\n1) STR = " << stats[0] << "\n2) DEX = " << stats[1] << "\n3) CON = " << stats[2] << "\n4) INT = " << stats[3] << "\n5) WIS = " << stats[4] << "\n6) CHA = " << stats[5] << endl;
        cout << "Select a number outside the above range to finalize your ability scores.\n";
        cin >> select;

        while (cin.fail())
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Invalid entry; try again: ";
            cin >> select;
        }

        select -= 1;

        if (select < 0 || select > 5)
        {
            editing = 0;
            break;
        }

        cout << "Adjust " << stats[select] << " " << abilities[select] << " by how much? ";
        cin >> adjust;

        result = (stats[select] + adjust);

        if (result < 8)
        {
            cout << "Ability scores cannot be lower than 8 in the point buy system.\n";
        }
        else if (result > 15)
        {
            cout << "Ability scores cannot be higher than 15 in the point buy system.\n";
        }
        else
        {
            remainder = stats[select] - result;
            points += remainder;
            if (points < 1)
            {
                cout << "You do not have the points for that operation.";
                break;
            }
            else if (points > 27)
            {
                cout << "You cannot accrue more than 27 points.";
                break;
            }
            stats[select] = result;
        }
    }
}
</code>```

Does anyone have any suggestions or examples I could tear apart?

EDIT:

...replace the 4th to last line in the code above to enact a tedious and inelegant solution to my query:

```<code>            if (stats[select] == 15 && result == 14)
            {
                points += remainder + 1;
            }
            else if (stats[select] == 15 && result < 14)
            {
                points += remainder + 2;
            }
            else if (stats[select] == 14 && result < 14)
            {
                points += remainder + 1;
            }
            else if (result == 15 && stats[select] == 14)
            {
                points += remainder - 1;
            }
            else if (result == 15 && stats[select] < 14)
            {
                points += remainder - 2;
            }
            else if (result == 14 && stats[select] < 14)
            {
                points += remainder - 1;
            }
            else
            {
                points += remainder;
            }
            stats[select] = result;
</code>```

This still isn't perfect; the extra points for the conditionals are independent from the check to see if there are enough points left to perform the operation.

答:
Rather than doing arithmetic with the adjustment, why not just have a lookup of stat to points cost?</p>

```<code>// outside main()
int stat_cost(int stat) {
    switch (stat){
        case 8: return 0;
        case 9: return 1;
        case 10: return 2;
        case 11: return 3;
        case 12: return 4;
        case 13: return 5;
        case 14: return 7;
        case 15: return 9;
        default: throw std::out_of_range("stat must be between 8 and 15 (inclusive)");
    }
}

// after checking result is in range
int points_result = points - stat_cost(result) + stat_cost(stats[select]);
if (points_result < 0)
{
    std::cout << "You do not have the points for that operation.";
    break;
}
else if (points_result > 27) // N.b. This condition can never be true
{
    std::cout << "You cannot accrue more than 27 points.";
    break;
}
points = points_result;
stats[select] = result;
</code>```

Title: C++ D&D Point Buy - Point Tracking?

Body:
I'm teaching myself C++ by coding a D&D 5E character creator.  I'm aware that it will be at least a three-step process, where I (1) learn the language, (2) implement data validation, then (3) learn and implement proper conventions.

I'm trying to only use standard libraries.  Right now I'm working on the ability score point buy system.  It might be that I'm exhausted, but I'm not sure how to properly track point expenditure.

See, in the point buy system, you can allocate 27 points among your six ability scores.  They each start at 8.  It costs one point per increase, up to 13, then two points per increase, up to 15.  Values above 15 and below 8 are impermissible.

I've gotten points to be tracked, and the upper and lower bounds recognized. I just can't figure any way (let alone a simple and elegant one like I'd prefer) to adjust the point costs for scores entering or leaving 14 or 15.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    const string abilities[6] = { "STR", "DEX", "CON", "INT", "WIS", "DEX" };

    bool editing = 1;

    int stats[6] = { 8, 8, 8, 8, 8, 8 };
    int points = 27;

    while (editing == 1)
    {
        int select = 0;
        int adjust = 0;
        int result = 0;
        int remainder = 0;

        cout << "You have " << points << " points to spend on your ability scores." << endl;
        cout << "Select a number to adjust that ability's score:\n1) STR = " << stats[0] << "\n2) DEX = " << stats[1] << "\n3) CON = " << stats[2] << "\n4) INT = " << stats[3] << "\n5) WIS = " << stats[4] << "\n6) CHA = " << stats[5] << endl;
        cout << "Select a number outside the above range to finalize your ability scores.\n";
        cin >> select;

        while (cin.fail())
        {
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Invalid entry; try again: ";
            cin >> select;
        }

        select -= 1;

        if (select < 0 || select > 5)
        {
            editing = 0;
            break;
        }

        cout << "Adjust " << stats[select] << " " << abilities[select] << " by how much? ";
        cin >> adjust;

        result = (stats[select] + adjust);

        if (result < 8)
        {
            cout << "Ability scores cannot be lower than 8 in the point buy system.\n";
        }
        else if (result > 15)
        {
            cout << "Ability scores cannot be higher than 15 in the point buy system.\n";
        }
        else
        {
            remainder = stats[select] - result;
            points += remainder;
            if (points < 1)
            {
                cout << "You do not have the points for that operation.";
                break;
            }
            else if (points > 27)
            {
                cout << "You cannot accrue more than 27 points.";
                break;
            }
            stats[select] = result;
        }
    }
}

Does anyone have any suggestions or examples I could tear apart?

EDIT:

...replace the 4th to last line in the code above to enact a tedious and inelegant solution to my query:

            if (stats[select] == 15 && result == 14)
            {
                points += remainder + 1;
            }
            else if (stats[select] == 15 && result < 14)
            {
                points += remainder + 2;
            }
            else if (stats[select] == 14 && result < 14)
            {
                points += remainder + 1;
            }
            else if (result == 15 && stats[select] == 14)
            {
                points += remainder - 1;
            }
            else if (result == 15 && stats[select] < 14)
            {
                points += remainder - 2;
            }
            else if (result == 14 && stats[select] < 14)
            {
                points += remainder - 1;
            }
            else
            {
                points += remainder;
            }
            stats[select] = result;

This still isn't perfect; the extra points for the conditionals are independent from the check to see if there are enough points left to perform the operation.

Body:
Rather than doing arithmetic with the adjustment, why not just have a lookup of stat to points cost?

// outside main()
int stat_cost(int stat) {
    switch (stat){
        case 8: return 0;
        case 9: return 1;
        case 10: return 2;
        case 11: return 3;
        case 12: return 4;
        case 13: return 5;
        case 14: return 7;
        case 15: return 9;
        default: throw std::out_of_range("stat must be between 8 and 15 (inclusive)");
    }
}

// after checking result is in range
int points_result = points - stat_cost(result) + stat_cost(stats[select]);
if (points_result < 0)
{
    std::cout << "You do not have the points for that operation.";
    break;
}
else if (points_result > 27) // N.b. This condition can never be true
{
    std::cout << "You cannot accrue more than 27 points.";
    break;
}
points = points_result;
stats[select] = result;