问:
Arduino - Gyro sensor - ISR - TimeStamp
I currently working to recreate a quad-copter controller.

I am working on getting data from my gyro sensor, and to do that, I'm using
an ISR with an interuption.

My problem is, when I call my function "gyro.getX" on the main program, it work.
But, when I call this function from my ISR, it doesn't work.
I think that I found the reson of the bug, the function I'm using is provided by the "Adafruit_LSM9DS0" library (from ST), and it used a "timestamp".
I think that the current time from my ISR is different that the current time from my Main program, but i don't know how to fix it.

Here a shortcut of my program:

void loop(){
/*main prog*/
}

/*
*Reserve interrupt routine service (ISR) by Arduino
*/
ISR(TIMER2_OVF_vect)
{
    TCNT2 = 256 - 250; // 250 x 16 µS = 4 ms
    if (varCompteur++ > 25)// 25 * 4 ms = 100 ms (half-period)
    {
        varCompteur = 0;

        SensorGet(pX, pY);//Feed gyro circular buffers
    }
}

void SensorGet(float * pRollX, float * pPitchY)
{
    lsm.getEvent(&accel, &mag, &gyro, &temp);

    GiroX_Feed(pX, gyro.gyro.x);
    GiroY_Feed(pPitchY, gyro.gyro.y);
}

bool Adafruit_LSM9DS0::getEvent(sensors_event_t *accelEvent,
                                sensors_event_t *magEvent,
                                sensors_event_t *gyroEvent,
                                sensors_event_t *tempEvent)
{
  /* Grab new sensor reading and timestamp. */
  read();
  uint32_t timestamp = millis();

  /* Update appropriate sensor events. */
  if (accelEvent) getAccelEvent(accelEvent, timestamp);
  if (magEvent)   getMagEvent(magEvent, timestamp);
  if (gyroEvent)  getGyroEvent(gyroEvent, timestamp);
  if (tempEvent)  getTempEvent(tempEvent, timestamp);

  return true;
}
```

答:
The problem isn't the time.  The problem is likely that your sensor uses the I2C and it is disabled during an interrupt routine, or it's some other communication protocol that relies on interrupts to function and is therefore disabled during your ISR.

You are really abusing the interrupt.  This is not the kind of thing interrupts are for.  Interrupt should be super fast, no time for communications there.  So the real question is why do you think you need an interrupt for this?

Title: Arduino - Gyro sensor - ISR - TimeStamp


来源: stackexchange

问:
Neo4j replication alternative to Neo4j Enterprise edition?
It seems Neo4J High Availability is only available for the Enterprise edition which is paid- is there another alternative to achieve replication without that module? (i.e. without cost). Thanks for any help!</p>

答:
Actually Neo4j Enterprise is free under the open source AGPLv3 license.

Neo4j Inc can't modify the terms and still call it AGPL.

If you use Neo4j Enterprise as a server (like most people do) and communicate with it via its REST API or any of the official BOLT drivers then you never trigger AGPL's copyleft requirements.

In other words - the software that connects to it does not have to be open sourced.

You can download Neo4j Enterprise open source licensed binaries up to version 3.2.x from dist.neo4.org.  The links for the windows and unix packages are below. (Replace the version number for specific versions)

http://dist.neo4j.org/neo4j-enterprise-3.2.8-windows.zip

http://dist.neo4j.org/neo4j-enterprise-3.2.8-unix.tar.gz

If you want Neo4j Enterprise 3.3.0 and on under it's free open source license, then you can build them from source like we do for our US government clients, or just grab them from our free distribution site.

Check out the blog post if you want to understand why this has happened.

https://blog.igovsol.com/2017/11/14/Neo4j-330-is-out-but-where-are-the-open-source-enterprise-binaries.html

ContentLicense: CC BY-SA 3.0


问:
recoding data in python pandas
All,

I have a time series of data that is hourly.  See below:

```<code>2014-01-01 00:00:00     96.8
2014-01-01 01:00:00     91.3
2014-01-01 02:00:00     97.8
2014-01-01 03:00:00     77.0
2014-01-01 04:00:00    132.7
2014-01-01 05:00:00    188.1
2014-01-01 06:00:00    141.1
2014-01-01 07:00:00    115.5
</code>```

I would to wrangle this into a DataFrame that looks like this:

Month  1    2    3    4    5    6    7    8    9  ...

Jan

Feb                     Data

Mar

...

What is the best way to do this in python pandas?  The data in the series is pre formmatted and the index is a datetime. Here is the index:

```<code>class 'pandas.tseries.index.DatetimeIndex'
[2014-01-01 00:00:00, ..., 2014-12-31 23:00:00]
Length: 8760, Freq: None, Timezone: None
</code>```

答:
If I'm understanding correctly it looks like you want to resample your data by summing the hourly values over a monthly time period. You can do that using pandas resample function: </p>

```<code># This will resample your data by month.
df.resample('1M').sum()
</code>```

Title: recoding data in python pandas

Body:
All,

I have a time series of data that is hourly.  See below:

2014-01-01 00:00:00     96.8
2014-01-01 01:00:00     91.3
2014-01-01 02:00:00     97.8
2014-01-01 03:00:00     77.0
2014-01-01 04:00:00    132.7
2014-01-01 05:00:00    188.1
2014-01-01 06:00:00    141.1
2014-01-01 07:00:00    115.5

I would to wrangle this into a DataFrame that looks like this:

Month  1    2    3    4    5    6    7    8    9  ...

Jan

Feb                     Data

Mar

...

What is the best way to do this in python pandas?  The data in the series is pre formmatted and the index is a datetime. Here is the index:

class 'pandas.tseries.index.DatetimeIndex'
[2014-01-01 00:00:00, ..., 2014-12-31 23:00:00]
Length: 8760, Freq: None, Timezone: None

Body:
If I'm understanding correctly it looks like you want to resample your data by summing the hourly values over a monthly time period. You can do that using pandas resample function:

# This will resample your data by month.
df.resample('1M').sum()


问:
JSON parsing - Memory Dependent?
I'm trying to pass very large arrays to JavaScipt to be manipulated client-side, and it's not working. These arrays typically have about 12,000 elements each, and this snippet of code is functioning correctly when I only plug in 2,000 elements.

```<code>    <script type="text/javascript">

        var getLenders = JSON.parse('<?php echo json_encode($getlenders); ?>');
        var discountArray = JSON.parse('<?php echo json_encode($discountArray); ?>');
        var getData = JSON.parse('<?php echo json_encode($sortedArray); ?>');

    </script>
</code>```

I increased the memory requirements of the server to 512MB (4 time as much as before) thinking that'd be more than enough, however it is still not working. Before I crank up the memory to 1024MB, I would like to know if there is any other reason this is not working. Could it be an issue with client-side memory?

Any input is appreciated.

答:
You should implement it with pagination. So maybe just display 100 entries at once that can be edited and sorted by headline.
Then the user can decide to view the next 100 entries by clicking on a next link. Then you do an AJAX request to fetch the data and update your website.
jQuery should be sufficient for the job.

Title: JSON parsing - Memory Dependent?

Body:
I'm trying to pass very large arrays to JavaScipt to be manipulated client-side, and it's not working. These arrays typically have about 12,000 elements each, and this snippet of code is functioning correctly when I only plug in 2,000 elements.

I increased the memory requirements of the server to 512MB (4 time as much as before) thinking that'd be more than enough, however it is still not working. Before I crank up the memory to 1024MB, I would like to know if there is any other reason this is not working. Could it be an issue with client-side memory?

Any input is appreciated.


问:
angular.js: Typescript class constructor "this is undefined"
I'm trying to make a simple TypeScript class, however when it's instantiated I receive an this is undefined error in the constructor.

Class:

```<code>class MyClass {
    stuff: string;
    constructor(){
        this.stuff = 'stuff';
    }
}
app.config([MyClass]);
</code>```

Gets compiled into:

```<code>var MyClass = /** @class */ (function () {
    function MyClass() {
        this.stuff = 'stuff';
    }
    return MyClass;
}());
app_module_1.app.config([MyClass]);
</code>```

Why is this not working? Why is this undefined? This seems to be the appropriate syntax based on examples and other code I've written.

The remainder of my code (this works):

```<code>export let app = angular.module('timeApp', [
    uirouter
]);

class MainController{
    stuff: string;
    constructor(){
        this.stuff = "TESTING";
    }
}

