问:
How to set onClickListener for items in a ListView (items of listview are generated dynamically by retreiving data from firebase)
Hi Iam trying to make a chatApp.Iam successful with initial steps like user authentication,registration.After a successfull login user gets a screen as shown in this image:

Now the list of users here are generated by following code:

```<code>ListView listView;
View view;
ArrayList<String> usernames = new ArrayList<>();
String name;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference();
DatabaseReference userRef = root.child("users");

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
   view = inflater.inflate(R.layout.fragment_users,container,false);
   listView =(ListView) view.findViewById(R.id.listView);
   final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (getContext(),android.R.layout.simple_list_item_1,usernames);
   listView.setAdapter(arrayAdapter);

   userRef.addChildEventListener(new ChildEventListener() {
     @Override
     public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
       String value = dataSnapshot.getValue().toString();
       try
       {
         JSONObject object = new JSONObject(value);
         name = object.getString("username");
       }
       catch(JSONException e)
       {
         e.printStackTrace();
       }

       usernames.add(name);
       arrayAdapter.notifyDataSetChanged();
     }

     @Override
     public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

     @Override
     public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {}
  });

  return view;
}
</code>```

Now whenever user clicks on particular name I've to take him to a messageActivity(more precisely another activity). Please tell me how I can add onClickListeners or any other possible method to do this?

答:
Try this

Declare this in your fragment or activity

```<code>private OnItemClickListener listPairedClickItem = new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > arg0, View arg1, int arg2, long arg3) {
        String personName = usernames.get(position);
        Toast.makeText( context, "listview clicked ", Toast.LENGTH_LONG ).show();
        Intent intent = new Intent(currenactivityname.this, activitytolaunchname.class);
        intent.putExtra("username",personName ); //get this name in next activity and show in title  bar
        startActivity(intent);
    }
};
</code>```

Usage

```<code>listView.setOnItemClickListener( listPairedClickItem );
</code>```

Body:
Hi Iam trying to make a chatApp.Iam successful with initial steps like user authentication,registration.After a successfull login user gets a screen as shown in this image:

Now the list of users here are generated by following code:

ListView listView;
View view;
ArrayList<String> usernames = new ArrayList<>();
String name;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference();
DatabaseReference userRef = root.child("users");

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
   view = inflater.inflate(R.layout.fragment_users,container,false);
   listView =(ListView) view.findViewById(R.id.listView);
   final ArrayAdapter <String> arrayAdapter = new ArrayAdapter<String>
     (getContext(),android.R.layout.simple_list_item_1,usernames);
   listView.setAdapter(arrayAdapter);

   userRef.addChildEventListener(new ChildEventListener() {
     @Override
     public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
       String value = dataSnapshot.getValue().toString();
       try
       {
         JSONObject object = new JSONObject(value);
         name = object.getString("username");
       }
       catch(JSONException e)
       {
         e.printStackTrace();
       }

       usernames.add(name);
       arrayAdapter.notifyDataSetChanged();
     }

     @Override
     public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {}

     @Override
     public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {}

     @Override
     public void onCancelled(@NonNull DatabaseError databaseError) {}
  });

  return view;
}

Now whenever user clicks on particular name I've to take him to a messageActivity(more precisely another activity). Please tell me how I can add onClickListeners or any other possible method to do this?

Body:
Try this

Declare this in your fragment or activity

private OnItemClickListener listPairedClickItem = new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > arg0, View arg1, int arg2, long arg3) {
        String personName = usernames.get(position);
        Toast.makeText( context, "listview clicked ", Toast.LENGTH_LONG ).show();
        Intent intent = new Intent(currenactivityname.this, activitytolaunchname.class);
        intent.putExtra("username",personName ); //get this name in next activity and show in title  bar
        startActivity(intent);
    }
};

Usage

listView.setOnItemClickListener( listPairedClickItem );


来源: stackexchange

问:
Android [LocationManager] requestLocationUpdates(), java.lang.RuntimeException
I am getting this error when requestion for location updates inside service. Location permission is granted, LocationManager is not null, Provider is not null.

```<code>LocationManager: [LocationManager] requestLocationUpdates(),
    java.lang.RuntimeException
        at android.location.LocationManager.requestLocationUpdates(LocationManager.java:1013)
        at android.location.LocationManager.requestLocationUpdates(LocationManager.java:595)
        at com.trackinglibrary.service.DataService.createAndRequestLocationUpdates(DataService.java:759)
        at com.trackinglibrary.service.DataService.onStartCommand(DataService.java:252)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3694)
        at android.app.ActivityThread.access$1600(ActivityThread.java:202)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:198)
        at android.app.ActivityThread.main(ActivityThread.java:6729)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

Location code that I am calling inside  onStartCommand():

```<code>@SuppressLint("MissingPermission")
    private void createAndRequestLocationUpdates() {
        try {

            if (!TrackThatUtils.isLocationEnabled(getApplicationContext())) {
                Log.e(TAG, "Location is disable.");
                return;
            }

            if (locationManager == null) {
                locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

                addProximityAlert();
            }

            if (locationManager == null || !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                Log.e(TAG, "Location provider is disable.");
                return;
            }

            // getting GPS status
            boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            Log.e(TAG, "Location provider is: " + isGPSEnabled);

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.

                Log.e(TAG, "== Error On onConnected() Permission not granted");
                //Permission not granted by user so cancel the further execution.
                return;
            }

            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
            criteria.setAltitudeRequired(false);
            criteria.setSpeedRequired(true);
            //setCostAllowed(true): This flag enables LocationManager to exchange “data packet” with
            // 3G/4G network base stations in order to get better location
            criteria.setCostAllowed(true);
            criteria.setBearingRequired(false);

            //API level 9 and up
            criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
            criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);

            String provider = locationManager.getBestProvider(criteria, true);

//          locationManager.requestLocationUpdates(gpsFreqInMillis, gpsFreqInDistance, criteria, locationListener, null);

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                    0, this);
            Log.i(TAG, "request for location updates..");
        } catch (SecurityException | IllegalArgumentException e) {
            Log.e(TAG, "Exception inside createAndRequestLocationUpdates(): " + e);
        }
    }