app.controller('mainController', MainController);
</code>```

答:
Why is this not working?

Because you are using app.config([MyClass]); Angular will call it without new and hence this will be undefined

Fix

Don't use classes with angular config. Use functions.

More

new : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a simple TypeScript class, however when it's instantiated I receive an this is undefined error in the constructor.

Class:

class MyClass {
    stuff: string;
    constructor(){
        this.stuff = 'stuff';
    }
}
app.config([MyClass]);

Gets compiled into:

var MyClass = /** @class */ (function () {
    function MyClass() {
        this.stuff = 'stuff';
    }
    return MyClass;
}());
app_module_1.app.config([MyClass]);

Why is this not working? Why is this undefined? This seems to be the appropriate syntax based on examples and other code I've written.

The remainder of my code (this works):

export let app = angular.module('timeApp', [
    uirouter
]);

class MainController{
    stuff: string;
    constructor(){
        this.stuff = "TESTING";
    }
}

app.controller('mainController', MainController);


问:
How to design claims based identity system for multi tenant application with Okta in ASP .Net
I have a multi tenant application that is using claims based identity management with Windows AD. A single user CAN have access to multiple tenants which he/she can simply switch by selecting a different tenant from a dropdown (with same credentials) in the header.

Lets say I have features A, B, C in my application that I want to restrict access to. And I have clients ACME1 and ACME2. How can I design the identity role/claims setup so that a user can access features A and B for ACME1 and the same user can access only B and C features for ACME2.

答:
You can configure your custom authorization server to return dynamic claims, using Okta Expressions.  Docs here:

https://developer.okta.com/authentication-guide/implementing-authentication/set-up-authz-server#create-claims-optional

With this you can use group names, such as company_a, and put users in the groups of the companies they have access to.  You would then configure the authorization server to return groups as scope during authentication.


问:
How does this code for getting the lowest bit position work?
```<code>unsigned GetLowestBitPos(unsigned value)
{
   double d = value ^ (value - !!value);
   return (((int*)&d)[1]>>20)-1023; // This is what I really need help understanding.
}
</code>```

It looks to me that the code is casting a double into a pointer to an integer. I'm not sure what the [1] is used for. Then it looks like we are bit shifting by 20 bits to the right

I would appreciate any help on this code.
Its been a while since I have programmed with C++ and I'm trying to write logic for a Programmable Logic Controller (PLC) to do the same thing if it is possible.

Thanks for any help

答:
Let's take this one step at a time. First:

```<code>double d = value ^ (value - !!value);
</code>```

If value = 0, then this evaluates to 0 ^ (0 - 0), so d is 0.
If value != 0, then this evaluates to value ^ (value - 1). This has the effect of setting the lowest one bit, and lowest zero bits of value to one, and all other bits to zero. eg:

```<code>value = 010100100
d     = 000000111
</code>```

This occurs because (value - 1) is the same as value, except that the lowest string of zero bits become one, and the next one bit becomes zero, due to carrying

```<code>value     = 010100100
value - 1 = 010100011
XOR value = 000000111
</code>```

In any case, d is loaded with the floating point value of this. The next line:

```<code>return (((int*)&d)[1]>>20)-1023;
</code>```

This extracts the floating point exponent, and adds back the bias. Note that this assumes a little endian system, such as x86; on a big endian system you'd need to use [0]. It also makes assumptions about the size of ints and doubles - in particular, it assumes 32-bit ints, and 64-bit IEEE floats for doubles.

The key here is that non-denormalized IEEE floating point values (and a 32-bit int in a double will always be non-denormalized) end up with a representation looking a bit like 1.xxxxxxxx * 2^(e-1023), where xxxxxxxx is the fractional component, and e is the exponent. Since you've arranged the ones bit of interest to be the highest order ones bit, the exponentends up with the value you're looking for.

That said, you probably won't be able to use this on a PLC - although it's a pretty clever hack, it's only even remotely efficient if you have a hardware FPU; and even on x86 systems there are faster built-in integer operations. There are a number of other techniques in this SO question; you'll probably be able to find a faster one there. Your PLC also may have a built-in operation to do this in one instruction as well.

ContentLicense: CC BY-SA 2.5

Body:
unsigned GetLowestBitPos(unsigned value)
{
   double d = value ^ (value - !!value);
   return (((int*)&d)[1]>>20)-1023; // This is what I really need help understanding.
}

It looks to me that the code is casting a double into a pointer to an integer. I'm not sure what the [1] is used for. Then it looks like we are bit shifting by 20 bits to the right

I would appreciate any help on this code.
Its been a while since I have programmed with C++ and I'm trying to write logic for a Programmable Logic Controller (PLC) to do the same thing if it is possible.

Thanks for any help

Body:
Let's take this one step at a time. First:

double d = value ^ (value - !!value);

If value = 0, then this evaluates to 0 ^ (0 - 0), so d is 0.
If value != 0, then this evaluates to value ^ (value - 1). This has the effect of setting the lowest one bit, and lowest zero bits of value to one, and all other bits to zero. eg:

value = 010100100
d     = 000000111

This occurs because (value - 1) is the same as value, except that the lowest string of zero bits become one, and the next one bit becomes zero, due to carrying

value     = 010100100
value - 1 = 010100011
XOR value = 000000111

In any case, d is loaded with the floating point value of this. The next line:

return (((int*)&d)[1]>>20)-1023;

This extracts the floating point exponent, and adds back the bias. Note that this assumes a little endian system, such as x86; on a big endian system you'd need to use [0]. It also makes assumptions about the size of ints and doubles - in particular, it assumes 32-bit ints, and 64-bit IEEE floats for doubles.

The key here is that non-denormalized IEEE floating point values (and a 32-bit int in a double will always be non-denormalized) end up with a representation looking a bit like 1.xxxxxxxx * 2^(e-1023), where xxxxxxxx is the fractional component, and e is the exponent. Since you've arranged the ones bit of interest to be the highest order ones bit, the exponentends up with the value you're looking for.

That said, you probably won't be able to use this on a PLC - although it's a pretty clever hack, it's only even remotely efficient if you have a hardware FPU; and even on x86 systems there are faster built-in integer operations. There are a number of other techniques in this SO question; you'll probably be able to find a faster one there. Your PLC also may have a built-in operation to do this in one instruction as well.


问:
android call function after volley response in AsyncTask
I am getting data from web service using volley library but I want to move to another activity when I get the data by volley response so I want to wait until i have connection response. When I used AsyncTask, and put the transfer function in post execution, the second activity start the the data received as I saw in log cat. and when I put the transfer function inside volley OnResponse the activity freezing. So how can wait until get response and save the data then move to another activity to use it.
Here is the code:

```<code>public class Loading_Car_info extends AppCompatActivity {

    String appUrl="https://darialkndari5.000webhostapp.com/read_info.php";
    String  user_id,name,v_date,v_no,qr_code;
    String[] phaths;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading__car_info);
        Bundle b=this.getIntent().getExtras();
        MyAsyncTask m=new MyAsyncTask();
        m.execute();

        }
    public void transfer()
    {

        Bundle b=new Bundle();
        b.putStringArray("paths", phaths);
        b.putString("name","hi");
        b.putString("v_dat","hello");
        b.putString("v_no","rrr");
        b.putString("qr_code",qr_code);

        Intent intent=new Intent(this,User_Info.class);
        intent.putExtras(b);
        startActivity(intent);
    }

    public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            //UI Interaction
        }

        @Override
        protected Void doInBackground(Void... params) {

                StringRequest stringRequest = new StringRequest(Request.Method.POST, appUrl, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        boolean move=false;

                        phaths=new String[response.length()];

                        try {

                            JSONObject jsnobject = new JSONObject(response);
                            JSONArray jsonArray = jsnobject.getJSONArray("ads");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject student = jsonArray.getJSONObject(i);
                                v_date=student.getString("v_date");
                                v_no=student.getString("v_no");
                                qr_code=student.getString("Qr_code");
                                name=student.getString("name");
                                phaths[i]=student.getString("path");

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("MainActivity 2" + error.toString());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();

                        params.put("id", "3");
                        return params;
                    }
                };
                NotificationData.getmInstance(Loading_Car_info.this).addrequestqueue(stringRequest);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            transfer();
        }
    }
}
</code>```

答:
You need to call transfer after getting all your data within onResponse():

```<code>   try {
        JSONObject jsnobject = new JSONObject(response);
        JSONArray jsonArray = jsnobject.getJSONArray("ads");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject student = jsonArray.getJSONObject(i);
            v_date=student.getString("v_date");
            v_no=student.getString("v_no");
            qr_code=student.getString("Qr_code");
            name=student.getString("name");
            phaths[i]=student.getString("path");

        }

        transfer();

    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

Body:
I am getting data from web service using volley library but I want to move to another activity when I get the data by volley response so I want to wait until i have connection response. When I used AsyncTask, and put the transfer function in post execution, the second activity start the the data received as I saw in log cat. and when I put the transfer function inside volley OnResponse the activity freezing. So how can wait until get response and save the data then move to another activity to use it.
Here is the code:

public class Loading_Car_info extends AppCompatActivity {

    String appUrl="https://darialkndari5.000webhostapp.com/read_info.php";
    String  user_id,name,v_date,v_no,qr_code;
    String[] phaths;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading__car_info);
        Bundle b=this.getIntent().getExtras();
        MyAsyncTask m=new MyAsyncTask();
        m.execute();

        }
    public void transfer()
    {

        Bundle b=new Bundle();
        b.putStringArray("paths", phaths);
        b.putString("name","hi");
        b.putString("v_dat","hello");
        b.putString("v_no","rrr");
        b.putString("qr_code",qr_code);

        Intent intent=new Intent(this,User_Info.class);
        intent.putExtras(b);
        startActivity(intent);
    }

    public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            //UI Interaction
        }

        @Override
        protected Void doInBackground(Void... params) {

                StringRequest stringRequest = new StringRequest(Request.Method.POST, appUrl, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        boolean move=false;

                        phaths=new String[response.length()];

                        try {

                            JSONObject jsnobject = new JSONObject(response);
                            JSONArray jsonArray = jsnobject.getJSONArray("ads");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject student = jsonArray.getJSONObject(i);
                                v_date=student.getString("v_date");
                                v_no=student.getString("v_no");
                                qr_code=student.getString("Qr_code");
                                name=student.getString("name");
                                phaths[i]=student.getString("path");

                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println("MainActivity 2" + error.toString());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();

                        params.put("id", "3");
                        return params;
                    }
                };
                NotificationData.getmInstance(Loading_Car_info.this).addrequestqueue(stringRequest);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            transfer();
        }
    }
}

Body:
You need to call transfer after getting all your data within onResponse():

   try {
        JSONObject jsnobject = new JSONObject(response);
        JSONArray jsonArray = jsnobject.getJSONArray("ads");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject student = jsonArray.getJSONObject(i);
            v_date=student.getString("v_date");
            v_no=student.getString("v_no");
            qr_code=student.getString("Qr_code");
            name=student.getString("name");
            phaths[i]=student.getString("path");

        }

        transfer();

    } catch (JSONException e) {
        e.printStackTrace();
    }


问:
Convert simple list comprehension into for loops
My objective is transform this list comprehension into for loops :

```<code>[[x * y for x in  [1, 2]] for y in [3, 4, 5]]
# gives [[3,6], [4,8], [5,10]]
</code>```

The only thing i can find :

```<code>List = []
for y in [3, 4, 5]:
    for x in [1, 2]:
        List.append([y * x])
# Gives [[3], [6], [4], [8], [5], [10]]
</code>```

I feel silly but i struggle to find the solution.

答:
Take out the square brackets

```<code>List = []
for y in [3, 4, 5]:
    for x in [1, 2]:
        List.append(y * x)
</code>```

Adding a square bracket around a calculation makes it a list in python

Body:
My objective is transform this list comprehension into for loops :

[[x * y for x in  [1, 2]] for y in [3, 4, 5]]
# gives [[3,6], [4,8], [5,10]]

The only thing i can find :

List = []
for y in [3, 4, 5]:
    for x in [1, 2]:
        List.append([y * x])
# Gives [[3], [6], [4], [8], [5], [10]]

I feel silly but i struggle to find the solution.

Body:
Take out the square brackets

List = []
for y in [3, 4, 5]:
    for x in [1, 2]:
        List.append(y * x)

Adding a square bracket around a calculation makes it a list in python


问:
Please help improve the data to be compiled
I have data with the table as follows: enter image description here

In my Model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'parent_id', 'name', 'url', 'description', 'sort_order',
    ];

    public function parent()
    {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('App\Category', 'parent_id');
    }

    public function getParentsAttribute()
    {
        $parents = collect([]);

        $parent = $this->parent;

        while (!is_null($parent)) {
            $parents->push($parent);
            $parent = $parent->parent;
        }

        return $parents->implode('name', ' > ');
    }
}
</code>```

In my Controller:

```<code><?php

namespace App\Http\Controllers;

use App\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function listCategory()
    {
        $categories = Category::orderBy('sort_order')->get();
        // dd($categories);

        return view('catalog.category.list', ['categories' => $categories]);
    }
}
</code>```

enter image description here

But I can not match expectations.

答: I change $parents->push($parent); to $parents->prepend($parent); in my Model and this problem solved.

Body:
I have data with the table as follows: enter image description here

In my Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'parent_id', 'name', 'url', 'description', 'sort_order',
    ];

    public function parent()
    {
        return $this->belongsTo('App\Category', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('App\Category', 'parent_id');
    }

    public function getParentsAttribute()
    {
        $parents = collect([]);

        $parent = $this->parent;

        while (!is_null($parent)) {
            $parents->push($parent);
            $parent = $parent->parent;
        }

        return $parents->implode('name', ' > ');
    }
}

In my Controller:

<?php

namespace App\Http\Controllers;

use App\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function listCategory()
    {
        $categories = Category::orderBy('sort_order')->get();
        // dd($categories);

        return view('catalog.category.list', ['categories' => $categories]);
    }
}

enter image description here

But I can not match expectations.


问:
"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?
When debugging in Visual Studio, sometimes I add a breakpoint but it's hollow and VS says "The breakpoint will not currently be hit. The source code is different from the original version." Obviously this prevents me from being able to debug.

What on earth does the message mean? What original version? If I've just opened up the solution and not made any changes whatsoever to the code, how can there be an 'original version'?

答:
For me, none of the items solved the issue. I just added a new line of code inside that function, something like:

```<code>int a=0;
</code>```

by adding that, I guess I triggered visual studio to add this function to the original version

Body:
For me, none of the items solved the issue. I just added a new line of code inside that function, something like:

int a=0;

by adding that, I guess I triggered visual studio to add this function to the original version


问:
golang recursively reflect both type of field and value

In golang, I want to recursively reflect through a struct, getting the name of the field, it's type and the value.

The code here helped me reflect golang recurisive reflection

The problem is when I try to extract the value I keep getting panics when I reflect the value on a ptr Value.
Is it possible to reflect both the type, and keep passing the value through until I get to the primitives, and at that point print both the field name, type and value?

Here is the code I modified:

    func printType(prefix string, t reflect.Type, v reflect.Value visited map[reflect.Type]bool) {

    // Print the name of this type with opening ( for description.
    fmt.Printf("%s (", t)

    // Traverse elements, adding to description as we go.
elems:
    for {
        switch t.Kind() {
        case reflect.Ptr:
            fmt.Print("ptr to ")
        case reflect.Slice:
            fmt.Print("slice of ")
        case reflect.Array:
            fmt.Printf("array with %d elements of ", t.Len())
        default:
            break elems
        }
        t = t.Elem()
    }

    // Print the kind of the type and the closing ) of the description.
    // In the case of a struct, we print the names of the fields and recurse.
    switch t.Kind() {
    case reflect.Struct:
        fmt.Printf("struct with %d fields)\n", t.NumField())
        if visited[t] {
            // Don't blow up on recursive type definition.
            break
        }
        visited[t] = true
        prefix += "    "
        for i := 0; i < t.NumField(); i++ {
            f := t.Field(i)
            // Get value for field
            fieldValue := v.Field(i)

            fmt.Print(prefix, f.Name, " ")
            printType(prefix, f.Type, fieldValue, visited)
        }
    default:
        fmt.Printf("%s) : %s\n", t.Kind(), v)
    }
}
```

When I run this I get a panic when calling fieldValue := v.Field(i)
Any thoughts on how to achieve this?

Thanks

答:
Try this:

```<code>func printValue(prefix string, v reflect.Value, visited map[interface{}]bool) {

    fmt.Printf("%s: ", v.Type())

    // Drill down through pointers and interfaces to get a value we can print.
    for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
        if v.Kind() == reflect.Ptr {
            // Check for recursive data
            if visited[v.Interface()] {
                fmt.Println("visted")
                return
            }
            visited[v.Interface()] = true
        }
        v = v.Elem()
    }

    switch v.Kind() {
    case reflect.Slice, reflect.Array:
        fmt.Printf("%d elements\n", v.Len())
        for i := 0; i < v.Len(); i++ {
            fmt.Printf("%s%d: ", prefix, i)
            printValue(prefix+"   ", v.Index(i), visited)
        }
    case reflect.Struct:
        t := v.Type() // use type to get number and names of fields
        fmt.Printf("%d fields\n", t.NumField())
        for i := 0; i < t.NumField(); i++ {
            fmt.Printf("%s%s: ", prefix, t.Field(i).Name)
            printValue(prefix+"   ", v.Field(i), visited)
        }
    case reflect.Invalid:
        fmt.Printf("nil\n")
    default:
        fmt.Printf("%v\n", v.Interface())
    }
}
</code>```

Because it's possible to get the type from a value, there's no need to pass types to the print function.

playground example

Body:
In golang, I want to recursively reflect through a struct, getting the name of the field, it's type and the value.

The code here helped me reflect golang recurisive reflection

The problem is when I try to extract the value I keep getting panics when I reflect the value on a ptr Value.
Is it possible to reflect both the type, and keep passing the value through until I get to the primitives, and at that point print both the field name, type and value?

Here is the code I modified:

    func printType(prefix string, t reflect.Type, v reflect.Value visited map[reflect.Type]bool) {

    // Print the name of this type with opening ( for description.
    fmt.Printf("%s (", t)

    // Traverse elements, adding to description as we go.
elems:
    for {
        switch t.Kind() {
        case reflect.Ptr:
            fmt.Print("ptr to ")
        case reflect.Slice:
            fmt.Print("slice of ")
        case reflect.Array:
            fmt.Printf("array with %d elements of ", t.Len())
        default:
            break elems
        }
        t = t.Elem()
    }

    // Print the kind of the type and the closing ) of the description.
    // In the case of a struct, we print the names of the fields and recurse.
    switch t.Kind() {
    case reflect.Struct:
        fmt.Printf("struct with %d fields)\n", t.NumField())
        if visited[t] {
            // Don't blow up on recursive type definition.
            break
        }
        visited[t] = true
        prefix += "    "
        for i := 0; i < t.NumField(); i++ {
            f := t.Field(i)
            // Get value for field
            fieldValue := v.Field(i)

            fmt.Print(prefix, f.Name, " ")
            printType(prefix, f.Type, fieldValue, visited)
        }
    default:
        fmt.Printf("%s) : %s\n", t.Kind(), v)
    }
}

When I run this I get a panic when calling fieldValue := v.Field(i)
Any thoughts on how to achieve this?

Thanks

Body:
Try this:

func printValue(prefix string, v reflect.Value, visited map[interface{}]bool) {

    fmt.Printf("%s: ", v.Type())

    // Drill down through pointers and interfaces to get a value we can print.
    for v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
        if v.Kind() == reflect.Ptr {
            // Check for recursive data
            if visited[v.Interface()] {
                fmt.Println("visted")
                return
            }
            visited[v.Interface()] = true
        }
        v = v.Elem()
    }

    switch v.Kind() {
    case reflect.Slice, reflect.Array:
        fmt.Printf("%d elements\n", v.Len())
        for i := 0; i < v.Len(); i++ {
            fmt.Printf("%s%d: ", prefix, i)
            printValue(prefix+"   ", v.Index(i), visited)
        }
    case reflect.Struct:
        t := v.Type() // use type to get number and names of fields
        fmt.Printf("%d fields\n", t.NumField())
        for i := 0; i < t.NumField(); i++ {
            fmt.Printf("%s%s: ", prefix, t.Field(i).Name)
            printValue(prefix+"   ", v.Field(i), visited)
        }
    case reflect.Invalid:
        fmt.Printf("nil\n")
    default:
        fmt.Printf("%v\n", v.Interface())
    }
}

Because it's possible to get the type from a value, there's no need to pass types to the print function.

playground example


问:
Bash script help, include sub-directories for processing files
I am definitely new to scripting.  I have a script that processes some files and I can't figure out how to run this against all files in a directory that has many sub-directories and thousands of files.  Basically I want to take this script and run it against a directory titled 2011 and have it process every file in every sub-folder.  </p>

```<code>#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done
</code>```

答:
The following script will recurse into every directory under ./userfiles and work on all files there, even ones with spaces in their names (or other nefarious characters).

Also, the way you have the script written, make will be passed as its last argument the filename as it appears on your disk appended with .html.  For example, the file ./userfiles/subdir/foobar.txt will be passed to make as ./userfiles/subdir/foobar.txt.html.  If this is not what you want, then adjust ${file}.html accordingly.