</code>```

答: According to the documentation RuntimeException is called when calling thread has no Looper. Try to call Looper.prepare() before you call LocationManager

ContentLicense: CC BY-SA 4.0

Body:
I am getting this error when requestion for location updates inside service. Location permission is granted, LocationManager is not null, Provider is not null.

LocationManager: [LocationManager] requestLocationUpdates(),
    java.lang.RuntimeException
        at android.location.LocationManager.requestLocationUpdates(LocationManager.java:1013)
        at android.location.LocationManager.requestLocationUpdates(LocationManager.java:595)
        at com.trackinglibrary.service.DataService.createAndRequestLocationUpdates(DataService.java:759)
        at com.trackinglibrary.service.DataService.onStartCommand(DataService.java:252)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3694)
        at android.app.ActivityThread.access$1600(ActivityThread.java:202)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:198)
        at android.app.ActivityThread.main(ActivityThread.java:6729)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Location code that I am calling inside  onStartCommand():

@SuppressLint("MissingPermission")
    private void createAndRequestLocationUpdates() {
        try {

            if (!TrackThatUtils.isLocationEnabled(getApplicationContext())) {
                Log.e(TAG, "Location is disable.");
                return;
            }

            if (locationManager == null) {
                locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

                addProximityAlert();
            }

            if (locationManager == null || !locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                Log.e(TAG, "Location provider is disable.");
                return;
            }

            // getting GPS status
            boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            Log.e(TAG, "Location provider is: " + isGPSEnabled);

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.

                Log.e(TAG, "== Error On onConnected() Permission not granted");
                //Permission not granted by user so cancel the further execution.
                return;
            }

            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
            criteria.setAltitudeRequired(false);
            criteria.setSpeedRequired(true);
            //setCostAllowed(true): This flag enables LocationManager to exchange “data packet” with
            // 3G/4G network base stations in order to get better location
            criteria.setCostAllowed(true);
            criteria.setBearingRequired(false);

            //API level 9 and up
            criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
            criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);

            String provider = locationManager.getBestProvider(criteria, true);

//          locationManager.requestLocationUpdates(gpsFreqInMillis, gpsFreqInDistance, criteria, locationListener, null);

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
                    0, this);
            Log.i(TAG, "request for location updates..");
        } catch (SecurityException | IllegalArgumentException e) {
            Log.e(TAG, "Exception inside createAndRequestLocationUpdates(): " + e);
        }
    }


问:
How to limit what the Linux Teminal prints by defaults (prompt)? (i.e. number of subfolder)
Context:

The problem comes from the work folder location: if I should work in a subfolder of a subfolder of a subfolder et cetera... The command line of the shell bask in Linux is so long that can use two lines to be correctly printed.

Question:

Is there a way of showing only the last (or the few last) working subfolder?

Example:

What is actually printed:

```<code>user@user-pc:~/Documents/robotic_arm/Monitoring/difference/develop/component/example/subfolder/subexample/module$
</code>```

What I would love to see:

```<code>user@user-pc:~/.../subexample/module$
</code>```

More Info:

Xubuntu 16.04

Terminator is used instead of the default "Linux Terminal Emulator"

I had a look on this Stackoverflow's question but it is for the input and not for the default line printed by the shell

答:
I do not know why but the previous answer does not work on my machine. However, an alternative solution that works fine is:

```<code>PROMPT_DIRTRIM=N
</code>```

where N is the number of subfolders you want to see.

Example:

```<code>user@user-pc:~/Documents/robotic_arm/difference/develop/component/ $ PROMPT_DIRTRIM=2
user@user-pc:~/.../develop/component/ $
</code>```

The solution was suggested by one of the answers above this question.

Body:
Context:

The problem comes from the work folder location: if I should work in a subfolder of a subfolder of a subfolder et cetera... The command line of the shell bask in Linux is so long that can use two lines to be correctly printed.

Question:

Is there a way of showing only the last (or the few last) working subfolder?

Example:

What is actually printed:

user@user-pc:~/Documents/robotic_arm/Monitoring/difference/develop/component/example/subfolder/subexample/module$

What I would love to see:

user@user-pc:~/.../subexample/module$

More Info:

Xubuntu 16.04

Terminator is used instead of the default "Linux Terminal Emulator"

I had a look on this Stackoverflow's question but it is for the input and not for the default line printed by the shell

Body:
I do not know why but the previous answer does not work on my machine. However, an alternative solution that works fine is:

PROMPT_DIRTRIM=N

where N is the number of subfolders you want to see.

Example:

user@user-pc:~/Documents/robotic_arm/difference/develop/component/ $ PROMPT_DIRTRIM=2
user@user-pc:~/.../develop/component/ $

The solution was suggested by one of the answers above this question.


问:
firebird - deadlock update conflicts with concurrent update
I'm maintaining an old software (Firebird 2.5 and C#.net). Recently we get a lot of "deadlock update conflicts with concurrent update" errors. I checked the transaction settings. It doesn't set Wait time out option:

```<code>public override IDbTransaction BeginTransaction(IDbConnection conn)
{
    FbTransaction trans = null;

    if (conn.State != ConnectionState.Open)
        conn.Open();

    FbTransactionOptions op = new FbTransactionOptions();
    op.TransactionBehavior = FbTransactionBehavior.ReadCommitted | FbTransactionBehavior.RecVersion;

    trans = ((FbConnection)conn).BeginTransaction(op);

    return trans;
}
</code>```

So, why do we get timeout? Shouldn't it wait for one transaction to be committed to commit the next one?

答:
A "deadlock update conflicts with concurrent update" happens when multiple transaction want to modify the same row. Only one updater can really change the row and commit. As long as the first transaction hasn't committed, the update in the second transaction will wait (indefinitely or until the configured timeout). As soon as the first transaction commits, the update in the second transaction will end with this error (if instead the first transaction had rolled back, the second would have continued).

If this started happening recently, you need to identify what changed. Did another tool also start writing to the database, did the number of users increase, did you upgrade something (eg Firebird, or the Firebird ado.net provider version, etc), did you make a change that resulted in long running transactions performing updates?

Your application code will need to be changed to automatically retry on this error. Also make sure that your transactions aren't too 'long' time-wise (the longer transactions are, the more chance of these types of errors occurring). In addition, you could try and change the transaction behavior from FbTransactionBehavior.RecVersion to FbTransactionBehavior.NoRecVersion, but that can introduce waiting when reading records that are currently updated by concurrent transactions, and it may actually increase occurrence of update conflicts if the record was updated (and committed) by a transaction with a newer transaction id.

See also http://www.firebirdfaq.org/faq151/, Transactions in Firebird: ACID, Isolation levels, Deadlocks, and Resolution of update conflicts and Transaction Statements.

Body:
I'm maintaining an old software (Firebird 2.5 and C#.net). Recently we get a lot of "deadlock update conflicts with concurrent update" errors. I checked the transaction settings. It doesn't set Wait time out option:

public override IDbTransaction BeginTransaction(IDbConnection conn)
{
    FbTransaction trans = null;

    if (conn.State != ConnectionState.Open)
        conn.Open();

    FbTransactionOptions op = new FbTransactionOptions();
    op.TransactionBehavior = FbTransactionBehavior.ReadCommitted | FbTransactionBehavior.RecVersion;

    trans = ((FbConnection)conn).BeginTransaction(op);

    return trans;
}

So, why do we get timeout? Shouldn't it wait for one transaction to be committed to commit the next one?


问:
Parsing a JSON with dl4j RecordReader
I plan to use dl4j on a dataset which is in the following format:

{"articles": [{"abstractText":"text..", "journal":"journal..", "meshMajor":["mesh1",...,"meshN"],
  "pmid":"PMID", "title":"title..", "year":"YYYY"},..., {..}]}

The field meshMajor contains the class labels and the rest are the input for the model. The input features are textual data.

I was wondering if there are any built in JSON dataset iterators like the CSV one. I looked up in the examples posted on github but couldn't locate one. If there isn't one available, can someone please provide some pointers on implementing it.

Thanks!

答:
This looks like a promising start:

https://deeplearning4j.org/docs/latest/datavec-serialization

You should then be able to use the examples here:

https://github.com/deeplearning4j/dl4j-examples/tree/master/datavec-examples/src/main/java/org/datavec/transform/basic

Title: Parsing a JSON with dl4j RecordReader


问:
is it possible to cast Dword to Type Name?
Let's take a look at this kind of code :

```<code>// Return me Dword of int
dword t = GetValueTypeNo<int>();
//here trying to tell to GetValue that my template is int (since t is dword of int)
int test5 = myVector.GetValue<t>("test5");
</code>```

Of course this kind of code is not working and it's actually useless. But it is possible to do something like that? cast a dword to a type name like int?

答:
If GetValueTypeNo can be made a constexpr function, you can make something like this:

```<code>template<typename T>
constexpr dword GetValueTypeNo() { ... }

template<dword>
struct Type_selector;

template<>
struct Type_selector<dword_value_for_int> {
    using Type = int;
};

template<>
struct Type_selector<dword_value_for_long> {
    using Type = long;
};

...

template<dword type>
using Type = typename Type_selector<type>::Type;
</code>```

and then write:

```<code>template<dword type>
Type<type> GetValue(...)
{ ... }

constexpr dword t = GetValueTypeNo<int>();
int test5 = myVector.GetValue<t>("test5");
</code>```

Body:
Let's take a look at this kind of code :

// Return me Dword of int
dword t = GetValueTypeNo<int>();
//here trying to tell to GetValue that my template is int (since t is dword of int)
int test5 = myVector.GetValue<t>("test5");

Of course this kind of code is not working and it's actually useless. But it is possible to do something like that? cast a dword to a type name like int?

Body:
If GetValueTypeNo can be made a constexpr function, you can make something like this:

template<typename T>
constexpr dword GetValueTypeNo() { ... }

template<dword>
struct Type_selector;

template<>
struct Type_selector<dword_value_for_int> {
    using Type = int;
};

template<>
struct Type_selector<dword_value_for_long> {
    using Type = long;
};

...

template<dword type>
using Type = typename Type_selector<type>::Type;

and then write:

template<dword type>
Type<type> GetValue(...)
{ ... }

constexpr dword t = GetValueTypeNo<int>();
int test5 = myVector.GetValue<t>("test5");


问:
How can i format log4j time to specific timezone?
Below is my log4j2 layout :

```<code>layout = %d{DATE} %-5p - %m%n.
</code>```

It'll print time in log as -> 2019-05-28 11:48:36,977 INFO  - Hello World.

Which is my system datetime(IST),but I want to print log datetime in GMT format.

is it possible to format timezone in log4j2?

答:
Yes it is possible.

To format date time in GMT please consider

```<code>%d{yyyy-MM-dd:HH:mm:ss.SSS,GMT+0}
</code>```

You can also change time zone by adding number after GMT for example:

```<code>%d{yyyy-MM-dd:HH:mm:ss.SSS,GMT+06}
</code>```

for more check out this link: Log4J Layouts

Body:
Below is my log4j2 layout :

layout = %d{DATE} %-5p - %m%n.

It'll print time in log as -> 2019-05-28 11:48:36,977 INFO  - Hello World.

Which is my system datetime(IST),but I want to print log datetime in GMT format.

is it possible to format timezone in log4j2?

Body:
Yes it is possible.

To format date time in GMT please consider

%d{yyyy-MM-dd:HH:mm:ss.SSS,GMT+0}

You can also change time zone by adding number after GMT for example:

%d{yyyy-MM-dd:HH:mm:ss.SSS,GMT+06}

for more check out this link: Log4J Layouts


问:
What method of OOP would be appropriate for periodic table properties?
I'm trying to code in java a pet project using the periodic table. What's the best/efficient way to make a data set out of periodic element properties. Should I make a class of all the elements individually? or make an array  or objects?

Initial plan was to just create redundant classes with properties for each individual element. (ex. class for hydrogen, class for carbon, class for nitrogen... etc). with each class having attributes such as atomic number, weight, name, etc.. It's a lot of work, but wondering if there are efficient ways lol. The goal is to make this as modular as possible so i can add more property values or conditions if I choose to do so

I am pretty new to java, so please suggest anything. Also let me know if someone has already done this or has made a library for this. :)

答:
Make one class for a chemical element with all its properties.

For categorical properties, like its group; is it a metal (alkali/lanthanoid /...) or noble gas, or trans-uranes or whatever, you can either add it as field, or hold an external Set of them, or indeed use inheritance. Also possible is to implement a (marker) interface Metal.

Inheritance is sensible only for different behavior, methods, in a strict hierarchy.
Even an Animal should not inherit from SwimmingAnimal or FlyingAnimal, but implement interfaces Swimming and Flying, as it can be both.
So for the groups Metal/Noble Gass/... one might use inheritance. But the background color in the periodic table for a group would then be held in every instance. IMHO it
only makes sense if for a Metal there is a deriveSalt(...) and such. And that I do not see.


问:
NSThread and object retain count issue
I want to be able to call an object's method on a new thread; but, I am confused about how to manage retain counts (or even if it is an issue).

In a non-threaded scenario, I would do this:

```<code>MyObject *newObject = [[MyObject alloc] init];
[newObject doSomething];
[newObject release];
</code>```

In this scenario, everything's fine. However, my question is whether the following threaded version is a problem:

```<code>MyObject *newObject = [[MyObject alloc] init];
[NSThread detachNewThreadSelector:@selector(doSomething)
                         toTarget:newObject
                       withObject:nil];
[newObject release];
</code>```

In this case, do I have to worry about newObject being released while -doSomething is processing? If the answer is yes, then it seems messy to have -doSomething retain self.

Is this an issue? And, if so, what's the correct solution?

答: detachNewThreadSelector retains both aTarget (newObject above) and anArgument (nil above) while the thread is executing, then releases them before exiting the thread.</p>

OwnerDisplayName: Scott S

LastEditorDisplayName: Chris Hanson

ContentLicense: CC BY-SA 2.5

Title: NSThread and object retain count issue

Body:
I want to be able to call an object's method on a new thread; but, I am confused about how to manage retain counts (or even if it is an issue).

In a non-threaded scenario, I would do this:

MyObject *newObject = [[MyObject alloc] init];
[newObject doSomething];
[newObject release];

In this scenario, everything's fine. However, my question is whether the following threaded version is a problem:

MyObject *newObject = [[MyObject alloc] init];
[NSThread detachNewThreadSelector:@selector(doSomething)
                         toTarget:newObject
                       withObject:nil];
[newObject release];

In this case, do I have to worry about newObject being released while -doSomething is processing? If the answer is yes, then it seems messy to have -doSomething retain self.

Is this an issue? And, if so, what's the correct solution?


问:
Replace image color and maintain 100% alpha background
I have a png with a transparent background. The foreground is a single color. I want to change this single color while preserving the 100% alpha background.

The code below doesn't work, it worked when I had a gif. However, when I changed the gif to a png then added the alpha stuff the color change broke down.

If I add imagetruecolortopalette($im, false, 255); the color is changed but alpha is lost.

Can someone show me where I am going wrong please

```<code>$imgname = "block.png";
$im = imagecreatefrompng($imgname);
imagealphablending($im, false);

$index = imagecolorclosest ($im, 153,153,153); // get Grey COlor
imagecolorset($im,$index,0,0,0); // SET NEW COLOR