Additionally, if you want find to only work on files ending in, for example, .html, then you can append the option -name "*.html" to the find command anywhere after the pathname.

```<code>#!/bin/bash

topLevelDir="./userfiles"

while IFS= read -r -d $'\0' file; do
    echo
    echo
    echo "Processing File $file ...."
    echo
    echo
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar "${file}".html
    echo
    echo
    echo "File $file.html Generated"
done < <(find "$topLevelDir" -type f -print0)
</code>```

Body:
I am definitely new to scripting.  I have a script that processes some files and I can't figure out how to run this against all files in a directory that has many sub-directories and thousands of files.  Basically I want to take this script and run it against a directory titled 2011 and have it process every file in every sub-folder.

#!/bin/bash
FILES=./userfiles/*
for f in $FILES
do
    echo ""
    echo ""
    echo "Processing File $f ...."
    echo ""
    echo ""
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar $f.html
    echo ""
    echo ""
    echo "File $f.html Generated"
done

Body:
The following script will recurse into every directory under ./userfiles and work on all files there, even ones with spaces in their names (or other nefarious characters).

Also, the way you have the script written, make will be passed as its last argument the filename as it appears on your disk appended with .html.  For example, the file ./userfiles/subdir/foobar.txt will be passed to make as ./userfiles/subdir/foobar.txt.html.  If this is not what you want, then adjust ${file}.html accordingly.

Additionally, if you want find to only work on files ending in, for example, .html, then you can append the option -name "*.html" to the find command anywhere after the pathname.

#!/bin/bash

topLevelDir="./userfiles"

while IFS= read -r -d $'\0' file; do
    echo
    echo
    echo "Processing File $file ...."
    echo
    echo
    make FILE_TYPE=user CSS_PATH=./log.css SCRIPT_PATH=./toggle.js SAXON_JAR=/opt/saxon/saxon9he.jar "${file}".html
    echo
    echo
    echo "File $file.html Generated"
done < <(find "$topLevelDir" -type f -print0)


问:
gRPC installation fails at "make"
I am following the Built From Source instructions to install grpc

```<code>$ git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc
</code>```

success

```<code>$ cd grpc
</code>```

success

```<code>$ git submodule update --init
</code>```

success

```<code>$ make
</code>```

fails after building a few source files

```<code>third_party/boringssl/crypto/rand/urandom.c:62:2: error: #error "system call number for getrandom is not the expected value"
#error "system call number for getrandom is not the expected value"
 ^
In file included from /usr/include/x86_64-linux-gnu/sys/syscall.h:31:0,
from third_party/boringssl/crypto/rand/urandom.c:32:
third_party/boringssl/crypto/rand/urandom.c: In function ‘init_once’:
third_party/boringssl/crypto/rand/urandom.c:128:15: error: ‘__NR_getrandom’ undeclared (first use in this function)
syscall(SYS_getrandom, &dummy, sizeof(dummy), GRND_NONBLOCK);
         ^
third_party/boringssl/crypto/rand/urandom.c:128:15: note: each undeclared identifier is reported only once for each function it appears in
third_party/boringssl/crypto/rand/urandom.c: In function ‘fill_with_entropy’:
third_party/boringssl/crypto/rand/urandom.c:258:21: error: ‘__NR_getrandom’ undeclared (first use in this function)
r = syscall(SYS_getrandom, out, len, 0 /* no flags */);
            ^
Makefile:2564: recipe for target '/home/usrnm/grpc/objs/opt/third_party/boringssl/crypto/rand/urandom.o' failed
make: *** [/home/usrnm/grpc/objs/opt/third_party/boringssl/crypto/rand/urandom.o] Error 1
</code>```

OS: Linux 4.4.0-0 SMP Debian 4.4.16-1

GCC version: gcc (Debian 4.9.2-10) 4.9.2

I couldn't find any open issues or any help about this error on the internet.

答: The problem seems to happen while compiling boringssl . We use the version given by $ git submodule, which at the time of this writing is be2ee342d3781ddb954f91f8a7e660c6f59e87e5 third_party/boringssl (version_for_cocoapods_7.0-526-gbe2ee342). Are you able to compile boringssl on its own?

Title: gRPC installation fails at "make"

Body:
I am following the Built From Source instructions to install grpc

$ git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc

success

$ cd grpc

success

$ git submodule update --init

success

$ make

fails after building a few source files

third_party/boringssl/crypto/rand/urandom.c:62:2: error: #error "system call number for getrandom is not the expected value"
#error "system call number for getrandom is not the expected value"
 ^
In file included from /usr/include/x86_64-linux-gnu/sys/syscall.h:31:0,
from third_party/boringssl/crypto/rand/urandom.c:32:
third_party/boringssl/crypto/rand/urandom.c: In function ‘init_once’:
third_party/boringssl/crypto/rand/urandom.c:128:15: error: ‘__NR_getrandom’ undeclared (first use in this function)
syscall(SYS_getrandom, &dummy, sizeof(dummy), GRND_NONBLOCK);
         ^
third_party/boringssl/crypto/rand/urandom.c:128:15: note: each undeclared identifier is reported only once for each function it appears in
third_party/boringssl/crypto/rand/urandom.c: In function ‘fill_with_entropy’:
third_party/boringssl/crypto/rand/urandom.c:258:21: error: ‘__NR_getrandom’ undeclared (first use in this function)
r = syscall(SYS_getrandom, out, len, 0 /* no flags */);
            ^
Makefile:2564: recipe for target '/home/usrnm/grpc/objs/opt/third_party/boringssl/crypto/rand/urandom.o' failed
make: *** [/home/usrnm/grpc/objs/opt/third_party/boringssl/crypto/rand/urandom.o] Error 1

OS: Linux 4.4.0-0 SMP Debian 4.4.16-1

GCC version: gcc (Debian 4.9.2-10) 4.9.2

I couldn't find any open issues or any help about this error on the internet.


问:
How to reference foreign key in mysql at phpmyadmin
I am using mysql in phpmyadmin. I have created two tables.

```<code>company (
company_id INT PRIMARY KEY,
company_name VARCHAR(20)
);

users (
user_id INT PRIMARY KEY,
user_first_name VARCHAR(20) ,
user_last_name VARCHAR(20),
user_type VARCHAR(10),
user_email VARCHAR(40)
);
</code>```

Now i want to declare Foreign key company(company) reference to users(user_id). SO company will be primary and foreign key at same time. How do i Do that?

答: ALTER TABLE company ADD CONSTRAINT company_id_fk FOREIGN KEY (company_id) REFERENCES users(user_id) ON DELETE RESTRICT ON UPDATE RESTRICT;

Body:
I am using mysql in phpmyadmin. I have created two tables.

company (
company_id INT PRIMARY KEY,
company_name VARCHAR(20)
);

users (
user_id INT PRIMARY KEY,
user_first_name VARCHAR(20) ,
user_last_name VARCHAR(20),
user_type VARCHAR(10),
user_email VARCHAR(40)
);

Now i want to declare Foreign key company(company) reference to users(user_id). SO company will be primary and foreign key at same time. How do i Do that?


问:
unable to send email using python
What am I doing wrong? Should be so simple.After I execute - nothing happens, no errors, no email. Nothing.
I am using Jupyter. </p>

```<code>def send_email(user, pwd, recipient, subject, body):
    import smtplib

    gmail_user = 'email@email.com'
    gmail_pwd = 'pass'
    FROM = 'email@email.com'
    TO = 'email@email.com'
    SUBJECT = 'Test'
    TEXT = 'Hello, this is test email'

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print ('successfully sent the mail')
    except:
        print ("failed to send mail")
</code>```

答:
It is only function definiton. You have to execut it like

```<code>send_email("me@gmai.com", "MyPaSwOrD", "you@gmail.com", "Money for you", "Hi")
</code>```

But your code will not use this data because it has hardcoded values inside.

Title: unable to send email using python

Body:
What am I doing wrong? Should be so simple.After I execute - nothing happens, no errors, no email. Nothing.
I am using Jupyter.

def send_email(user, pwd, recipient, subject, body):
    import smtplib

    gmail_user = 'email@email.com'
    gmail_pwd = 'pass'
    FROM = 'email@email.com'
    TO = 'email@email.com'
    SUBJECT = 'Test'
    TEXT = 'Hello, this is test email'

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(gmail_user, gmail_pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print ('successfully sent the mail')
    except:
        print ("failed to send mail")

Body:
It is only function definiton. You have to execut it like

send_email("me@gmai.com", "MyPaSwOrD", "you@gmail.com", "Money for you", "Hi")

But your code will not use this data because it has hardcoded values inside.


问:
Python Convert string to dict
I have a string :

```<code>'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'
</code>```

and would like to convert it to

```<code>{
  "tomatoes" : "5" ,
  "livestock" :"{"cow" : "5" , "sheep" :"2" }"
}
</code>```

Any ideas ?

答:
What u have is a JSON formatted string which u want to convert to python dictionary.

Using the JSON library :

```<code>import json
with open("your file", "r") as f:
    dictionary =  json.loads(f.read());
</code>```

Now dictionary contains the data structure which ur looking for.

Title: Python Convert string to dict

Body:
I have a string :

'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'

and would like to convert it to

{
  "tomatoes" : "5" ,
  "livestock" :"{"cow" : "5" , "sheep" :"2" }"
}

Any ideas ?

Body:
What u have is a JSON formatted string which u want to convert to python dictionary.

Using the JSON library :

import json
with open("your file", "r") as f:
    dictionary =  json.loads(f.read());

Now dictionary contains the data structure which ur looking for.


问:
Error creating apache certificate
I have a CentOS server and I'm trying to install Apache Certificate using the following command:

certbot --apache -d myDomain.com

But I'm getting the following error:

```<code>Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator apache, Installer apache
Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org
Obtaining a new certificate
Performing the following challenges:
tls-sni-01 challenge for myDomain.com
Error while running apachectl graceful.

Job for httpd.service invalid.

Cleaning up challenges
Error while running apachectl graceful.

Job for httpd.service invalid.

Encountered exception during recovery
Error while running apachectl graceful.

Job for httpd.service invalid.
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/certbot/error_handler.py", line 100, in _call_registered
    self.funcs[-1]()
  File "/usr/lib/python2.7/site-packages/certbot/auth_handler.py", line 284, in _cleanup_challenges
    self.auth.cleanup(achalls)
  File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 1945, in cleanup
    self.restart()
  File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 1834, in restart
    self._reload()
  File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 1845, in _reload
    raise errors.MisconfigurationError(str(err))
MisconfigurationError: Error while running apachectl graceful.

Job for httpd.service invalid.

Error while running apachectl graceful.

Job for httpd.service invalid.
</code>```

I check if Apache was running:

```<code>ps aux|grep httpd
root     16569  0.0  0.0   9064   920 pts/1    S+   14:44   0:00 grep --color=auto httpd
</code>```

I had no instances of apache running.

Any of you knows how can I fix this error or if there is workaround this?

I'll really appreciate your help.

答:
certbot is clearly trying to start/restart apache and that's failing. There could be many reasons for that, and I would start by looking for the apache error log and seeing what it has. (There can be more than one, so check the timestamps.)

It would also be interesting to know if apache can start at all. What happens with a plain old apachectl start?

Title: Error creating apache certificate

Body:
I have a CentOS server and I'm trying to install Apache Certificate using the following command:

certbot --apache -d myDomain.com

But I'm getting the following error:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator apache, Installer apache
Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org
Obtaining a new certificate
Performing the following challenges:
tls-sni-01 challenge for myDomain.com
Error while running apachectl graceful.

Job for httpd.service invalid.

Cleaning up challenges
Error while running apachectl graceful.

Job for httpd.service invalid.

Encountered exception during recovery
Error while running apachectl graceful.

Job for httpd.service invalid.
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/certbot/error_handler.py", line 100, in _call_registered
    self.funcs[-1]()
  File "/usr/lib/python2.7/site-packages/certbot/auth_handler.py", line 284, in _cleanup_challenges
    self.auth.cleanup(achalls)
  File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 1945, in cleanup
    self.restart()
  File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 1834, in restart
    self._reload()
  File "/usr/lib/python2.7/site-packages/certbot_apache/configurator.py", line 1845, in _reload
    raise errors.MisconfigurationError(str(err))
MisconfigurationError: Error while running apachectl graceful.

Job for httpd.service invalid.

Error while running apachectl graceful.

Job for httpd.service invalid.

I check if Apache was running:

ps aux|grep httpd
root     16569  0.0  0.0   9064   920 pts/1    S+   14:44   0:00 grep --color=auto httpd

I had no instances of apache running.

Any of you knows how can I fix this error or if there is workaround this?

I'll really appreciate your help.


问:
Can I lay a fixed layer over a custom canvas?
In Android Studio, I'm developing a game in which I draw my animation at 60fps using a SurfaceView object. I use a semitransparent image as the top layer to hide the edges of the playing field -- sort of a "fogs of war" effect so that the player does not know what to expect beyond the shadows.

My problem is that I need to draw this shadow image for every frame, even though the shadow never changes or moves, even when the playing field scrolls right/left/up/down.  And it's a full-screen image, so it slows the game to a crawl.

Is there a way to create a one-time overlay ONCE on top of the animated custom canvas? I also want to interact with the canvas beneath it, as if the overlay was not even there.

答:
Have you tried putting a full screen ImageView over your surface view and setting the "fog of war" image to this, should draw it once (this is assuming the background to your "fog of war is transparent").

If you need anything fancier then ViewOverlay should cover you, but my understanding is this is used when individual views wish to draw outside their bounds for animations, as you are using full screen surface view this should be unnecessary

https://developer.android.com/reference/android/view/ViewOverlay.html

Also no reason why you can't stick a surface view over a surface view. One for the fog of war / screen effects, one for the game surface.


问:
Catching constraint violations in JPA 2.0
Consider the following entity class, used with, for example, EclipseLink 2.0.2 - where the link attribute is not the primary key, but unique nontheless.

```<code>@Entity
public class Profile {
  @Id
  private Long id;

  @Column(unique = true)
  private String link;

  // Some more attributes and getter and setter methods
}
</code>```

When I insert records with a duplicate value for the link attribute, EclipseLink does not throw a EntityExistsException, but throws a DatabaseException, with the message explaining that the unique constraint was violated.

This doesn't seem very usefull, as there would not be a simple, database independent, way to catch this exception. What would be the advised way to deal with this?

A few things that I have considered are:

Checking the error code on the DatabaseException - I fear that this error code, though, is the native error code for the database;

Checking the existence of a Profile with the specific value for link beforehand - this obviously would result in an enormous amount of superfluous queries.

答:
It's too bad they don't have a ConstraintViolationException in JPA. I've created a helper method to determine if the PersistenceException is a constraint violation for a given class - it is hibernate only though. I imagine there is a way to do it using other implementations.</p>

```<code>protected Boolean isUniqueConstraintViolation(PersistenceException ex, Class entity) {

    if (((NonUniqueObjectException)ex.getCause()).getEntityName().equals(entity.getName())) {
        return true;
    }

    return false;
}
</code>```

Body:
Consider the following entity class, used with, for example, EclipseLink 2.0.2 - where the link attribute is not the primary key, but unique nontheless.

@Entity
public class Profile {
  @Id
  private Long id;

  @Column(unique = true)
  private String link;

  // Some more attributes and getter and setter methods
}

When I insert records with a duplicate value for the link attribute, EclipseLink does not throw a EntityExistsException, but throws a DatabaseException, with the message explaining that the unique constraint was violated.

This doesn't seem very usefull, as there would not be a simple, database independent, way to catch this exception. What would be the advised way to deal with this?

A few things that I have considered are:

Checking the error code on the DatabaseException - I fear that this error code, though, is the native error code for the database;

Checking the existence of a Profile with the specific value for link beforehand - this obviously would result in an enormous amount of superfluous queries.

Body:
It's too bad they don't have a ConstraintViolationException in JPA. I've created a helper method to determine if the PersistenceException is a constraint violation for a given class - it is hibernate only though. I imagine there is a way to do it using other implementations.

protected Boolean isUniqueConstraintViolation(PersistenceException ex, Class entity) {

    if (((NonUniqueObjectException)ex.getCause()).getEntityName().equals(entity.getName())) {
        return true;
    }

    return false;
}


答:
You need a temporary list in between the for-loops:

```<code>List = []
for y in [3, 4, 5]:
   l = []
   for x in [1, 2]:
       l.append(x*y)
   List.append(l)
</code>```

Output:

```<code>[[3, 6], [4, 8], [5, 10]]
</code>```

Title: Convert simple list comprehension into for loops

Body:
My objective is transform this list comprehension into for loops :

[[x * y for x in  [1, 2]] for y in [3, 4, 5]]
# gives [[3,6], [4,8], [5,10]]

The only thing i can find :

List = []
for y in [3, 4, 5]:
    for x in [1, 2]:
        List.append([y * x])
# Gives [[3], [6], [4], [8], [5], [10]]

I feel silly but i struggle to find the solution.

Body:
You need a temporary list in between the for-loops:

List = []
for y in [3, 4, 5]:
   l = []
   for x in [1, 2]:
       l.append(x*y)
   List.append(l)

Output:

[[3, 6], [4, 8], [5, 10]]


问:
Read SQS queue from AWS Lambda
I have the following infrastructure:

I have an EC2 instance with a NodeJS+Express process listening on a port for messages (process 1). Every time the process receives a message it sends it to an SQS queue. Then I have another process in the same machine reading the queue using long polling (process 2). When it finds a message in the queue it inserts the data in a MariaDB database sitting on an RDS instance.

(Just to clarify, messages are generated by users, they send a chunk of data which can contain arbitrary information to the endpoint where the process 1 is listening)

Now I want to put the process that reads the SQS (process 2) in a Lambda function so that the process that writes to the queue and the one that reads from the queue are completely independent. The problem is that I don't know if this is possible.

I know that Lambda function are invoked in response to an event, and the events supported at the moment are S3, SNS, SES, DynamoDB, Kinesis, Cognito, CloudWatch and Cloudformation but NOT SQS.

I was thinking in using SNS notifications to invoke the Lambda function so that every time a message is pushed to the queue, an SNS notification is fired and invokes the Lambda function but after playing a bit with it I've realised that is not possible to create an SNS notification from SQS, it's only possible to write SNS notifications to the queue.

Right now I'm a bit stuck because I don't know how to continue. I have the feeling that is not possible to create this infrastructure due to the current limitations in the AWS services. Is there another way to do what I want or am I in a dead-end?

Just to extend my question with some research I've made, this github repo shows how to read an SQS queu from a Lambda function but the lambda function works only if is fired from the command line:

https://github.com/robinjmurphy/sqs-to-lambda

In the readme, the author mentions the following:

Update: Lambda now supports SNS notifications as an event source,
  which makes this hack entirely unneccessary for SNS notifcations. You
  might still find it useful if you like the idea of using a Lambda
  function to process jobs on an SQS queue.

But I think this doesn't solve my problem, an SNS notification can invoke the Lambda function but I don't see how I can create a notification when a message is received in the SQS queue.

Thanks

答: We had some similar requirements so we ended up building a library and open sourcing it to help with SQS to Lambda async.  I'm not sure if this fills your particular set of requirements, but thought it might be worth a look: https://read.iopipe.com/sqs-lambda-teaming-up-92c4096be49c</p>

Title: Read SQS queue from AWS Lambda


问:
XInitThreads() called. Still graphics.h crashes
When I use  to draw in c++, the frame comes out fine for 2-3 seconds and then crashes saying:

[xcb] Unknown sequence number while processing queue.

[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called

I have called the XInitThreads() befor initgraph()
I use Ubuntu 17.10 and g++ 7.2
There seems to be a problem with Ubuntu while using XInitThreads() from what I saw online.
Is there an alternative drawing method? Or can I fix this problem?

A part of my code:

```<code>int main()
{
  int gd = DETECT, gm;
  XInitThreads();
  initgraph(&gd, &gm, NULL);
  line(100,100,200,200);
  delay(10000);
  getch();
}
</code>```

答:
See: xcb.freedesktop.org/tutorial

It seems as if you could use this tutorial. My understanding was that graphics.h was a header for functions included a long time ago, with Borland Turbo-C? If the functionality of that library was directly reproduced, it wouldn't be compatible with xcb or Xlib since it took over the framebuffer entirely.

I found the Basic Windows and Drawing tutorial, which you'll find at the link I provided, to be very helpful. After you create a window and map it to the screen, you can draw in it using the primitives, pixel by pixel if you like.

Body:
When I use  to draw in c++, the frame comes out fine for 2-3 seconds and then crashes saying:

[xcb] Unknown sequence number while processing queue.

[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called

I have called the XInitThreads() befor initgraph()
I use Ubuntu 17.10 and g++ 7.2
There seems to be a problem with Ubuntu while using XInitThreads() from what I saw online.
Is there an alternative drawing method? Or can I fix this problem?

A part of my code:

int main()
{
  int gd = DETECT, gm;
  XInitThreads();
  initgraph(&gd, &gm, NULL);
  line(100,100,200,200);
  delay(10000);
  getch();
}


问:
Generics and Entity Framework: How do I return a different type depending on a column value
We have a Persons table which stores different types of persons (Buyer, Seller, Agent, etc).  Our ORM is Entity Framework CodeFirst (CTP5).  We're using the repository pattern for good TDD and mocking.  In the PersonRepository I want to return a specific type so I can do things like this:

```<code>Agent a = repository.Get<Agent>(5005);  // Where 5005 is just an example Id for the person
a.SomeAgentProperty = someValue;
Buyer b = repository.Get<Buyer>(253);   // Again, a simple PersonId.
b.SomeBuyerProperty = someOtherValue;
</code>```

The idea is that I know what kind of person I'm getting when I get it from the repository.  And, yes, I could just create X different Get methods called GetBuyer(int PersonId), GetSeller(int PersonId) and so on.  But that has a code smell.

How would the generic function look?

Here is my repository interface so far:

```<code>public interface IPersonRepository
{
    Person Get(int PersonId);   // To get a generic person
    T Get<T>(int PersonId);     // To get a specific type of person (buyer, agent, etc.)
    void Save(Person person);
    void Delete(int p);
}
</code>```

And my concrete implementation:

```<code>    public T Get<T>(int PersonId)
    {
        //Here's my question: What goes here?
    }