imageAlphaBlending($im, true);
imageSaveAlpha($im, true);
$imgname = "result.png";
imagepng($im, $imgname ); // save image as gif
imagedestroy($im);
</code>```

EDIT :: This is a simple enough script.

When I used a gif, the color changed and the new image was saved. When a changed to a .png. The color no longer changed and thus the original image passes through the script unchanged.

答: Is it a PNG-24? As far as I believe that would only work with PNG-8. Maybe you could try to use Imagick</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a png with a transparent background. The foreground is a single color. I want to change this single color while preserving the 100% alpha background.

The code below doesn't work, it worked when I had a gif. However, when I changed the gif to a png then added the alpha stuff the color change broke down.

If I add imagetruecolortopalette($im, false, 255); the color is changed but alpha is lost.

Can someone show me where I am going wrong please

$imgname = "block.png";
$im = imagecreatefrompng($imgname);
imagealphablending($im, false);

$index = imagecolorclosest ($im, 153,153,153); // get Grey COlor
imagecolorset($im,$index,0,0,0); // SET NEW COLOR

imageAlphaBlending($im, true);
imageSaveAlpha($im, true);
$imgname = "result.png";
imagepng($im, $imgname ); // save image as gif
imagedestroy($im);

EDIT :: This is a simple enough script.

When I used a gif, the color changed and the new image was saved. When a changed to a .png. The color no longer changed and thus the original image passes through the script unchanged.


问:
How to reinit bean object in previously autowired objects?
I need to reinit singleton bean instance for all previously autowired fields.

I tried to remove the bean from registy in app context, and re-register new object.

```<code>ConfigurableApplicationContext configContext = (ConfigurableApplicationContext)appContext;
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();
((DefaultListableBeanFactory) beanRegistry).destroySingleton("fbdProg");
((DefaultListableBeanFactory) beanRegistry).registerSingleton("fbdProg", program);
</code>```

It works only once, the first time it is called.

The issue is how to reinit the bean to make new instance available in other classes, where it is autowired

答:
Every class with a @Bean annotation is a singleton by default in spring boot, but you can provide a @Scope annotation if you want that the lifehook of a variable to be related to

a session

an http request

the lifehook of a serveletContext

anyway you have to keep in mind that @Bean should be singleton, for example in the persistence pattern you have an entity and a repository. The respository should be a singletone because it essentialy gives only methods to store and retrieve entities, while an entity should not be a singletone because you need an entity for every object you have to store in a database. The same for services. You may also want to taake a look at this article: spring boot scopes

Body:
I need to reinit singleton bean instance for all previously autowired fields.

I tried to remove the bean from registy in app context, and re-register new object.

ConfigurableApplicationContext configContext = (ConfigurableApplicationContext)appContext;
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();
((DefaultListableBeanFactory) beanRegistry).destroySingleton("fbdProg");
((DefaultListableBeanFactory) beanRegistry).registerSingleton("fbdProg", program);

It works only once, the first time it is called.

The issue is how to reinit the bean to make new instance available in other classes, where it is autowired


问:
How can I use a google classroom API on a website I am making to access specific rosters and put them on a list displayed on the website?
I am making a website for a teacher and he wants to be able to take attendance easily and he wants me to use the google classroom api to access his roster in his class so that it can then display that list of names on the website and he can easily take attendance there</p>

答:
The best thing to start with is to navigate in the official documentation for Classroom API.

The Classroom API provides a RESTful interface for you to manage
  courses and rosters in Google Classroom.

For python, you can refer to the quickstart guide designed for Python implementation. See sample code.

To access students, use REST Resource: courses.students.

You will be able to use the supported methods such as create, delete, get and list.


问:
Should this request be GET or POST?
My API accepts 2 parameters, product and quantity, and it returns a price.

At the moment this is a 'GET' request, which makes sense. But there are now new requirements to log every price that is returned in an audit table. This now feels like a POST?

Question

What is/where can I find the criteria for determining whether a request should be made as GET or POST?

答:
GET -  It perform when you first time enter to page

POST - It perform when you make some actions(for example you will change data) on the page and after that you reload it

Title: Should this request be GET or POST?


问:
STM32 Serial DMA - Finding the beginning of the Stream
I have a known serial stream format that I am capturing via the DMA. It has header and footer bytes. But sometimes the MCU starts capturing in the middle of the stream and then the sync is out because the DMA is looking for a set number of bytes. I have read of people using circular buffers, but I have struggled to grasp this concept.

Instead, I was thinking of disabling the DMA and enabling the a serial interrupt at the start up of the MCU. Then cycle through each byte that is captured by the interrupt to find the start byte. Then, once I have found the start byte, disable the serial interrupt capturing and enable the DMA to take over the capturing of the stream.

Does this sound feasible? Thanks for any input.

I am using STM32 HAL libs with the new STM32 IDE that includes STM32 CubeMX.

答:
As the protocol has idle gaps between packets, you can use the idle interrupt feature of the UART to synchronize the receiver.

Enable the UART interrupt, simply start receiving with DMA, and set UARTx->CR1 |= USART_CR1_IDLEIE. Whenever the idle interrupt is triggered, look at the DMA channel, if it's still running, stop the transfer and discard the input buffer (as this means that the receive was started in the middle of the packet) and start receiving the next packet.


问:
What does "Content-type: application/json; charset=utf-8" really mean?
When I make a POST request with a JSON body to my REST service I include Content-type: application/json; charset=utf-8 in the message header. Without this header, I get an error from the service. I can also successfully use Content-type: application/json without the ;charset=utf-8 portion.

What exactly does charset=utf-8 do ? I know it specifies the character encoding but the service works fine without it. Does this encoding limit the characters that can be in the message body?

答:
I exactly agree with @deceze but I want to develop this "I get an error from the service" part of the question,

We getting this kind of errors as http 415

Http 415 Unsupported Media type error

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.

The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.

In other words, such is seen in this example.

We have to set the correct content type and we have to accept the right content type
as seen Add Content-Type: application/json and Accept: application/json. Otherwise, it will assume the default


问:
how to run a logrotate hourly
I created a program.conf that logrotate my logs hourly in an EC2 instance. the logrotate works well when i force it command (by sudo logrotate program.conf --verbose --force) but it doesn't run each hour.

I tried several solutions by googling this problem like puting my program.conf in /etc/logrotate.d and moving logrotate from cron.dail into cron.hourly.
but it doesn't work.

Here is my program.conf :

```<code>/home/user_i/*.log{
hourly
missingok
dateext
rotate 1
compress
size 100M
sharedscripts
postrotate
    /usr/bin/bash file.sh
endscript
}
</code>```

Have you any idea please ?

Thanks

答:
You will need to add the job in your crontab

```<code>crontab -e
</code>```

And then add a job that runs every hour 14 minutes past,

```<code>14 * * * * /usr/sbin/logrotate /home/sammy/logrotate.conf --state /home/sammy/logrotate-state
</code>```

Taken from : https://www.digitalocean.com/community/tutorials/how-to-manage-logfiles-with-logrotate-on-ubuntu-16-04

Also additionally check if the crontab is actually running by doing

```<code>service crontab status
</code>```

if it is stopped you can start it by doing

```<code>service crontab start
</code>```

Title: how to run a logrotate hourly

Body:
I created a program.conf that logrotate my logs hourly in an EC2 instance. the logrotate works well when i force it command (by sudo logrotate program.conf --verbose --force) but it doesn't run each hour.

I tried several solutions by googling this problem like puting my program.conf in /etc/logrotate.d and moving logrotate from cron.dail into cron.hourly.
but it doesn't work.

Here is my program.conf :

/home/user_i/*.log{
hourly
missingok
dateext
rotate 1
compress
size 100M
sharedscripts
postrotate
    /usr/bin/bash file.sh
endscript
}

Have you any idea please ?

Thanks

Body:
You will need to add the job in your crontab

crontab -e

And then add a job that runs every hour 14 minutes past,

14 * * * * /usr/sbin/logrotate /home/sammy/logrotate.conf --state /home/sammy/logrotate-state

Taken from : https://www.digitalocean.com/community/tutorials/how-to-manage-logfiles-with-logrotate-on-ubuntu-16-04

Also additionally check if the crontab is actually running by doing

service crontab status

if it is stopped you can start it by doing

service crontab start


问:
How can you extract a integer number from a string in a function?
I want to input a string into a function and get the integer that's in it to compare the number with another expression. I've searched a lot but some don't work or give me this: ['6']. I can't compare that to a number so it can't work. Please Help.

```<code>{def numberC(card):
#numbers = []
#numbers.append(re.findall(\-?\d+, card))
#nums = re.compile(r"[+-]?\d+(?:\.\d+)?")
print(re.findall("\-?\d+", card))
return re.findall("\-?\d+", card)}
</code>```

That is the function I've made that doesn't work.

The string that goes into it looks like this "Red Card 10".

I then use this to compare them as a card battle.

```<code>{elif(card1 == card2):
    if(numberC(card1) < numberC(card2)):
        return "Player 2 is the Winner!"
    else:
        return "Player 1 is the Winner!"}
</code>```

The expected result is from "Red Card 10" I want just 10 that has a data type of an integer.

答:
Use re.search

Ex:

```<code>def numberC(card):
    return re.search("\-?(\d+)", card).group(1)
</code>```

Body:
I want to input a string into a function and get the integer that's in it to compare the number with another expression. I've searched a lot but some don't work or give me this: ['6']. I can't compare that to a number so it can't work. Please Help.

{def numberC(card):
#numbers = []
#numbers.append(re.findall(\-?\d+, card))
#nums = re.compile(r"[+-]?\d+(?:\.\d+)?")
print(re.findall("\-?\d+", card))
return re.findall("\-?\d+", card)}

That is the function I've made that doesn't work.

The string that goes into it looks like this "Red Card 10".

I then use this to compare them as a card battle.

{elif(card1 == card2):
    if(numberC(card1) < numberC(card2)):
        return "Player 2 is the Winner!"
    else:
        return "Player 1 is the Winner!"}

The expected result is from "Red Card 10" I want just 10 that has a data type of an integer.

Body:
Use re.search

Ex:

def numberC(card):
    return re.search("\-?(\d+)", card).group(1)


问:
Sql query in ASP.NET
I am using the following query to update record in asp.net, what's wrong with it?</p>

```<code>Dim updateSqlString As String = "UPDATE Subscriber_Communication SET([[marketing_rec_id]=?, [Currently_own]=?,[Purchase_date]=?, [Interested_in_owning]=?, [Product_of_interest]=?," & _
"[Time_frame_to_own]=?, [Referred_by]=?, [Campaign_Code]=?,[Last_Update]=?, [record_created_on]=?, [Comments]=?, [Comment_Date]=?, [Community_id]=?," & _
"[Certification]=?, [subscriber_Type]=?, [unsubscribe_comment]=?" & _
"WHERE [Communication_id]=" & Communication_id
  Using conn As New SqlConnection(ConnString)
            Using cmd As New SqlCommand(insertSqlString, conn)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("marketing_rec_id", marketing_rec_id)
                cmd.Parameters.AddWithValue("Currently_own", Currently_own)
                cmd.Parameters.AddWithValue("Purchase_date", Purchase_date)
                cmd.Parameters.AddWithValue("Interested_in_owning", Interested_in_owning)
                cmd.Parameters.AddWithValue("Product_of_interest", Product_of_interest)
                cmd.Parameters.AddWithValue("Time_frame_to_own", Time_frame_to_own)
                cmd.Parameters.AddWithValue("Referred_by", Referred_by)
                cmd.Parameters.AddWithValue("Campaign_Code", Campaign_Code)
                cmd.Parameters.AddWithValue("Last_Update", Last_Update)
                cmd.Parameters.AddWithValue("record_created_on", record_created_on)
                cmd.Parameters.AddWithValue("Comments", Comments)
                cmd.Parameters.AddWithValue("Comment_Date", Comment_Date)
                cmd.Parameters.AddWithValue("Community_id", Community_id)
                cmd.Parameters.AddWithValue("Certification", Certification)
                cmd.Parameters.AddWithValue("subscriber_Type", subscriber_Type)
                cmd.Parameters.AddWithValue("unsubscribe_comment", unsubscribe_comment)
                conn.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using
</code>```

答:
You have the string variable as

updateSqlString

while you are using

insertSqlString

to update the database .

Title: Sql query in ASP.NET

Body:
I am using the following query to update record in asp.net, what's wrong with it?

Dim updateSqlString As String = "UPDATE Subscriber_Communication SET([[marketing_rec_id]=?, [Currently_own]=?,[Purchase_date]=?, [Interested_in_owning]=?, [Product_of_interest]=?," & _
"[Time_frame_to_own]=?, [Referred_by]=?, [Campaign_Code]=?,[Last_Update]=?, [record_created_on]=?, [Comments]=?, [Comment_Date]=?, [Community_id]=?," & _
"[Certification]=?, [subscriber_Type]=?, [unsubscribe_comment]=?" & _
"WHERE [Communication_id]=" & Communication_id
  Using conn As New SqlConnection(ConnString)
            Using cmd As New SqlCommand(insertSqlString, conn)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("marketing_rec_id", marketing_rec_id)
                cmd.Parameters.AddWithValue("Currently_own", Currently_own)
                cmd.Parameters.AddWithValue("Purchase_date", Purchase_date)
                cmd.Parameters.AddWithValue("Interested_in_owning", Interested_in_owning)
                cmd.Parameters.AddWithValue("Product_of_interest", Product_of_interest)
                cmd.Parameters.AddWithValue("Time_frame_to_own", Time_frame_to_own)
                cmd.Parameters.AddWithValue("Referred_by", Referred_by)
                cmd.Parameters.AddWithValue("Campaign_Code", Campaign_Code)
                cmd.Parameters.AddWithValue("Last_Update", Last_Update)
                cmd.Parameters.AddWithValue("record_created_on", record_created_on)
                cmd.Parameters.AddWithValue("Comments", Comments)
                cmd.Parameters.AddWithValue("Comment_Date", Comment_Date)
                cmd.Parameters.AddWithValue("Community_id", Community_id)
                cmd.Parameters.AddWithValue("Certification", Certification)
                cmd.Parameters.AddWithValue("subscriber_Type", subscriber_Type)
                cmd.Parameters.AddWithValue("unsubscribe_comment", unsubscribe_comment)
                conn.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using


问:
Django: put offline a post after an event
I'm trying to put offline the posts after an event, a definite date. I've developed a simple model for test my aim and inside the model I've put a function(named is_expired) that, ideally, must define if a post is or not is online. Below there is the model:

```<code>from django.db import models
from django.utils import timezone
import datetime

class BlogPost(models.Model):
    CHOICHES = (
        ("Unselected", "Unselected"),
        ("One Month", "One Month"),
        ("One Year", "One Year"),
        )

    title = models.CharField(
        max_length=70,
        unique=True,
        )
    membership = models.CharField(
        max_length=50,
        choices=CHOICHES,
        default="Unselected",
        )
    publishing_date = models.DateTimeField(
                        default=timezone.now,
                        )

    def __str__(self):
        return self.title

    @property
    def is_future(self):
        if self.publishing_date > datetime.datetime.now():
            return True
        return False

    @property
    def is_expired(self):
        if self.membership == "One Month":
            def monthly(self):
                if publishing_date + datetime.timedelta(days=30) <= datetime.datetime.now():
                    return True
        if self.membership == "One Year":
            def yearly(self):
                if publishing_date + datetime.timedelta(days=365) <= datetime.datetime.now():
                    return True
        return False

    class Meta:
        ordering = ['-publishing_date']
</code>```

For show a list of all expired posts I use this simple template:

```<code>{% for p in posts_list %}
  {% if p.is_future or p.is_expired %}
  <div class="container my-4 bg-primary">
    <h3><a class="text-white" href="{{ p.get_absolute_url }}">{{ p.title }}</a></h3>
    <h5>Data di pubblicazione: {{ p.publishing_date|date:"d - M - Y | G:i:s" }}</h5>
    {% if p.is_expired %}
      <p>Expired? <span class="text-danger"><strong>Yes</strong></span></p>
    {% else %}
      <p>Expired? <span class="text-success"><strong>No</strong></span></p>
    {% endif %}
  </div>
  {% endif %}
{% empty %}
  <div class="container my-4 bg-primary">
    <h1>No posts!</h1>
  </div>
{% endfor %}
</code>```

The problem is that I don't see the expired posts but only the future posts(with function named is_future), inside the console there are no errors and then I don't now where is the error.
I'm newbie whit use of Python and Django.

Someone can indicate to me the error?

UPDATE:

views.py

```<code>def listPosts(request):
    posts_list = BlogPost.objects.all()
    context = {"posts_list": posts_list}
    template = 'blog/reading/list_post.html'
    return render(request, template, context)
</code>```

答:
Your is_expired() method always returns False. Inside the method, you define two inner function (monthly and yearly) but never call them. Those inner functions are actually useless, you want:

```<code>@property
def is_expired(self):
    if self.membership == "One Month":
        if self.publishing_date + datetime.timedelta(days=30) <= datetime.datetime.now():
            return True
    elif self.membership == "One Year":
        if self.publishing_date + datetime.timedelta(days=365) <= datetime.datetime.now():
            return True
    return False
</code>```

Body:
I'm trying to put offline the posts after an event, a definite date. I've developed a simple model for test my aim and inside the model I've put a function(named is_expired) that, ideally, must define if a post is or not is online. Below there is the model:

from django.db import models
from django.utils import timezone
import datetime

class BlogPost(models.Model):
    CHOICHES = (
        ("Unselected", "Unselected"),
        ("One Month", "One Month"),
        ("One Year", "One Year"),
        )

    title = models.CharField(
        max_length=70,
        unique=True,
        )
    membership = models.CharField(
        max_length=50,
        choices=CHOICHES,
        default="Unselected",
        )
    publishing_date = models.DateTimeField(
                        default=timezone.now,
                        )

    def __str__(self):
        return self.title

    @property
    def is_future(self):
        if self.publishing_date > datetime.datetime.now():
            return True
        return False

    @property
    def is_expired(self):
        if self.membership == "One Month":
            def monthly(self):
                if publishing_date + datetime.timedelta(days=30) <= datetime.datetime.now():
                    return True
        if self.membership == "One Year":
            def yearly(self):
                if publishing_date + datetime.timedelta(days=365) <= datetime.datetime.now():
                    return True
        return False

    class Meta:
        ordering = ['-publishing_date']

For show a list of all expired posts I use this simple template:

{% for p in posts_list %}
  {% if p.is_future or p.is_expired %}

{{ p.title }}

Data di pubblicazione: {{ p.publishing_date|date:"d - M - Y | G:i:s" }}

    {% if p.is_expired %}

Expired? Yes

    {% else %}

Expired? No

    {% endif %}

  {% endif %}
{% empty %}

No posts!

{% endfor %}

The problem is that I don't see the expired posts but only the future posts(with function named is_future), inside the console there are no errors and then I don't now where is the error.
I'm newbie whit use of Python and Django.

Someone can indicate to me the error?

UPDATE:

views.py

def listPosts(request):
    posts_list = BlogPost.objects.all()
    context = {"posts_list": posts_list}
    template = 'blog/reading/list_post.html'
    return render(request, template, context)

Body:
Your is_expired() method always returns False. Inside the method, you define two inner function (monthly and yearly) but never call them. Those inner functions are actually useless, you want:

@property
def is_expired(self):
    if self.membership == "One Month":
        if self.publishing_date + datetime.timedelta(days=30) <= datetime.datetime.now():
            return True
    elif self.membership == "One Year":
        if self.publishing_date + datetime.timedelta(days=365) <= datetime.datetime.now():
            return True
    return False


问:
How to get lat/lng coordinates from VisibleRegion using Apple MapKit?
I need upperRight and bottomLeft coordinates of the visible mapView.

In mapViewDidChangeVisibleRegion I get the values.

```<code>class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!

    var currentLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView.delegate = self

        self.customizeMapView()

        currentLocation =  CLLocation(latitude: ( 37.334922), longitude: (-122.009033))

        self.centerMapOnLocation()

   }

    func customizeMapView(){
        self.mapView.showsBuildings = true
        self.mapView.showsCompass = true
        self.mapView.showsPointsOfInterest = true
        self.mapView.showsUserLocation = false
        self.mapView.userTrackingMode = .none
        self.mapView.showsZoomControls = true
        self.mapView.mapType = .satelliteFlyover
    }

    func centerMapOnLocation(){

        let centerRegionCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)

        let spanRegion:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.0025, longitudeDelta: 0.0025)
        let mapRegion: MKCoordinateRegion = MKCoordinateRegion(center: centerRegionCoordinate, span: spanRegion)
        mapView.setRegion(mapRegion, animated: true)

    }

    func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
        print("mapViewDidChangeVisibleRegion")
       /*
         0,0         +x

         +y

        */
        let upperRight = mapView.convert(CGPoint(x: self.view.frame.size.width, y: 0.0), toCoordinateFrom: self.view)
        let bottomLeft = mapView.convert(CGPoint(x: 0.0, y: self.view.frame.size.height), toCoordinateFrom: self.view)

        print("upperRight: \(upperRight) ")
        print("bottomLeft: \(bottomLeft) ")

    }
</code>```

I expect the coordinated to be correct but I'm getting -180.0.

These are the values I get when initially running the App:

```<code>upperRight: CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)
bottomLeft: CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)
</code>```

Moving the map horizontally with a gesture:

```<code>upperRight: CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)
bottomLeft: CLLocationCoordinate2D(latitude: 37.33245941071868, longitude: -122.01073312548439)
</code>```

Moving the map vertically with a gesture:

```<code>upperRight: CLLocationCoordinate2D(latitude: 37.33687329393082, longitude: -122.00780068382419)
bottomLeft: CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)
</code>```

Moving the map  diagonally with gesture:

```<code>upperRight: CLLocationCoordinate2D(latitude: 37.336306795130724, longitude: -122.00839348216184)
bottomLeft: CLLocationCoordinate2D(latitude: 37.33126864523067, longitude: -122.01130820828396)
</code>```

How to perform mapView.convert correctly?

答:
Instead of calculating mapView frame to determine coordinates, I would prefer to use MKCoordinateRegion to get the bounding-box coordinates, like so:

```<code>extension MKCoordinateRegion {

    var boundingBoxCoordinates: [CLLocationCoordinate2D] {
        let halfLatDelta = self.span.latitudeDelta / 2
        let halfLngDelta = self.span.longitudeDelta / 2

        let topLeft = CLLocationCoordinate2D(
            latitude: self.center.latitude + halfLatDelta,
            longitude: self.center.longitude - halfLngDelta
        )
        let bottomRight = CLLocationCoordinate2D(
            latitude: self.center.latitude - halfLatDelta,
            longitude: self.center.longitude + halfLngDelta
        )
        let bottomLeft = CLLocationCoordinate2D(
            latitude: self.center.latitude - halfLatDelta,
            longitude: self.center.longitude - halfLngDelta
        )
        let topRight = CLLocationCoordinate2D(
            latitude: self.center.latitude + halfLatDelta,
            longitude: self.center.longitude + halfLngDelta
        )

        return [topLeft, topRight, bottomRight, bottomLeft]
    }

}
</code>```

Usage: Showing annotations on MKMapView at top-left, top-right, bottom-right, bottom-left

```<code>class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet var mapView: MKMapView!

    private let annotations: [MKPointAnnotation] = [MKPointAnnotation(), MKPointAnnotation(), MKPointAnnotation(), MKPointAnnotation()]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView.addAnnotations(annotations)

        let currentLocationCoordinate = CLLocationCoordinate2D(latitude: 37.334922, longitude: -122.009033)
        let spanRegion = MKCoordinateSpan(latitudeDelta: 0.0025, longitudeDelta: 0.0025)
        let mapRegion = MKCoordinateRegion(center: currentLocationCoordinate, span: spanRegion)
        mapView.setRegion(mapRegion, animated: true)
    }

    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        let bounds = mapView.region.boundingBoxCoordinates
        print("TopLeft: \(bounds[0])\nTopRight: \(bounds[1])\nBottomRight: \(bounds[2])\nBottomLeft: \(bounds[3])")
        for (i, coordinate) in bounds.enumerated() {
            self.annotations[i].coordinate = coordinate
        }
    }

}
</code>```

That yields

Body:
I need upperRight and bottomLeft coordinates of the visible mapView.

In mapViewDidChangeVisibleRegion I get the values.

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!

    var currentLocation: CLLocation!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView.delegate = self

        self.customizeMapView()

        currentLocation =  CLLocation(latitude: ( 37.334922), longitude: (-122.009033))

        self.centerMapOnLocation()

   }

    func customizeMapView(){
        self.mapView.showsBuildings = true
        self.mapView.showsCompass = true
        self.mapView.showsPointsOfInterest = true
        self.mapView.showsUserLocation = false
        self.mapView.userTrackingMode = .none
        self.mapView.showsZoomControls = true
        self.mapView.mapType = .satelliteFlyover
    }

    func centerMapOnLocation(){

        let centerRegionCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)

        let spanRegion:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.0025, longitudeDelta: 0.0025)
        let mapRegion: MKCoordinateRegion = MKCoordinateRegion(center: centerRegionCoordinate, span: spanRegion)
        mapView.setRegion(mapRegion, animated: true)

    }

    func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
        print("mapViewDidChangeVisibleRegion")
       /*
         0,0         +x

         +y

        */
        let upperRight = mapView.convert(CGPoint(x: self.view.frame.size.width, y: 0.0), toCoordinateFrom: self.view)
        let bottomLeft = mapView.convert(CGPoint(x: 0.0, y: self.view.frame.size.height), toCoordinateFrom: self.view)

        print("upperRight: \(upperRight) ")
        print("bottomLeft: \(bottomLeft) ")

    }

I expect the coordinated to be correct but I'm getting -180.0.

These are the values I get when initially running the App:

upperRight: CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)
bottomLeft: CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)

Moving the map horizontally with a gesture:

upperRight: CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)
bottomLeft: CLLocationCoordinate2D(latitude: 37.33245941071868, longitude: -122.01073312548439)

Moving the map vertically with a gesture:

upperRight: CLLocationCoordinate2D(latitude: 37.33687329393082, longitude: -122.00780068382419)
bottomLeft: CLLocationCoordinate2D(latitude: -180.0, longitude: -180.0)

Moving the map  diagonally with gesture:

upperRight: CLLocationCoordinate2D(latitude: 37.336306795130724, longitude: -122.00839348216184)
bottomLeft: CLLocationCoordinate2D(latitude: 37.33126864523067, longitude: -122.01130820828396)

How to perform mapView.convert correctly?

Body:
Instead of calculating mapView frame to determine coordinates, I would prefer to use MKCoordinateRegion to get the bounding-box coordinates, like so:

extension MKCoordinateRegion {

    var boundingBoxCoordinates: [CLLocationCoordinate2D] {
        let halfLatDelta = self.span.latitudeDelta / 2
        let halfLngDelta = self.span.longitudeDelta / 2

        let topLeft = CLLocationCoordinate2D(
            latitude: self.center.latitude + halfLatDelta,
            longitude: self.center.longitude - halfLngDelta
        )
        let bottomRight = CLLocationCoordinate2D(
            latitude: self.center.latitude - halfLatDelta,
            longitude: self.center.longitude + halfLngDelta
        )
        let bottomLeft = CLLocationCoordinate2D(
            latitude: self.center.latitude - halfLatDelta,
            longitude: self.center.longitude - halfLngDelta
        )
        let topRight = CLLocationCoordinate2D(
            latitude: self.center.latitude + halfLatDelta,
            longitude: self.center.longitude + halfLngDelta
        )

        return [topLeft, topRight, bottomRight, bottomLeft]
    }

}

Usage: Showing annotations on MKMapView at top-left, top-right, bottom-right, bottom-left

class ViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet var mapView: MKMapView!

    private let annotations: [MKPointAnnotation] = [MKPointAnnotation(), MKPointAnnotation(), MKPointAnnotation(), MKPointAnnotation()]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.mapView.addAnnotations(annotations)

        let currentLocationCoordinate = CLLocationCoordinate2D(latitude: 37.334922, longitude: -122.009033)
        let spanRegion = MKCoordinateSpan(latitudeDelta: 0.0025, longitudeDelta: 0.0025)
        let mapRegion = MKCoordinateRegion(center: currentLocationCoordinate, span: spanRegion)
        mapView.setRegion(mapRegion, animated: true)
    }

    func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
        let bounds = mapView.region.boundingBoxCoordinates
        print("TopLeft: \(bounds[0])\nTopRight: \(bounds[1])\nBottomRight: \(bounds[2])\nBottomLeft: \(bounds[3])")
        for (i, coordinate) in bounds.enumerated() {
            self.annotations[i].coordinate = coordinate
        }
    }

}

That yields


问:
Unknown column 'email' in 'field list'
I am building a user registration and authentication system in nodejs. When I try to encrypt the password of the user and store it into my sql user database, it gives an error.

The implementation for registration controller is as follows:

```<code>var express=require("express");
var connection = require('./../config');
const bcrypt = require('bcrypt')