</code>```

答:
I would suggest to use something like:

```<code>public T Get<T>(int PersonId) where T: new()
{
    return new T(PersonId);
}
</code>```

and load data in the constructor or implement some kind of Load method for each type of your entity, like:

```<code>interface IEntity
{
    void Load(int Id);
}

class CBuyer: IEntity
{
    public Load(int Id) { ... }
}

public T Get<T>(int PersonId) where T: IEntity, new()
{
    T ent = new T();
    ent.Load(PersonId);
    return ent;
}
</code>```

Body:
We have a Persons table which stores different types of persons (Buyer, Seller, Agent, etc).  Our ORM is Entity Framework CodeFirst (CTP5).  We're using the repository pattern for good TDD and mocking.  In the PersonRepository I want to return a specific type so I can do things like this:

Agent a = repository.Get<Agent>(5005);  // Where 5005 is just an example Id for the person
a.SomeAgentProperty = someValue;
Buyer b = repository.Get<Buyer>(253);   // Again, a simple PersonId.
b.SomeBuyerProperty = someOtherValue;

The idea is that I know what kind of person I'm getting when I get it from the repository.  And, yes, I could just create X different Get methods called GetBuyer(int PersonId), GetSeller(int PersonId) and so on.  But that has a code smell.

How would the generic function look?

Here is my repository interface so far:

public interface IPersonRepository
{
    Person Get(int PersonId);   // To get a generic person
    T Get<T>(int PersonId);     // To get a specific type of person (buyer, agent, etc.)
    void Save(Person person);
    void Delete(int p);
}

And my concrete implementation:

    public T Get<T>(int PersonId)
    {
        //Here's my question: What goes here?
    }

Body:
I would suggest to use something like:

public T Get<T>(int PersonId) where T: new()
{
    return new T(PersonId);
}

and load data in the constructor or implement some kind of Load method for each type of your entity, like:

interface IEntity
{
    void Load(int Id);
}

class CBuyer: IEntity
{
    public Load(int Id) { ... }
}

public T Get<T>(int PersonId) where T: IEntity, new()
{
    T ent = new T();
    ent.Load(PersonId);
    return ent;
}


问:
What is the fastest way to get the value of e?
What is the most optimised algorithm which finds the value of e with moderate accuracy?

I am looking for a comparison between optimised approaches giving more importance to speed than high precision.

Edit: By moderate accuracy I mean upto 6-7 decimal places.
But if there is a HUGE difference in speed, then I can settle with 4-5 places.

答: For reference see Brother's formula here  : https://www.intmath.com/exponential-logarithmic-functions/calculating-e.php


问:
How to resize Twitter Bootstrap modal dynamically based on data content
I'm loading modal with remote content in this way

```<code><a data-toggle="modal" data-target="#myModal" href="my-page.php">Click to open Modal</a>
</code>```

and now I need to set also size of modal based on content...
Then I add data-class

```<code><a data-toggle="modal" data-target="#myModal" data-class="modal-lg" href="my-page.php">Click to open Modal</a>

<a data-toggle="modal" data-target="#myModal" data-class="modal-sm" href="my-page2.php">Click to open Modal</a>
</code>```

And then I have tried this to set the size

```<code>$('#myModal').on('shown.bs.modal', function () {
  var class = $(this).data('class');
  $(this).find('.modal-dialog').addClass(class);
});
</code>```

but not working...

答:
Your code don't catch the element that open the modal:

var class = $(this).data('class');

in this context this refer to modal.

Furthermore, class is a reserved words in ECMAScript5/6 (you cannot use it as variable name).

To grab the correct data-class value, you can use relatedTarget property of the event (passed as function argument).

Finally, remove any css classes that may be present and add the correct class:

```<code>$('#myModal').on('show.bs.modal', function (event) {

  var _trigger = $(event.relatedTarget)
  var _class = _trigger.data('class');

  $(this)
    .find('.modal-dialog')
    .removeClass('modal-lg modal-sm')
    .addClass( _class);

});
</code>```

Demo: https://codepen.io/anon/pen/XzQByR

PS I use show.bs.modal event, because it is fired immediately when the show instance method is called (see the docs) and, in the demo, I use <button> instead of

Body:
I'm loading modal with remote content in this way

Click to open Modal

and now I need to set also size of modal based on content...
Then I add data-class

Click to open Modal

Click to open Modal

And then I have tried this to set the size

$('#myModal').on('shown.bs.modal', function () {
  var class = $(this).data('class');
  $(this).find('.modal-dialog').addClass(class);
});

but not working...

Body:
Your code don't catch the element that open the modal:

var class = $(this).data('class');

in this context this refer to modal.

Furthermore, class is a reserved words in ECMAScript5/6 (you cannot use it as variable name).

To grab the correct data-class value, you can use relatedTarget property of the event (passed as function argument).

Finally, remove any css classes that may be present and add the correct class:

$('#myModal').on('show.bs.modal', function (event) {

  var _trigger = $(event.relatedTarget)
  var _class = _trigger.data('class');

  $(this)
    .find('.modal-dialog')
    .removeClass('modal-lg modal-sm')
    .addClass( _class);

});

Demo: https://codepen.io/anon/pen/XzQByR

PS I use show.bs.modal event, because it is fired immediately when the show instance method is called (see the docs) and, in the demo, I use <button> instead of <a>


问:
How to automatically convert many fields of a polygon shapefile to raster in R
I have a shapefile representing Thiessen polygons.

Each polygon is associated with many values of a table.

```<code>thiessen <- readOGR(dsn = getwd(), layer = poly)
OGR data source with driver: ESRI Shapefile
Source: ".../raingauges/shp", layer: "thiessen_pol"
with 10 features
It has 5 fields
head(thiessen)
  est est_name p001 p002 p003
0   2   borges    1    8    2
1   0     e018    2    4    3
2   5  starosa    5   15    1
3   6   delfim    4    2    2
4   1     e087    1    1    3
5   3     e010    0    1    0
</code>```

The columns 'est' and 'est_name' are related to the ID and name of the rain gauges. The following columns are important to me and represent precipitation values on day 1, 2, and so on (in the exemple I kept just three days, but actually, I have 8 years of daily precipitation data).

I need to convert the polygons to raster, but one raster for each field (column p001, p002, and so on) of the table.

There is a simple way to convert polygons to raster with the function rasterize in R.

```<code>r_p001 <- rasterize(thiessen, r, field = thiessen$p001)
plot(r_p001)
writeRaster(r_p001, filename=".../raingauges/shp/r_p001.tif")
</code>```

The problem is that I need to set manually the field (column) of the table with the polygon values to be converted to raster. As I have about 2900 days (2900 columns with precipitation values for each rain gauge), it is impossible to do manually.

The documentation does not help to clarify how to automate this process and I did not find anything on the internet to help me.

Does anyone know how to automatically convert each field to raster and save as tif format?

答:
Here is an approach:

Example data

```<code>library(raster)
r <- raster(ncols=36, nrows=18)
p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
att <- data.frame(id=1:3, var1=10:12, var2=c(6,9,6))
pols <- spPolygons(p1, p2, p3, attr=att)
</code>```

The important thing is to have a field with a unique If your data do not have it, add it like this

```<code>pols$id <- 1:nrow(pols)
</code>```

Rasterize

```<code>r <- rasterize(pols, r, field='id')
</code>```

Create a layer for all other variables

```<code>x <- subs(r, data.frame(pols), by='id', which=2:ncol(pols), filename="rstr.grd")
x
#class       : RasterBrick
#dimensions  : 18, 36, 648, 2  (nrow, ncol, ncell, nlayers)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : rstr.grd
#names       : var1, var2
#min values  :   10,    6
#max values  :   12,    9
</code>```

An alternative is to keep one layer with Raster Attribute Table, that is quicker, but depending on your purpose, perhaps a less useful method:

```<code>r <- rasterize(pols, r, field='id')
f <- as.factor(r)
v <- levels(f)[[1]]