module.exports.register=function(req,res){
    var today = new Date();
    var encryptedString = bcrypt.hashSync(req.body.password, 5);
    var user={
        "userid":req.body.userid,
        "password":encryptedString,
        "clientid":req.body.clientid,
        "email":req.body.email
    }
    connection.query('INSERT INTO user SET ?',user, function (error, results, fields) {
      if (error) {
        res.json({
            status:false,
            message:'query error'
        })
      }else{
          res.json({
            status:true,
            data:results,
            message:'user registered sucessfully'
        })
      }
    });
}
</code>```

The user table has the following structure

```<code>CREATE TABLE `user`(
`userid` varchar(25) NOT NULL,
`password` varchar(60) NOT NULL,
`clientid` varchar(25) NOT NULL,
PRIMARY KEY (`userid`),
CONSTRAINT `user_ibfk_1` FOREIGN KEY (`clientid`) REFERENCES `client`(`clientid`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

Without the password encryption, the user is stored successfully with the password being plaintext. Why does this issue occur upon encrypting the password?

Any help clarifying this would be appreciated.

This is the result for console.log(error):

```<code>code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sqlMessage: "Unknown column 'email' in 'field list'",
  sqlState: '42S22',
  index: 0,
  sql: "INSERT INTO user SET `userid` = '1', `password` = " +
    "'$2b$05$0D2eG3Jp.UhlYs.pbtYip.yMrCYkjhHiVZC3WwrtmKJG4pyRKZDae', " +
    "`clientid` = '1', `email` = 'abc@xyz.com'"
}
</code>```

答:
Unknown column 'email' in 'field list'

It is self explainatory. You have no email column in your table which confirms DDL you have provided.

```<code>`userid` varchar(25) NOT NULL,
`password` varchar(60) NOT NULL,
`clientid` varchar(25) NOT NULL,
</code>```

no email

while you are sending it trough user

```<code>var user={
    "userid":req.body.userid,
    "password":encryptedString,
    "clientid":req.body.clientid,
    "email":req.body.email
}
</code>```

Title: Unknown column 'email' in 'field list'

Body:
I am building a user registration and authentication system in nodejs. When I try to encrypt the password of the user and store it into my sql user database, it gives an error.

The implementation for registration controller is as follows:

var express=require("express");
var connection = require('./../config');
const bcrypt = require('bcrypt')

module.exports.register=function(req,res){
    var today = new Date();
    var encryptedString = bcrypt.hashSync(req.body.password, 5);
    var user={
        "userid":req.body.userid,
        "password":encryptedString,
        "clientid":req.body.clientid,
        "email":req.body.email
    }
    connection.query('INSERT INTO user SET ?',user, function (error, results, fields) {
      if (error) {
        res.json({
            status:false,
            message:'query error'
        })
      }else{
          res.json({
            status:true,
            data:results,
            message:'user registered sucessfully'
        })
      }
    });
}

The user table has the following structure

CREATE TABLE `user`(
`userid` varchar(25) NOT NULL,
`password` varchar(60) NOT NULL,
`clientid` varchar(25) NOT NULL,
PRIMARY KEY (`userid`),
CONSTRAINT `user_ibfk_1` FOREIGN KEY (`clientid`) REFERENCES `client`(`clientid`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Without the password encryption, the user is stored successfully with the password being plaintext. Why does this issue occur upon encrypting the password?

Any help clarifying this would be appreciated.

This is the result for console.log(error):

code: 'ER_BAD_FIELD_ERROR',
  errno: 1054,
  sqlMessage: "Unknown column 'email' in 'field list'",
  sqlState: '42S22',
  index: 0,
  sql: "INSERT INTO user SET `userid` = '1', `password` = " +
    "'$2b$05$0D2eG3Jp.UhlYs.pbtYip.yMrCYkjhHiVZC3WwrtmKJG4pyRKZDae', " +
    "`clientid` = '1', `email` = 'abc@xyz.com'"
}

Body:
Unknown column 'email' in 'field list'

It is self explainatory. You have no email column in your table which confirms DDL you have provided.

`userid` varchar(25) NOT NULL,
`password` varchar(60) NOT NULL,
`clientid` varchar(25) NOT NULL,

no email

while you are sending it trough user

var user={
    "userid":req.body.userid,
    "password":encryptedString,
    "clientid":req.body.clientid,
    "email":req.body.email
}


问:
iPhone: How to programmatically convert String entered by user into Init caps?
I have a textbox where in user enters the string.

I want to programmatically convert this string to init caps.

How can I do that?

答:
Try using this UITextAutocapitalizationTypeWords or UITextAutocapitalizationTypeAllCharacters

UPDATE

capitalizedString or upperCaseString will help you

[textField.text uppercaseString]; will give you all the characters in textfield as capital letters


问:
TransmitFile yielding a corrupt files with wrong filesize
I have the following method available to download a file when a page is visited. The issue have is that it seems to yield files with added bytes back, that based on the type of file can make it corrupt. I have the following method:

```<code>Public Class GetImage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'snipped unimportant code
        Dim fileSize = New FileInfo(filepath).Length
        Response.Clear()
        Response.AddHeader("content-length", fileSize.ToString())
        Response.ContentType = "application/octet-stream"
        Response.AppendHeader("content-disposition", "attachment; filename=" & DisplayName)
        Response.TransmitFile(filepath)
    End Sub
End Class
</code>```

For an example when an xlsm file with the size 177030 is downloaded using the above method the downloaded file has a size of 177710 and becomes corrupt (but repairable) in Excel. It always seems to add 680 bytes.

I've tried substituting TransmitFile with WriteFile. Setting the length in TransmitFile to the actual filesize that is correctly retrieved from FileInfo. I've also looked at different files and I've tried running it both locally on server and locally; all with the same results.

答: It was missing Response.Flush() at the end of the method

Body:
I have the following method available to download a file when a page is visited. The issue have is that it seems to yield files with added bytes back, that based on the type of file can make it corrupt. I have the following method:

Public Class GetImage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'snipped unimportant code
        Dim fileSize = New FileInfo(filepath).Length
        Response.Clear()
        Response.AddHeader("content-length", fileSize.ToString())
        Response.ContentType = "application/octet-stream"
        Response.AppendHeader("content-disposition", "attachment; filename=" & DisplayName)
        Response.TransmitFile(filepath)
    End Sub
End Class

For an example when an xlsm file with the size 177030 is downloaded using the above method the downloaded file has a size of 177710 and becomes corrupt (but repairable) in Excel. It always seems to add 680 bytes.

I've tried substituting TransmitFile with WriteFile. Setting the length in TransmitFile to the actual filesize that is correctly retrieved from FileInfo. I've also looked at different files and I've tried running it both locally on server and locally; all with the same results.


问:
Always enter credentials without "prompt=login" in IdentityServer4
This is similar to IdentityServer4 Force User to re-enter credentials, but the solution there says to use prompt=login query string in the /authorize URL, which works, but also allows for sneaky users to remove it. Also, seeing as I'm not using .AddOpenIdConnect() the suggestion to use OnRedirectToIdentityProvider doesn't apply to me.

So how can we force the user to always enter credentials without relying on the prompt=login in the query string?

Here's my basic IdentityServer4 setup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var builder = services.AddIdentityServer()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApis())
        .AddInMemoryClients(Config.GetClients());

    builder.AddDeveloperSigningCredential();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseFileServer();
    app.UseIdentityServer();
    app.UseMvc();
}
```

<p>Where my login page only has an "OK" and "Cancel" button (I don't care which user logs on yet, only that authentication was OK or not), and the controller does the following when it is authenticating the user:</p>

<pre class="lang-cs prettyprint-override"><code>public async Task<IActionResult> Post(AuthenticateViewModel model, string button)
{
    var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

    if (button == "authCancel")
    {
        if (context != null)
        {
            await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);
            return Redirect(model.ReturnUrl);
        }

        return Redirect("~/");
    }

    if (button == "authOk" && ModelState.IsValid)
    {
        if (context != null)
        {
            await _events.RaiseAsync(new UserLoginSuccessEvent("provider", "userId", "subjectId", "name"));
            await HttpContext.SignInAsync("subject", "name", new AuthenticationProperties());
            return Redirect(model.ReturnUrl);
        }
    }

    return Redirect("~/");
}
</code>```

答:
An option could be to stick to prompt=login for all requests or based on  some client setting, or a http header.

It is easy to look into the default request validator and implement your customization like the following:

public class YourCustomAuthorizeRequestValidator:ICustomAuthorizeRequestValidator
{
  public Task ValidateAsync(CustomAuthorizeRequestValidationContext context)
  {
    var request = context.Result.ValidatedRequest;
    if (string.IsNullOrWhiteSpace(request.Raw["prompted"]))
    {
      request.Raw.Add("prompted", "true");
      request.PromptMode = OidcConstants.PromptModes.Login;
    }
    else if (request.Subject.IsAuthenticated())
    {
      request.PromptMode = OidcConstants.PromptModes.None;
    }
    return Task.CompletedTask;
  }
}
```

<p>and then in your Identityserver startup:</p>

<pre class="lang-cs prettyprint-override"><code>services.AddIdentityServer()
  .AddCustomAuthorizeRequestValidator<YourCustomAuthorizeRequestValidator>();
</code>```

Body:
This is similar to IdentityServer4 Force User to re-enter credentials, but the solution there says to use prompt=login query string in the /authorize URL, which works, but also allows for sneaky users to remove it. Also, seeing as I'm not using .AddOpenIdConnect() the suggestion to use OnRedirectToIdentityProvider doesn't apply to me.

So how can we force the user to always enter credentials without relying on the prompt=login in the query string?

Here's my basic IdentityServer4 setup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var builder = services.AddIdentityServer()
        .AddInMemoryIdentityResources(Config.GetIdentityResources())
        .AddInMemoryApiResources(Config.GetApis())
        .AddInMemoryClients(Config.GetClients());

    builder.AddDeveloperSigningCredential();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseHttpsRedirection();
    app.UseFileServer();
    app.UseIdentityServer();
    app.UseMvc();
}

Where my login page only has an "OK" and "Cancel" button (I don't care which user logs on yet, only that authentication was OK or not), and the controller does the following when it is authenticating the user:

public async Task<IActionResult> Post(AuthenticateViewModel model, string button)
{
    var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

    if (button == "authCancel")
    {
        if (context != null)
        {
            await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);
            return Redirect(model.ReturnUrl);
        }

        return Redirect("~/");
    }

    if (button == "authOk" && ModelState.IsValid)
    {
        if (context != null)
        {
            await _events.RaiseAsync(new UserLoginSuccessEvent("provider", "userId", "subjectId", "name"));
            await HttpContext.SignInAsync("subject", "name", new AuthenticationProperties());
            return Redirect(model.ReturnUrl);
        }
    }

    return Redirect("~/");
}

Body:
An option could be to stick to prompt=login for all requests or based on  some client setting, or a http header.

It is easy to look into the default request validator and implement your customization like the following:

public class YourCustomAuthorizeRequestValidator:ICustomAuthorizeRequestValidator
{
  public Task ValidateAsync(CustomAuthorizeRequestValidationContext context)
  {
    var request = context.Result.ValidatedRequest;
    if (string.IsNullOrWhiteSpace(request.Raw["prompted"]))
    {
      request.Raw.Add("prompted", "true");
      request.PromptMode = OidcConstants.PromptModes.Login;
    }
    else if (request.Subject.IsAuthenticated())
    {
      request.PromptMode = OidcConstants.PromptModes.None;
    }
    return Task.CompletedTask;
  }
}

and then in your Identityserver startup:

services.AddIdentityServer()
  .AddCustomAuthorizeRequestValidator<YourCustomAuthorizeRequestValidator>();


问:
Student grading program (I am a beginner)
The program was running properly and now it not running anymore.

I wrote the code in Visual Studio first and the question is from Hackerrank.com, so the compiler from Hackerrank does not want to run this code:

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {
    /*
     * Complete the gradingStudents function below.
     */
    static int[] gradingStudents(int[] grades) {
       int fail = 40;

       for (int i = 0; i < grades.Length; i++)
       {
           if (grades[i] < fail)
           {
               double failcheck = Math.Round((double)grades[i] / 5, MidpointRounding.AwayFromZero) * 5;

               if (failcheck < fail)
               {
                   Console.WriteLine(grades[i]);
               }
               else
               {
                   Console.WriteLine(failcheck);
               }
           }
        }

        return grades;
    }

    static void Main(string[] args) {
        TextWriter tw = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int n = Convert.ToInt32(Console.ReadLine());
 grades = new int [n];

        for (int gradesItr = 0; gradesItr < n; gradesItr++) {
            int gradesItem = Convert.ToInt32(Console.ReadLine());
            grades[gradesItr] = gradesItem;
        }

        int[] result = gradingStudents(grades);

        tw.WriteLine(string.Join("\n", result));

        tw.Flush();
        tw.Close();
    }
}
</code>```

Sample Input 0

```<code>4
73
67
38
33
</code>```

Sample Output 0

```<code>75
67
40
33
</code>```

答:
If your problem is this ,
Then based on hackerrank problem description you should change method gradingStudents as:

static int[] gradingStudents(int[] grades)
{
    for (int i = 0; i < grades.Length; i++)
    {
        var item = grades[i];
        if (item >= 38)
        {
            var diff = 5 - (item % 5);
            if (diff < 3)
                grades[i] = item + diff;
        }
    }

    return grades;
}
```

Body:
The program was running properly and now it not running anymore.

I wrote the code in Visual Studio first and the question is from Hackerrank.com, so the compiler from Hackerrank does not want to run this code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {
    /*
     * Complete the gradingStudents function below.
     */
    static int[] gradingStudents(int[] grades) {
       int fail = 40;

       for (int i = 0; i < grades.Length; i++)
       {
           if (grades[i] < fail)
           {
               double failcheck = Math.Round((double)grades[i] / 5, MidpointRounding.AwayFromZero) * 5;

               if (failcheck < fail)
               {
                   Console.WriteLine(grades[i]);
               }
               else
               {
                   Console.WriteLine(failcheck);
               }
           }
        }

        return grades;
    }

    static void Main(string[] args) {
        TextWriter tw = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int n = Convert.ToInt32(Console.ReadLine());
 grades = new int [n];

        for (int gradesItr = 0; gradesItr < n; gradesItr++) {
            int gradesItem = Convert.ToInt32(Console.ReadLine());
            grades[gradesItr] = gradesItem;
        }

        int[] result = gradingStudents(grades);

        tw.WriteLine(string.Join("\n", result));

        tw.Flush();
        tw.Close();
    }
}

Sample Input 0

4
73
67
38
33

Sample Output 0

75
67
40
33


问:
C++ Matrix Class - Suggestions
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

```<code>template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix<U>&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix<U>&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}
</code>```

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.

答:
You might want to make r, c and mat members private.

Your streaming operators are not symmetric (operator<< doesn't write out r and c).

Title: C++ Matrix Class - Suggestions

Body:
I am trying to build a templated Matrix class in C++. Below is its implementation.
I implemented two operators +,+= as of now just to give an idea on how it will look and I thought it would be best to ask for feedback before I proceed any further.

The whole implementation is public and also there are no explicit bound/error checks, this is because its not meant to be a full fledged matrix library and hence avoided unnecessary code.

It would be very helpful if someone could comment on it and may be suggest a few improvements or suggestions.

Thank you.

template<class T>
class Matrix
{
    public:
    int r,c;
    vector< vector< T > >mat;

    Matrix() {}

    // Constructor to set the size of the matrix
    Matrix(int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            mat[i].resize(c);
    }
    // Constructor to build a matrix from a C 2d array
    // Pointer to the first element is passed (&arr[0][0])
    Matrix(T *arr,int _r,int _c)
    {
        r=_r;c=_c;
        mat.resize(r);
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i].push_back(arr[i*c+j]);
    }
    template<typename U>
    Matrix<T>& operator +=(const Matrix&M)
    {
        for(int i=0;i<r;i++)
            for(int j=0;j<c;j++)
                mat[i][j]+=static_cast<T>(M.mat[i][j]);
        return *this;
    }
    template<typename U>
    Matrix<T> operator +(const Matrix&M)
    {
        Matrix<T>tmp=*this;
        return tmp+=M;
    }
};

template<typename T>
istream& operator >>(istream &in,Matrix<T>&M)
{
    in>>M.r>>M.c;
    Matrix<T>tmp(M.r,M.c);
    for(int i=0;i<M.r;i++)
        for(int j=0;j<M.c;j++)
            in>>tmp.mat[i][j];
    M=tmp;
    return in;
}
template<typename T>
ostream& operator <<(ostream &out,Matrix<T>M)
{
    for(int i=0;i<M.r;i++)
    {
        for(int j=0;j<M.c;j++)
            cout<<M.mat[i][j]<<" ";
        cout<<endl;
    }
    return out;
}

EDIT:
Thank you all for the suggestions.

I just have one small question, say I do want to implement error checking (ex: checking for bounds,valid arguments etc..) however I do want the provide user with an option to disable error checking completely, is there any good way to implement this ?
What I need is something like example:`ios_base::sync_with_stdio(0);.
Thanks again.


问:
Autofocus first form element inside active div in a form
I have a form with several divs (10+) and I display only 1 at a time whereas the rest are set to display: hidden.When I click on the Next button, the current div gets hidden and the next one gets visible. There is a Previous button too.

Is there a way to focus the first form element of the currently visible div using JavaScript?

HTML Structure is as follows:

```<code><form id = "myForm">
<div id="div1">
<!-------Div can hav 2 cols---->
    <div class = "row">
        <div class= "col">
            <input autofocus>
        </div>
        <div class = "col">
            <select></select>
        </div>
    </div>
</div>
<div id="div2" style = "display: none;">
<!-------Or Div can have 1 col---->
    <div class = "row">
        <div class = "col">
             <!-------First element can be input---->
            <input>
        </div>
    </div>
</div>
<div id="div3" style = "display: none;">
    <div class = "row">
        <div class = "col">
             <!-------Or First element can be select---->
             <select> </select>
             <input>
        </div>
    </div>
</div>
<!-------More Divs---->
</form>
</code>```

The autofocus works on the first element but then I need to focus on the first elements of the rest of the divs inside the form using JavaScript.

答:
You can try this</p>

```<code><!DOCTYPE html>
<html>
<body>

<form id="form">
<input type="text"  />
<input type="text" />
<div>

</div>
</form>
<script>
var f = document.getElementById("form");
f[1].focus();
</script>
</body>
</html>

</code>```

Body:
I have a form with several divs (10+) and I display only 1 at a time whereas the rest are set to display: hidden.When I click on the Next button, the current div gets hidden and the next one gets visible. There is a Previous button too.

Is there a way to focus the first form element of the currently visible div using JavaScript?

HTML Structure is as follows:

<form id = "myForm">

            <input autofocus>

            <select></select>

            <input>

             <select> </select>
             <input>

</form>

The autofocus works on the first element but then I need to focus on the first elements of the rest of the divs inside the form using JavaScript.

Body:
You can try this

<!DOCTYPE html>
<html>
<body>

<form id="form">
<input type="text"  />
<input type="text" />
<div>

</div>
</form>
<script>
var f = document.getElementById("form");
f[1].focus();
</script>
</body>
</html>


问:
Offline Python Speech Recognition
I am creating a project that must respond to voice commands. I want this to work offline and I need it to be fast. I have tried PocketSphinx but it is not accurate enough. I will say, "hello", and in a quiet room it will display "mello" or "chello" my mic is good. What should I do? If I try to recognize it with google recognition then I get the perfect results. But my internet is slow and it takes forever. Any help is appreciated!</p>

答: Try snowboy.kitt.ai it is a wake word engine so you can have it recognize commands like "turn on the lights" or "hey Jarvis"</p>

Title: Offline Python Speech Recognition


问:
Splitting javascript object to normal String with = sign
How can I dynamically convert a json object to the following manner
I do have </p>

```<code>{ eligible: true, qualified:true }
</code>```

<p>but I need to make it like this </p>

```<code>eligible= true, qualified=true
</code>```

答:
If we can assume the string is a valid JSON object (yours is missing the quotes) you can parse the string as JSON and then use Object.entries to get the key value pairs which can then be mapped and joined down to your desired string output.

const jsonStr = '{ "eligible": true, "qualified":true }'
const jsonObj = JSON.parse(jsonStr)

console.log(Object.entries(jsonObj).map(e => e.join('=')).join(', '))```

Body:
How can I dynamically convert a json object to the following manner
I do have

{ eligible: true, qualified:true }

but I need to make it like this

eligible= true, qualified=true