v <- cbind(v, data.frame(pols)[,-1])
levels(f) <- v
f
#class       : RasterLayer
#dimensions  : 18, 36, 648  (nrow, ncol, ncell)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : in memory
#names       : layer
#values      : 1, 3  (min, max)
#attributes  :
# ID var1 var2
#  1   10    6
#  2   11    9
#  3   12    6
</code>```

You can then do:

```<code>z <- deratify(f)
</code>```

To get the same result as in the first example

```<code>z
#class       : RasterBrick
#dimensions  : 18, 36, 648, 2  (nrow, ncol, ncell, nlayers)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : in memory
#names       : var1, var2
#min values  :   10,    6
#max values  :   12,    9
</code>```

Body:
I have a shapefile representing Thiessen polygons.

Each polygon is associated with many values of a table.

thiessen <- readOGR(dsn = getwd(), layer = poly)
OGR data source with driver: ESRI Shapefile
Source: ".../raingauges/shp", layer: "thiessen_pol"
with 10 features
It has 5 fields
head(thiessen)
  est est_name p001 p002 p003
0   2   borges    1    8    2
1   0     e018    2    4    3
2   5  starosa    5   15    1
3   6   delfim    4    2    2
4   1     e087    1    1    3
5   3     e010    0    1    0

The columns 'est' and 'est_name' are related to the ID and name of the rain gauges. The following columns are important to me and represent precipitation values on day 1, 2, and so on (in the exemple I kept just three days, but actually, I have 8 years of daily precipitation data).

I need to convert the polygons to raster, but one raster for each field (column p001, p002, and so on) of the table.

There is a simple way to convert polygons to raster with the function rasterize in R.

r_p001 <- rasterize(thiessen, r, field = thiessen$p001)
plot(r_p001)
writeRaster(r_p001, filename=".../raingauges/shp/r_p001.tif")

The problem is that I need to set manually the field (column) of the table with the polygon values to be converted to raster. As I have about 2900 days (2900 columns with precipitation values for each rain gauge), it is impossible to do manually.

The documentation does not help to clarify how to automate this process and I did not find anything on the internet to help me.

Does anyone know how to automatically convert each field to raster and save as tif format?

Body:
Here is an approach:

Example data

library(raster)
r <- raster(ncols=36, nrows=18)
p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
att <- data.frame(id=1:3, var1=10:12, var2=c(6,9,6))
pols <- spPolygons(p1, p2, p3, attr=att)

The important thing is to have a field with a unique If your data do not have it, add it like this

pols$id <- 1:nrow(pols)

Rasterize

r <- rasterize(pols, r, field='id')

Create a layer for all other variables

x <- subs(r, data.frame(pols), by='id', which=2:ncol(pols), filename="rstr.grd")
x
#class       : RasterBrick
#dimensions  : 18, 36, 648, 2  (nrow, ncol, ncell, nlayers)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : rstr.grd
#names       : var1, var2
#min values  :   10,    6
#max values  :   12,    9

An alternative is to keep one layer with Raster Attribute Table, that is quicker, but depending on your purpose, perhaps a less useful method:

r <- rasterize(pols, r, field='id')
f <- as.factor(r)
v <- levels(f)[[1]]

v <- cbind(v, data.frame(pols)[,-1])
levels(f) <- v
f
#class       : RasterLayer
#dimensions  : 18, 36, 648  (nrow, ncol, ncell)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : in memory
#names       : layer
#values      : 1, 3  (min, max)
#attributes  :
# ID var1 var2
#  1   10    6
#  2   11    9
#  3   12    6

You can then do:

z <- deratify(f)

To get the same result as in the first example

z
#class       : RasterBrick
#dimensions  : 18, 36, 648, 2  (nrow, ncol, ncell, nlayers)
#resolution  : 10, 10  (x, y)
#extent      : -180, 180, -90, 90  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : in memory
#names       : var1, var2
#min values  :   10,    6
#max values  :   12,    9


问:
Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error
I am facing the below issue and am unable to build the application.

XXX has conflicting provisioning settings. XXX is automatically
  provisioned, but provisioning profile WildCard has been manually
  specified. Set the provisioning profile value to "Automatic" in the
  build settings editor, or switch to manual provisioning in the target
  editor. Code signing is required for product type 'Application' in SDK
  'iOS 10.0'

I am also unable to choose a particular profile.

How to resolve this issue?

答:
The Untick-tick (check-uncheck) "Automatically manage signing".) of Xcode checkboxes don't work for me (as many suggested on the top).

It happens with frameworks linked in your project.

Solution:

Find your framework or any other target that required signing.

Go to Build settings

Search Signing Identity

Set Don't code sign manually.


问:
Save data and close Tkinter window at the same time
So I am trying to get data from the user and then I want the gui window to close, and save the data into variables for my code right after they click "Enter". But the window just stays there. How do I get it to save the data, and the gui window to close at the same time?</p>

```<code>#pop up window
def show_entry_fields():
   global ModelNumber,PowerOutput,SerialNumber

   ModelNumber=e1.get()
   PowerOutput=e2.get()
   SerialNumber=e3.get()

master = Tk()
master.title("Model Information")

master.geometry("500x300")

master.iconbitmap("square.ico")

Label(master, text="Model Information").grid(row=0,column=1)
Label(master, text="Model Number ").grid(row=2)
Label(master, text="Power Output (w)").grid(row=3)
Label(master,text="Serial Number").grid(row=4)

e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)

e1.grid(row=2, column=1)
e2.grid(row=3, column=1)
e3.grid(row=4, column=1)

Button(master, text='Enter', command=show_entry_fields).grid(row=6,
column=1, sticky=W, pady=4)

mainloop()
master.withdraw()
</code>```

答:
I don't quite understand the question. It seems like all you need to do is create a function that does both actions.</p>

```<code>def save_and_quit()
    show_entry_fields()
    master.quit()

...
button = Button(master, text='Enter', command=save_and_quit)
button.grid(row=6, column=1, sticky=W, pady=4)
</code>```

Body:
So I am trying to get data from the user and then I want the gui window to close, and save the data into variables for my code right after they click "Enter". But the window just stays there. How do I get it to save the data, and the gui window to close at the same time?

#pop up window
def show_entry_fields():
   global ModelNumber,PowerOutput,SerialNumber

   ModelNumber=e1.get()
   PowerOutput=e2.get()
   SerialNumber=e3.get()

master = Tk()
master.title("Model Information")

master.geometry("500x300")

master.iconbitmap("square.ico")

Label(master, text="Model Information").grid(row=0,column=1)
Label(master, text="Model Number ").grid(row=2)
Label(master, text="Power Output (w)").grid(row=3)
Label(master,text="Serial Number").grid(row=4)

e1 = Entry(master)
e2 = Entry(master)
e3 = Entry(master)

e1.grid(row=2, column=1)
e2.grid(row=3, column=1)
e3.grid(row=4, column=1)

Button(master, text='Enter', command=show_entry_fields).grid(row=6,
column=1, sticky=W, pady=4)

mainloop()
master.withdraw()

Body:
I don't quite understand the question. It seems like all you need to do is create a function that does both actions.

def save_and_quit()
    show_entry_fields()
    master.quit()

...
button = Button(master, text='Enter', command=save_and_quit)
button.grid(row=6, column=1, sticky=W, pady=4)


问:
Export sql query result to csv from tableau
I use Tableau soft, i connected to amazon redshift via tableau and created query!
How this query result (10 000 000 obs) export to csv from tableau?

答:
you could do the following

calculate an aggregate

right mouse button

See data ...

"Complete Data" Option

"Export all" option


答:
Use the OfType<T>() method, which will result in EF doing an INNER JOIN to the specified T if your using TPT, or a filter based on the discriminator if your using TPH.

```<code>public TPerson Get<TPerson>(int PersonId) where TPerson : Person
{
    return ctx.People
              .OfType<TPerson>()
              .SingleOrDefault(x => x.PersonId == PersonId);
}
</code>```

And that will work just like you wanted:

```<code>Agent a = repository.Get<Agent>(5005);
</code>```

Title: Generics and Entity Framework: How do I return a different type depending on a column value

Body:
Use the OfType<T>() method, which will result in EF doing an INNER JOIN to the specified T if your using TPT, or a filter based on the discriminator if your using TPH.

public TPerson Get<TPerson>(int PersonId) where TPerson : Person
{
    return ctx.People
              .OfType<TPerson>()
              .SingleOrDefault(x => x.PersonId == PersonId);
}

And that will work just like you wanted:

Agent a = repository.Get<Agent>(5005);


问:
Android BLE, Can't connect to device
I'm making an application which has to talk to a BLE devices on Android.

I am running into issues establishing the connection to the BLE device.

Case 1) Scan:
During a scan after a device has been discovered and reported via

```<code>BluetoothLEScanCallback.onScanResult(...)
</code>```

I am attempting the connect via:

```<code>result.getDevice().connectGatt(...)
</code>```

Problem is on some devices I test this (namely HTC One M8 running Android 5.0.1 and HTC Desire 516 running Android 4.3) the connection process seems to fail, i.e. the callback

```<code>BluetoothGattCallback.onConnectionStateChange(....)
</code>```

is simply not called most of the time.
Now this is not a consistent behavior, sometimes it is sometimes it is not.

The second problem is that often if the connection is established
the

```<code>BluetoothGatt.discoverServices()
</code>```

call fails, i.e. the
    BluetoothGattCallback.onServicesDiscovered(...)
is also not called. I tried retrying the call a couple of times spaced by X number of milliseconds but it seems to consistently fail regardless of the number of attempts or spacing between them.

Case 2 Listening

The pretty much same thing happens when I attempt to simply "listen" for a device, again calling

```<code>BluetoothDevice device = BluetoothManager.getAdapter().getRemoteDevice(macAddress);
device.connectGatt(...)
</code>```

results often in the same situation.

In both cases I am having issue with Android most of the time, I have a Nexus 5 device on which that same code seems to work for the most part (sometimes the BT stack seems to fail to do its job)
A bit more disturbing that the iOS application we have has none of these problems.

Has anyone encountered these issues?
Any ideas how to address them?

答:
I encounter the same problem.  I connect to a Bluegigga BLE113 bluetooth 4.0 module.  My app is based on the BluetoothLeGatt Sample source.  My Samsung phone connects great, with no problems.  My LG V10 can't connect.  Except sometimes, when it will connect.  Mostly, it won't connect. onConnectionStateChange never gets called.  It is very frustrating, and I haven't been able to figure out the problem.

But I can connect my LG phone if I use NRF Connect, which seems to prove there is a programming solution.  But they don't release the source for NRF-Connect.

If anyone can expand of how to fix this, I would appreciate it.

Title: Android BLE, Can't connect to device

Body:
I'm making an application which has to talk to a BLE devices on Android.

I am running into issues establishing the connection to the BLE device.

Case 1) Scan:
During a scan after a device has been discovered and reported via

BluetoothLEScanCallback.onScanResult(...)

I am attempting the connect via:

result.getDevice().connectGatt(...)

Problem is on some devices I test this (namely HTC One M8 running Android 5.0.1 and HTC Desire 516 running Android 4.3) the connection process seems to fail, i.e. the callback

BluetoothGattCallback.onConnectionStateChange(....)

is simply not called most of the time.
Now this is not a consistent behavior, sometimes it is sometimes it is not.

The second problem is that often if the connection is established
the

BluetoothGatt.discoverServices()

call fails, i.e. the
    BluetoothGattCallback.onServicesDiscovered(...)
is also not called. I tried retrying the call a couple of times spaced by X number of milliseconds but it seems to consistently fail regardless of the number of attempts or spacing between them.

Case 2 Listening

The pretty much same thing happens when I attempt to simply "listen" for a device, again calling

BluetoothDevice device = BluetoothManager.getAdapter().getRemoteDevice(macAddress);
device.connectGatt(...)

results often in the same situation.

In both cases I am having issue with Android most of the time, I have a Nexus 5 device on which that same code seems to work for the most part (sometimes the BT stack seems to fail to do its job)
A bit more disturbing that the iOS application we have has none of these problems.

Has anyone encountered these issues?
Any ideas how to address them?


问:
C read a file, line by line to vector
I just started coding in C.
I have implemented a vector that seems to be working when i append strings to it,
but as soon as i read from the file i seem to get the last string again and again.
From what i can see it seems like it uses the same address and therfore i get the same line again and again.

But i can't seem to find a solution to the problem, hope you can help.

this is my vector structure:

```<code>void vector_init(Vector *vector){
    vector -> size = 0;
    vector -> capacity = 20;
    vector -> data = malloc(sizeof(void *) * vector -> capacity);
</code>```

}

and appending to vector:

```<code>void vector_push(Vector *vector, void *value){
    vector_double_capacity(vector);
    vector -> data[vector -> size ++] = value;
}
</code>```

and here is what i do in my main function:

```<code>int main(int argc, char *argv[]) {

    Vector someVector;
    vector_init(&someVector);

    FILE *fp;
    void *line = NULL;
    size_t len = 0;
    fp = fopen(argv[1], "r");

    if (fp == NULL)
        exit(EXIT_FAILURE);

    while (getline(&line, &len, fp) != -1){
        vector_push(&someVector, line);
    }

    fclose(fp);
    printf("\n");

    vector_push(&someVector, "blah");
    vector_push(&someVector, "test");
    vector_push(&someVector, "some random txt");
    vector_push(&someVector, "yollo");
    vector_push(&someVector, "something");

    for (int i = 0; i < someVector.size; i++)
        printf("\nvalue is : %s", (char *) vector_get_element(&someVector, i));

    return 0;
}
</code>```

My get_element function:

```<code>void *vector_get_element(const Vector *vector, size_t index){
    if (index >= vector -> size || index < 0){
        printf ("Index %d out of bounds", (int) index);
    }
    return vector -> data[index];
}
</code>```

here is my output:

```<code>value is : terminal
value is : terminal
value is : terminal
value is : terminal
value is : blah
value is : test
value is : some random txt
value is : yollo
value is : something
Process finished with exit code 0
</code>```

答:
You need to make a copy of the data you add to your vector.

```<code>void vector_push(Vector *vector, void *value, size_t bytes){
    vector_double_capacity(vector);
    void *copy = malloc(bytes);
    memcpy(copy, value, bytes);
    vector -> data[vector -> size ++] = copy;
}
</code>```

You'd have to call that with something like

```<code>vector_push(&someVector, line, 1 + strlen( line ) );
</code>```

to preserve your vector's apparent purpose of holding a pointer to any type of data and not just NUL-terminated strings.  You may also want to add a size field to your structure so you know how much data is pointed to.

Title: C read a file, line by line to vector

Body:
I just started coding in C.
I have implemented a vector that seems to be working when i append strings to it,
but as soon as i read from the file i seem to get the last string again and again.
From what i can see it seems like it uses the same address and therfore i get the same line again and again.

But i can't seem to find a solution to the problem, hope you can help.

this is my vector structure:

void vector_init(Vector *vector){
    vector -> size = 0;
    vector -> capacity = 20;
    vector -> data = malloc(sizeof(void *) * vector -> capacity);

}

and appending to vector:

void vector_push(Vector *vector, void *value){
    vector_double_capacity(vector);
    vector -> data[vector -> size ++] = value;
}

and here is what i do in my main function:

int main(int argc, char *argv[]) {

    Vector someVector;
    vector_init(&someVector);

    FILE *fp;
    void *line = NULL;
    size_t len = 0;
    fp = fopen(argv[1], "r");

    if (fp == NULL)
        exit(EXIT_FAILURE);

    while (getline(&line, &len, fp) != -1){
        vector_push(&someVector, line);
    }

    fclose(fp);
    printf("\n");

    vector_push(&someVector, "blah");
    vector_push(&someVector, "test");
    vector_push(&someVector, "some random txt");
    vector_push(&someVector, "yollo");
    vector_push(&someVector, "something");

    for (int i = 0; i < someVector.size; i++)
        printf("\nvalue is : %s", (char *) vector_get_element(&someVector, i));

    return 0;
}

My get_element function:

void *vector_get_element(const Vector *vector, size_t index){
    if (index >= vector -> size || index < 0){
        printf ("Index %d out of bounds", (int) index);
    }
    return vector -> data[index];
}

here is my output:

value is : terminal
value is : terminal
value is : terminal
value is : terminal
value is : blah
value is : test
value is : some random txt
value is : yollo
value is : something
Process finished with exit code 0

Body:
You need to make a copy of the data you add to your vector.

void vector_push(Vector *vector, void *value, size_t bytes){
    vector_double_capacity(vector);
    void *copy = malloc(bytes);
    memcpy(copy, value, bytes);
    vector -> data[vector -> size ++] = copy;
}

You'd have to call that with something like

vector_push(&someVector, line, 1 + strlen( line ) );

to preserve your vector's apparent purpose of holding a pointer to any type of data and not just NUL-terminated strings.  You may also want to add a size field to your structure so you know how much data is pointed to.


问:
AttachNotSupportedException when trying to start a JFR recording
I'm receiving AttachNotSupportedException when trying to start a JFR recording.
It was working normally, until now.

```<code>jcmd 3658 JFR.start maxsize=100M filename=jfr_1.jfr dumponexit=true settings=profile
</code>```

Output:

```<code>3658:
com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded
        at sun.tools.attach.LinuxVirtualMachine.<init>(LinuxVirtualMachine.java:106)
        at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
        at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:208)
</code>```

What might be happening?

SO: Oracle Linux Server release 6.7

```<code>$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
</code>```

答: Another possibility: your app is running under systemd with 'PrivateTmp=yes'. This prevents the /tmp/.java_pid1234 file from being found.</p>

Body:
I'm receiving AttachNotSupportedException when trying to start a JFR recording.
It was working normally, until now.

jcmd 3658 JFR.start maxsize=100M filename=jfr_1.jfr dumponexit=true settings=profile

Output:

3658:
com.sun.tools.attach.AttachNotSupportedException: Unable to open socket file: target process not responding or HotSpot VM not loaded
        at sun.tools.attach.LinuxVirtualMachine.<init>(LinuxVirtualMachine.java:106)
        at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:63)
        at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:208)

What might be happening?

SO: Oracle Linux Server release 6.7

$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)


问:
How to append context root in IBM HTTP Proxy for Liberty Server
I have a Java EAR application deployed to a couple of liberty 16.x application servers, and have one IBM HTTP Proxy server (Apache) running in front of it acting as the load balancer and HTTPS proxy. I want to have our intranet users simply enter in an easy to remember URL like https://product-aa and then be redirected to https://server-aa:8443/EarApplication, without needing to have them manually add the context root in the URL.

I'm trying to figure out the best way to achieve this.

答:
First, register product-aa in DNS as a CNAME for server-aa

Then append to httpd.conf:

```<code>NameVirtualHost *:80
<virtualhost *:80>
  ServerName server-aa
</virtualhost>
<virtualhost *:80>
  ServerName product-aa
  RedirectMatch ^/$ /EarApplication
  # ... or http://server-aa/EarApplication
</virtualhost>
</code>```

Body:
First, register product-aa in DNS as a CNAME for server-aa

Then append to httpd.conf:

NameVirtualHost *:80
<virtualhost *:80>
  ServerName server-aa
</virtualhost>
<virtualhost *:80>
  ServerName product-aa
  RedirectMatch ^/$ /EarApplication
  # ... or http://server-aa/EarApplication
</virtualhost>