问:
How to send notifications to users when a message is posted in Android
I wanted to send notification to users as soon as a message is posted by the admin.

What I'm facing currently:

Every time I open the app, notification sound arrives even though there are no new messages ( Is it because the code is written in onCreate() method?)

When I click on the notification, I'm redirected to the MainActivity correctly and again the notification sound comes. Its kind of annoying :(

I wrote the Notification code in addChildEventListener. Can anyone guide me in fixing the above mentioned things. Please review my following code.

Code for MainActivity of my app.

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

    ...

    // [Start of onCreate Method]
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ...

        // NOTIFICATIONS
        mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.bcm_logo)
                        .setContentTitle("BCM")
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setContentText("You have a new message")
                        .setAutoCancel(true); // clear notification when clicked

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        mBuilder.setContentIntent(pi);

        messagesDatabaseReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG, "Child ADDED !");

                Log.d(TAG, "D: " + dataSnapshot);

                    mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    mNotifyMgr.notify(mNotificationId, mBuilder.build());

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG, "Child Changed");
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Log.d(TAG, "CHILD REMOVED!");
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG, "Child Moved");
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, "Child Cancelled");
            }
        });
    }    // [End of onCreate Method]

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            if (resultCode == RESULT_OK) {

                Log.d(TAG, "User Signed in");

            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }

        }
    }

    ...

    // WHAT IF SIGNED IN
    private void onSignedInitialize(String userDisplayName) {
        mUserName = userDisplayName;
        Message.setSenderName(mUserName);
        attachDatabaseReadListener();
    }

    // ATTACH AND DETACH THE DATABASE READ LISTENERS
    private void attachDatabaseReadListener() {
        if (childEventListener == null) {
            childEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Message message = dataSnapshot.getValue(Message.class);
                    mMessageAdapter.add(message);
                }

                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                public void onChildRemoved(DataSnapshot dataSnapshot) {
                }

                public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                }

                public void onCancelled(DatabaseError databaseError) {
                }
            };
            messagesDatabaseReference.addChildEventListener(childEventListener);
        }
    }
    ...
} // [END of Main Activity]
</code>```

答:
The Problem here is that onChildAdded() will be called with every single Message from your Database as soon as you attach the Listener to your DatabaseReference. As there is no start or end of the Datastream from your Database there is no way to determine when an Message is "new" and when to show a notification. There are two possible Solutions:

1. Use a ValueEventListener:

```<code>    databaseReference.addValueEventListener(new ValueEventListener() {

            Boolean showNotification = false;

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if(showNotification) {
                    mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    mNotifyMgr.notify(mNotificationId, mBuilder.build());
                }
                //use your Data here
                showNotification = true;
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

The downside of this approach is that you will get the whole list of Messages everytime there is a new Message.

2. Use a Timestamp in your data structure:
Save the Timestamp of Creation inside your Message.
Then you can extend your existing ChildEventListener like this:

```<code>messagesDatabaseReference.addChildEventListener(
new ChildEventListener() {

    //set to the time when the listener is created
    private long attachTime = System.currentTimeMillis();

    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG, "Child ADDED !");
        Message message = dataSnapshot.getValue(Message.class);
        //if the message is newer then then the creation of the ChildEventListener -> show notification
        if(message.getCreationTime > attachTime) {
            mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mNotifyMgr.notify(mNotificationId, mBuilder.build());
            attachTime = message.getCreationTime;
        }
        //use your Data here
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG, "Child Changed");
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        Log.d(TAG, "CHILD REMOVED!");
    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG, "Child Moved");
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d(TAG, "Child Cancelled");
    }
});
</code>```

Full Example:

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

    public static final String TAG = "MessagesActivity";
    private static final int mNotificationId = 1;
    private DatabaseReference messagesDatabaseReference;
    private ChildEventListener childEventListener;
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotifyMgr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.bcm_logo)
                        .setContentTitle("BCM")
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setContentText("You have a new message")
                        .setAutoCancel(true); // clear notification when clicked

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pi);
    }

    @Override
    public void onResume() {
        super.onResume();
        messagesDatabaseReference = FirebaseDatabase.getInstance().getReference();
        attachDatabaseReadListener();
    }

    @Override
    public void onPause() {
        super.onPause();
        detachDatabaseReadListener();
    }

    private void attachDatabaseReadListener() {
        if (childEventListener == null) {
            childEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Log.d(TAG, "Child ADDED !");
                    Message message = dataSnapshot.getValue(Message.class);
                    //if the message is newer then then the creation of the ChildEventListener -> show notification
                    if(message.getCreationTime > attachTime) {
                        mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        mNotifyMgr.notify(mNotificationId, mBuilder.build());

                    }
                    mMessageAdapter.add(message);
                }

                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                public void onChildRemoved(DataSnapshot dataSnapshot) {
                }

                public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                }

                public void onCancelled(DatabaseError databaseError) {
                }
            };
            messagesDatabaseReference.addChildEventListener(childEventListener);
        }
    }

    private void detachDatabaseReadListener() {
        messagesDatabaseReference.removeEventListener(childEventListener);
    }
}
</code>```

Body:
I wanted to send notification to users as soon as a message is posted by the admin.

What I'm facing currently:

Every time I open the app, notification sound arrives even though there are no new messages ( Is it because the code is written in onCreate() method?)

When I click on the notification, I'm redirected to the MainActivity correctly and again the notification sound comes. Its kind of annoying :(

I wrote the Notification code in addChildEventListener. Can anyone guide me in fixing the above mentioned things. Please review my following code.

Code for MainActivity of my app.

public class MainActivity extends AppCompatActivity {

    ...

    // [Start of onCreate Method]
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ...

        // NOTIFICATIONS
        mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this)
                        .setSmallIcon(R.drawable.bcm_logo)
                        .setContentTitle("BCM")
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setContentText("You have a new message")
                        .setAutoCancel(true); // clear notification when clicked

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
        mBuilder.setContentIntent(pi);

        messagesDatabaseReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG, "Child ADDED !");

                Log.d(TAG, "D: " + dataSnapshot);

                    mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    mNotifyMgr.notify(mNotificationId, mBuilder.build());

            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG, "Child Changed");
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                Log.d(TAG, "CHILD REMOVED!");
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                Log.d(TAG, "Child Moved");
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d(TAG, "Child Cancelled");
            }
        });
    }    // [End of onCreate Method]

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            if (resultCode == RESULT_OK) {

                Log.d(TAG, "User Signed in");

            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }

        }
    }

    ...

    // WHAT IF SIGNED IN
    private void onSignedInitialize(String userDisplayName) {
        mUserName = userDisplayName;
        Message.setSenderName(mUserName);
        attachDatabaseReadListener();
    }

    // ATTACH AND DETACH THE DATABASE READ LISTENERS
    private void attachDatabaseReadListener() {
        if (childEventListener == null) {
            childEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Message message = dataSnapshot.getValue(Message.class);
                    mMessageAdapter.add(message);
                }

                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                public void onChildRemoved(DataSnapshot dataSnapshot) {
                }

                public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                }

                public void onCancelled(DatabaseError databaseError) {
                }
            };
            messagesDatabaseReference.addChildEventListener(childEventListener);
        }
    }
    ...
} // [END of Main Activity]

Body:
The Problem here is that onChildAdded() will be called with every single Message from your Database as soon as you attach the Listener to your DatabaseReference. As there is no start or end of the Datastream from your Database there is no way to determine when an Message is "new" and when to show a notification. There are two possible Solutions:

1. Use a ValueEventListener:

    databaseReference.addValueEventListener(new ValueEventListener() {

            Boolean showNotification = false;

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if(showNotification) {
                    mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    mNotifyMgr.notify(mNotificationId, mBuilder.build());
                }
                //use your Data here
                showNotification = true;
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

The downside of this approach is that you will get the whole list of Messages everytime there is a new Message.

2. Use a Timestamp in your data structure:
Save the Timestamp of Creation inside your Message.
Then you can extend your existing ChildEventListener like this:

messagesDatabaseReference.addChildEventListener(
new ChildEventListener() {

    //set to the time when the listener is created
    private long attachTime = System.currentTimeMillis();

    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG, "Child ADDED !");
        Message message = dataSnapshot.getValue(Message.class);
        //if the message is newer then then the creation of the ChildEventListener -> show notification
        if(message.getCreationTime > attachTime) {
            mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            mNotifyMgr.notify(mNotificationId, mBuilder.build());
            attachTime = message.getCreationTime;
        }
        //use your Data here
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG, "Child Changed");
    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {
        Log.d(TAG, "CHILD REMOVED!");
    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
        Log.d(TAG, "Child Moved");
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d(TAG, "Child Cancelled");
    }
});

Full Example:

public class MainActivity extends AppCompatActivity {

    public static final String TAG = "MessagesActivity";
    private static final int mNotificationId = 1;
    private DatabaseReference messagesDatabaseReference;
    private ChildEventListener childEventListener;
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotifyMgr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.bcm_logo)
                        .setContentTitle("BCM")
                        .setDefaults(Notification.DEFAULT_SOUND)
                        .setContentText("You have a new message")
                        .setAutoCancel(true); // clear notification when clicked

        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pi);
    }

    @Override
    public void onResume() {
        super.onResume();
        messagesDatabaseReference = FirebaseDatabase.getInstance().getReference();
        attachDatabaseReadListener();
    }

    @Override
    public void onPause() {
        super.onPause();
        detachDatabaseReadListener();
    }

    private void attachDatabaseReadListener() {
        if (childEventListener == null) {
            childEventListener = new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    Log.d(TAG, "Child ADDED !");
                    Message message = dataSnapshot.getValue(Message.class);
                    //if the message is newer then then the creation of the ChildEventListener -> show notification
                    if(message.getCreationTime > attachTime) {
                        mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        mNotifyMgr.notify(mNotificationId, mBuilder.build());

                    }
                    mMessageAdapter.add(message);
                }

                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                public void onChildRemoved(DataSnapshot dataSnapshot) {
                }

                public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                }

                public void onCancelled(DatabaseError databaseError) {
                }
            };
            messagesDatabaseReference.addChildEventListener(childEventListener);
        }
    }

    private void detachDatabaseReadListener() {
        messagesDatabaseReference.removeEventListener(childEventListener);
    }
}


来源: stackexchange

问:
NodeJS Identify once
I want variable identify once so;

├── project_folder

|   ├── app.js //main file

|   └── router/index.js

app.js

```<code>const express = require('express');
const app = express();
const path = require('path');
const router = require('./router/index');
const mysql = require('mysql');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use('/',router);

app.listen( 8000, function(){
    console.log( 'Server listening on * 8000' );
});
</code>```

index.js

```<code>//other codes
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err){
    if(err)
        console.log(err);
});
//other codes
</code>```

error : mysql is not defined

I don't want identify mysql and other variables again.

How can I solve?

Thank you for your helping.

SOLVED

Create a settings.js
Define settings in file

EXAMPLE

```<code>const testSettings = "test Settings...";

module.exports = {
    test:testSettings
}
</code>```

In a file you want
require('./settings');

Using: settings.test

答:
You just need to require('mysql') in you index.js file.

And in your app.js file, as you have already imported this file(index.js), this will lead to the execution of this file as soon as it is required by you in app.js file.

Therefore, you need not require('mysql') in the app.js file as this is the way NODE intends to work (modularizes the code).

it must be required in each file where you us mysql

```<code>const mysql = require('mysql');

    const connection =

 mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : 'root',
        database : 'wordpress'
    });

    connection.connect(function(err) {
        if (err) {
            console.log(err);
        }
    });
</code>```

If you create any functions inside this index.js file which are required in other modules, you can module.exports them.

Edit:

Refer to this link for in-depth explanation on modules: https://nodejs.org/api/modules.html

ContentLicense: CC BY-SA 3.0

Title: NodeJS Identify once

Body:
I want variable identify once so;

├── project_folder

|   ├── app.js //main file

|   └── router/index.js

app.js

const express = require('express');
const app = express();
const path = require('path');
const router = require('./router/index');
const mysql = require('mysql');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use('/',router);

app.listen( 8000, function(){
    console.log( 'Server listening on * 8000' );
});

index.js

//other codes
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err){
    if(err)
        console.log(err);
});
//other codes

error : mysql is not defined

I don't want identify mysql and other variables again.

How can I solve?

Thank you for your helping.

SOLVED

Create a settings.js
Define settings in file

EXAMPLE

const testSettings = "test Settings...";

module.exports = {
    test:testSettings
}

In a file you want
require('./settings');

Using: settings.test

Body:
You just need to require('mysql') in you index.js file.

And in your app.js file, as you have already imported this file(index.js), this will lead to the execution of this file as soon as it is required by you in app.js file.

Therefore, you need not require('mysql') in the app.js file as this is the way NODE intends to work (modularizes the code).

it must be required in each file where you us mysql

const mysql = require('mysql');

    const connection =

 mysql.createConnection({
        host     : 'localhost',
        user     : 'root',
        password : 'root',
        database : 'wordpress'
    });

    connection.connect(function(err) {
        if (err) {
            console.log(err);
        }
    });

If you create any functions inside this index.js file which are required in other modules, you can module.exports them.

Edit:

Refer to this link for in-depth explanation on modules: https://nodejs.org/api/modules.html


问:
Cython Typing List of Strings
I'm trying to use cython to improve the performance of a loop, but I'm running
into some issues declaring the types of the inputs.

How do I include a field in my typed struct which is a string that can be
either 'front' or 'back'

I have a np.recarray that looks like the following (note the length of the
recarray is unknown as compile time)

```<code>import numpy as np
weights = np.recarray(4, dtype=[('a', np.int64),  ('b', np.str_, 5), ('c', np.float64)])
weights[0] = (0, "front", 0.5)
weights[1] = (0, "back", 0.5)
weights[2] = (1, "front", 1.0)
weights[3] = (1, "back", 0.0)
</code>```

as well as inputs of a list of strings and a pandas.Timestamp

```<code>import pandas as pd
ts = pd.Timestamp("2015-01-01")
contracts = ["CLX16", "CLZ16"]
</code>```

I am trying to cythonize the following loop

```<code>def ploop(weights, contracts, timestamp):
    cwts = []
    for gen_num, position, weighting in weights:
        if weighting != 0:
            if position == "front":
                cntrct_idx = gen_num
            elif position == "back":
                cntrct_idx = gen_num + 1
            else:
                raise ValueError("transition.columns must contain "
                                 "'front' or 'back'")
            cwts.append((gen_num, contracts[cntrct_idx], weighting, timestamp))
    return cwts
</code>```

My attempt involved typing the weights input as a struct in cython,
in a file struct_test.pyx as follows

```<code>import numpy as np
cimport numpy as np

cdef packed struct tstruct:
    np.int64_t gen_num
    char[5] position
    np.float64_t weighting

def cloop(tstruct[:] weights_array, contracts, timestamp):
    cdef tstruct weights
    cdef int i
    cdef int cntrct_idx

    cwts = []
    for k in xrange(len(weights_array)):
        w = weights_array[k]
        if w.weighting != 0:
            if w.position == "front":
                cntrct_idx = w.gen_num
            elif w.position == "back":
                cntrct_idx = w.gen_num + 1
            else:
                raise ValueError("transition.columns must contain "
                                 "'front' or 'back'")
            cwts.append((w.gen_num, contracts[cntrct_idx], w.weighting,
                         timestamp))
    return cwts
</code>```

But I am receiving runtime errors, which I believe are related to the
char[5] position.

```<code>import pyximport
pyximport.install()
import struct_test

struct_test.cloop(weights, contracts, ts)

ValueError: Does not understand character buffer dtype format string ('w')
</code>```

In addition I am a bit unclear how I would go about typing contracts as well
as timestamp.

答:
Your ploop (without the timestamp variable) produces:

```<code>In [226]: ploop(weights, contracts)
Out[226]: [(0, 'CLX16', 0.5), (0, 'CLZ16', 0.5), (1, 'CLZ16', 1.0)]
</code>```

Equivalent function without a loop:

```<code>def ploopless(weights, contracts):
    arr_contracts = np.array(contracts) # to allow array indexing
    wgts1 = weights[weights['c']!=0]
    mask = wgts1['b']=='front'
    wgts1['b'][mask] = arr_contracts[wgts1['a'][mask]]
    mask = wgts1['b']=='back'
    wgts1['b'][mask] = arr_contracts[wgts1['a'][mask]+1]
    return wgts1.tolist()

In [250]: ploopless(weights, contracts)
Out[250]: [(0, 'CLX16', 0.5), (0, 'CLZ16', 0.5), (1, 'CLZ16', 1.0)]
</code>```

I'm taking advantage of the fact that returned list of tuples has same (int, str, int) layout as the input weight array.  So I'm just making a copy of weights and replacing selected values of the b field.

Note that I use the field selection index before the mask one.  The boolean mask produces a copy, so we have to careful about indexing order.

I'm guessing that loop-less array version will be competitive in time with the cloop (on realistic arrays).  The string and list operations in cloop probably limit its speedup.

Title: Cython Typing List of Strings

Body:
I'm trying to use cython to improve the performance of a loop, but I'm running
into some issues declaring the types of the inputs.

How do I include a field in my typed struct which is a string that can be
either 'front' or 'back'

I have a np.recarray that looks like the following (note the length of the
recarray is unknown as compile time)

import numpy as np
weights = np.recarray(4, dtype=[('a', np.int64),  ('b', np.str_, 5), ('c', np.float64)])
weights[0] = (0, "front", 0.5)
weights[1] = (0, "back", 0.5)
weights[2] = (1, "front", 1.0)
weights[3] = (1, "back", 0.0)

as well as inputs of a list of strings and a pandas.Timestamp

import pandas as pd
ts = pd.Timestamp("2015-01-01")
contracts = ["CLX16", "CLZ16"]

I am trying to cythonize the following loop

def ploop(weights, contracts, timestamp):
    cwts = []
    for gen_num, position, weighting in weights:
        if weighting != 0:
            if position == "front":
                cntrct_idx = gen_num
            elif position == "back":
                cntrct_idx = gen_num + 1
            else:
                raise ValueError("transition.columns must contain "
                                 "'front' or 'back'")
            cwts.append((gen_num, contracts[cntrct_idx], weighting, timestamp))
    return cwts

My attempt involved typing the weights input as a struct in cython,
in a file struct_test.pyx as follows

import numpy as np
cimport numpy as np

cdef packed struct tstruct:
    np.int64_t gen_num
    char[5] position
    np.float64_t weighting

def cloop(tstruct[:] weights_array, contracts, timestamp):
    cdef tstruct weights
    cdef int i
    cdef int cntrct_idx

    cwts = []
    for k in xrange(len(weights_array)):
        w = weights_array[k]
        if w.weighting != 0:
            if w.position == "front":
                cntrct_idx = w.gen_num
            elif w.position == "back":
                cntrct_idx = w.gen_num + 1
            else:
                raise ValueError("transition.columns must contain "
                                 "'front' or 'back'")
            cwts.append((w.gen_num, contracts[cntrct_idx], w.weighting,
                         timestamp))
    return cwts

But I am receiving runtime errors, which I believe are related to the
char[5] position.

import pyximport
pyximport.install()
import struct_test

struct_test.cloop(weights, contracts, ts)

ValueError: Does not understand character buffer dtype format string ('w')

In addition I am a bit unclear how I would go about typing contracts as well
as timestamp.

Body:
Your ploop (without the timestamp variable) produces:

In [226]: ploop(weights, contracts)
Out[226]: [(0, 'CLX16', 0.5), (0, 'CLZ16', 0.5), (1, 'CLZ16', 1.0)]

Equivalent function without a loop:

def ploopless(weights, contracts):
    arr_contracts = np.array(contracts) # to allow array indexing
    wgts1 = weights[weights['c']!=0]
    mask = wgts1['b']=='front'
    wgts1['b'][mask] = arr_contracts[wgts1['a'][mask]]
    mask = wgts1['b']=='back'
    wgts1['b'][mask] = arr_contracts[wgts1['a'][mask]+1]
    return wgts1.tolist()

In [250]: ploopless(weights, contracts)
Out[250]: [(0, 'CLX16', 0.5), (0, 'CLZ16', 0.5), (1, 'CLZ16', 1.0)]

I'm taking advantage of the fact that returned list of tuples has same (int, str, int) layout as the input weight array.  So I'm just making a copy of weights and replacing selected values of the b field.

Note that I use the field selection index before the mask one.  The boolean mask produces a copy, so we have to careful about indexing order.

I'm guessing that loop-less array version will be competitive in time with the cloop (on realistic arrays).  The string and list operations in cloop probably limit its speedup.


问:
recursive xml schema generation
I have an xml with a recursive element such as in the example below. A contains a sequence of B elements. Each B element contain a C, D, E and F element. Each F except the last one in the sequence contains a B element.

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<A>
  <B>
    <C></C>
    <D></D>
    <E></E>
          <F>
            <B>
              <C></C>
              <D></D>
              <E></E>
                    <F>
                      <B>
                        <C></C>
                        <D></D>
                        <E></E>
                        <F></F>
                      </B>
                    </F>
           </B>
        </F>
   </B>
</A>
</code>```

When I generate a schema for this xml using an online generator I get a really long schema file. Is there no way to write a shorter recursive schema for this xml?

答:
Of course a recursive schema can be written. For any instance document, there's any number of schemas that can be used to describe it accurately, but the difficult thing for an automatic schema generator is to spot the patterns that describe it elegantly: that is, to guess what other instance documents you might want the schema to accept as well.

The typical way to write a recursive schema is to use named global types (though it can also be done with named global element declarations). Something like:

```<code><xs:element name="A" type="A-type"/>

<xs:complexType name="A-type">
  <xs:sequence>
    <xs:element ref="A" minOccurs="0"/>
  </xs:sequence>
</xs:complexType>
</code>```

Title: recursive xml schema generation

Body:
I have an xml with a recursive element such as in the example below. A contains a sequence of B elements. Each B element contain a C, D, E and F element. Each F except the last one in the sequence contains a B element.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

    <C></C>
    <D></D>
    <E></E>
          <F>

              <C></C>
              <D></D>
              <E></E>
                    <F>

                        <C></C>
                        <D></D>
                        <E></E>
                        <F></F>

                    </F>

        </F>

When I generate a schema for this xml using an online generator I get a really long schema file. Is there no way to write a shorter recursive schema for this xml?

Body:
Of course a recursive schema can be written. For any instance document, there's any number of schemas that can be used to describe it accurately, but the difficult thing for an automatic schema generator is to spot the patterns that describe it elegantly: that is, to guess what other instance documents you might want the schema to accept as well.

The typical way to write a recursive schema is to use named global types (though it can also be done with named global element declarations). Something like:

<xs:element name="A" type="A-type"/>

<xs:complexType name="A-type">
  <xs:sequence>
    <xs:element ref="A" minOccurs="0"/>
  </xs:sequence>
</xs:complexType>


问:
C# append object to xml file using serialization
I am trying append a serialized object to an existing xml file beneath the root element, which I thought would be simple but is proving to be a little challenging.

The problem is in the AddShortcut method but I added some more code for completeness.

I believe what I need to do is:

load the file into an XmlDocument.

navigate to the node I want to append beneath (here the node name is Shortcuts).

create some type of writer and then serialize the object.

save the XmlDocument.

The trouble is in steps 2 and 3. I have tried different variations but I think using XPathNavigator somehow to find the "root" node to append under is a step in the right direction.

I have also looked at almost every question on Stack Overflow on the subject.

Any suggestions welcome. Here is my code

```<code>class XmlEngine
{
   public string FullPath { get; set; } // the full path to the xmlDocument
   private readonly XmlDocument xDoc;

   public XmlEngine(string fullPath, string startElement, string[] rElements)
   {
      FullPath = fullPath;
      xDoc = new XmlDocument();
      CreateXmlFile(FullPath, startElement, rElements);
   }

   public void CreateXmlFile(string path, string startElement, string[] rElements)
   {
     try
     {
       if (!File.Exists(path))
       {
         // create a txt writer
         XmlTextWriter wtr = new XmlTextWriter(path, System.Text.Encoding.UTF8);

         // make sure the file is well formatted
         wtr.Formatting = Formatting.Indented;

         wtr.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
         wtr.WriteStartElement(startElement);
         wtr.Close();

         // write the top level root elements
         writeRootElements(path, rElements);
       }
     }
     catch (Exception ex)
     {
       Console.WriteLine("Error: " + ex.Message);
       Console.WriteLine("Could not create file: " + path);
     }
  }

  public void AddShortcut(Shortcut s)
  {
     xDoc.Load(FullPath);
     rootNode = xDoc.AppendChild(xDoc.CreateElement("Shortcuts"));

     var serializer = new XmlSerializer(s.GetType());

     using (var writer = new StreamWriter(FullPath, true))
     {
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.OmitXmlDeclaration = true;

        serializer.Serialize(writer, s);
     }

     xDoc.Save(FullPath);

  }

}
</code>```

答:
This code sample worked for me:

xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Launchpad>
  <Shortcuts>
    <Shortcut Id="1">
      <Type>Folder</Type>
      <FullPath>C:\SomePath</FullPath>
      <Name>SomeFolderName</Name>
    </Shortcut>
  </Shortcuts>
</Launchpad>
</code>```

Method:

```<code>public void AddShortcut(Shortcut s)
{
   xDoc.Load(FullPath);
   var rootNode = xDoc.GetElementsByTagName("Shortcuts")[0];
   var nav = rootNode.CreateNavigator();
   var emptyNamepsaces = new XmlSerializerNamespaces(new[] {
       XmlQualifiedName.Empty
   });

   using (var writer = nav.AppendChild())
   {
      var serializer = new XmlSerializer(s.GetType());
      writer.WriteWhitespace("");
      serializer.Serialize(writer, s, emptyNamepsaces);
      writer.Close();
   }
   xDoc.Save(FullPath);
}
</code>```

Body:
I am trying append a serialized object to an existing xml file beneath the root element, which I thought would be simple but is proving to be a little challenging.

The problem is in the AddShortcut method but I added some more code for completeness.

I believe what I need to do is:

load the file into an XmlDocument.

navigate to the node I want to append beneath (here the node name is Shortcuts).

create some type of writer and then serialize the object.

save the XmlDocument.

The trouble is in steps 2 and 3. I have tried different variations but I think using XPathNavigator somehow to find the "root" node to append under is a step in the right direction.

I have also looked at almost every question on Stack Overflow on the subject.

Any suggestions welcome. Here is my code

class XmlEngine
{
   public string FullPath { get; set; } // the full path to the xmlDocument
   private readonly XmlDocument xDoc;

   public XmlEngine(string fullPath, string startElement, string[] rElements)
   {
      FullPath = fullPath;
      xDoc = new XmlDocument();
      CreateXmlFile(FullPath, startElement, rElements);
   }

   public void CreateXmlFile(string path, string startElement, string[] rElements)
   {
     try
     {
       if (!File.Exists(path))
       {
         // create a txt writer
         XmlTextWriter wtr = new XmlTextWriter(path, System.Text.Encoding.UTF8);

         // make sure the file is well formatted
         wtr.Formatting = Formatting.Indented;

         wtr.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
         wtr.WriteStartElement(startElement);
         wtr.Close();

         // write the top level root elements
         writeRootElements(path, rElements);
       }
     }
     catch (Exception ex)
     {
       Console.WriteLine("Error: " + ex.Message);
       Console.WriteLine("Could not create file: " + path);
     }
  }

  public void AddShortcut(Shortcut s)
  {
     xDoc.Load(FullPath);
     rootNode = xDoc.AppendChild(xDoc.CreateElement("Shortcuts"));

     var serializer = new XmlSerializer(s.GetType());

     using (var writer = new StreamWriter(FullPath, true))
     {
        XmlWriterSettings ws = new XmlWriterSettings();
        ws.OmitXmlDeclaration = true;

        serializer.Serialize(writer, s);
     }

     xDoc.Save(FullPath);

  }

}

Body:
This code sample worked for me:

xml:

<?xml version="1.0" encoding="UTF-8"?>
<Launchpad>
  <Shortcuts>
    <Shortcut Id="1">
      <Type>Folder</Type>
      <FullPath>C:\SomePath</FullPath>
      <Name>SomeFolderName</Name>
    </Shortcut>
  </Shortcuts>
</Launchpad>

Method:

public void AddShortcut(Shortcut s)
{
   xDoc.Load(FullPath);
   var rootNode = xDoc.GetElementsByTagName("Shortcuts")[0];
   var nav = rootNode.CreateNavigator();
   var emptyNamepsaces = new XmlSerializerNamespaces(new[] {
       XmlQualifiedName.Empty
   });

   using (var writer = nav.AppendChild())
   {
      var serializer = new XmlSerializer(s.GetType());
      writer.WriteWhitespace("");
      serializer.Serialize(writer, s, emptyNamepsaces);
      writer.Close();
   }
   xDoc.Save(FullPath);
}


问:
PHP MySQL Query Where x = $variable from function
Why is this not working:

```<code>function listOrderComments ($factnr){
global $connection;

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
</code>```

When I echo $factnr I get "123" back.

When I uncommented //$factnr = 123; my function is working.

Looked everywhere for a solution. check the type $factnr is (string).

答:
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.

Here is an example of the code you would use.

```<code><?php

 // START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';

try
 {

 $db = new PDO($dsn, $uname, $pass);

 $db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
 error_reporting(0);
 } catch (PDOException $ex)
 {
 echo "Database error:" . $ex->getMessage();
 }

// END ESTABLISHING CONNECTION - CONNECTION IS MADE.

 $factnr = "123" // or where-ever you get your input from.

 $query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";

 $statement = $db->prepare($query);

 // The values you wish to put in.
 $statementInputs = array("factnr" => $factnr);

 $statement->execute($statementInputs);

 //Returns results as an associative array.
 $result = $statement->fetchAll(PDO::FETCH_ASSOC);

 $statement->closeCursor();

 //Shows array of results.
 print_r($result);
 ?>
</code>```

Body:
Why is this not working:

function listOrderComments ($factnr){
global $connection;

//$factnr = 123; //or $factnr = "123"; (Both work)

$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);

When I echo $factnr I get "123" back.

When I uncommented //$factnr = 123; my function is working.

Looked everywhere for a solution. check the type $factnr is (string).

Body:
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.

Here is an example of the code you would use.

<?php

 // START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';

try
 {

 $db = new PDO($dsn, $uname, $pass);

 $db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
 error_reporting(0);
 } catch (PDOException $ex)
 {
 echo "Database error:" . $ex->getMessage();
 }

// END ESTABLISHING CONNECTION - CONNECTION IS MADE.

 $factnr = "123" // or where-ever you get your input from.

 $query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";

 $statement = $db->prepare($query);

 // The values you wish to put in.
 $statementInputs = array("factnr" => $factnr);

 $statement->execute($statementInputs);

 //Returns results as an associative array.
 $result = $statement->fetchAll(PDO::FETCH_ASSOC);

 $statement->closeCursor();

 //Shows array of results.
 print_r($result);
 ?>


问:
get the value of JSON parameter c#
I'm trying to get the id parameter from the json below without success, using c#. It's a double array (users/warings)

```<code>JSON:
contents = "{\"users\":[{\"id\":64,\"username\":\"100146\",\"firstname\":\"NAME\",\"lastname\":\"LASTNAME PROFILI\",\"department\":\"\",\"firstaccess\":0,\"lastaccess\":0"}],\"warnings\":[]}"
</code>```

this is what I tried

```<code>JavaScriptSerializer serializer = new JavaScriptSerializer();
object obj1 = serializer.DeserializeObject(contents);
object obj2 = obj1["users"];
string id = obj2["id"];
</code>```

I get an error in obj2.
I don't want to create a class to parse the JSON into, just extract the id value from the 'users' array is enough

thanks for your time!

答:
Try using the dynamic rather than object type:</p>

```<code>dynamic d = JObject.Parse("{\"users\":[{\"id\":64,\"username\":\"100146\",\"firstname\":\"NAME\",\"lastname\":\"LASTNAME PROFILI\",\"department\":\"\",\"firstaccess\":0,\"lastaccess\":0"}],\"warnings\":[]}");

var usersCount = d.users.Count;
var warningsCount = d.warnings.Count;

var id = d.users[0].id;
</code>```

Title: get the value of JSON parameter c#

Body:
I'm trying to get the id parameter from the json below without success, using c#. It's a double array (users/warings)

JSON:
contents = "{\"users\":[{\"id\":64,\"username\":\"100146\",\"firstname\":\"NAME\",\"lastname\":\"LASTNAME PROFILI\",\"department\":\"\",\"firstaccess\":0,\"lastaccess\":0"}],\"warnings\":[]}"

this is what I tried

JavaScriptSerializer serializer = new JavaScriptSerializer();
object obj1 = serializer.DeserializeObject(contents);
object obj2 = obj1["users"];
string id = obj2["id"];

I get an error in obj2.
I don't want to create a class to parse the JSON into, just extract the id value from the 'users' array is enough

thanks for your time!

Body:
Try using the dynamic rather than object type:

dynamic d = JObject.Parse("{\"users\":[{\"id\":64,\"username\":\"100146\",\"firstname\":\"NAME\",\"lastname\":\"LASTNAME PROFILI\",\"department\":\"\",\"firstaccess\":0,\"lastaccess\":0"}],\"warnings\":[]}");

var usersCount = d.users.Count;
var warningsCount = d.warnings.Count;

var id = d.users[0].id;


问:
No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription
I’m keep getting the above error when trying to execute  Start-AzureService.

Following information prompted when executing Get-AzureAccount:

```<code>Id                    Type Subscriptions                        Tenants
--                    ---- -------------                        -------
Me@outlook.com User   12345678-1234-5678-9012-345678901235 {12345678-1234-5678-9012-345678901235}
</code>```

And following information prompted when executing Get-AzureSubscription:

```<code>SubscriptionId            : 12345678-1234-5678-9012-345678901235
SubscriptionName          : My Production (Pay-As-You-Go)
Environment               : MyCloud
DefaultAccount            : Me@outlook.com
IsDefault                 : True
IsCurrent                 : True
TenantId                  : 12345678-1234-5678-9012-345678901235
CurrentStorageAccountName :

Select-AzureSubscription : Parameter set cannot be resolved using the specified named parameters.
</code>```

is prompted when When I try to follow the suggested command:

```<code>Select-AzureSubscription -Default "My Production (Pay-As-You-Go)"
</code>```

答:
When I tried to Select-AzureSubscription it was giving me the error "Subscription does not exist" when I was passing 100% correct subscription name or subscription Id that I found on Azure portal and from powershell:

```<code>$account = Login-AzureRmAccount
$account.Context.Subscription.SubscriptionId
$account.Context.Subscription.SubscriptionName
</code>```

Adding Azure account fixed the problem for me:

```<code>Add-AzureAccount
</code>```

Body:
I’m keep getting the above error when trying to execute  Start-AzureService.

Following information prompted when executing Get-AzureAccount:

Id                    Type Subscriptions                        Tenants
--                    ---- -------------                        -------
Me@outlook.com User   12345678-1234-5678-9012-345678901235 {12345678-1234-5678-9012-345678901235}

And following information prompted when executing Get-AzureSubscription:

SubscriptionId            : 12345678-1234-5678-9012-345678901235
SubscriptionName          : My Production (Pay-As-You-Go)
Environment               : MyCloud
DefaultAccount            : Me@outlook.com
IsDefault                 : True
IsCurrent                 : True
TenantId                  : 12345678-1234-5678-9012-345678901235
CurrentStorageAccountName :

Select-AzureSubscription : Parameter set cannot be resolved using the specified named parameters.

is prompted when When I try to follow the suggested command:

Select-AzureSubscription -Default "My Production (Pay-As-You-Go)"

Body:
When I tried to Select-AzureSubscription it was giving me the error "Subscription does not exist" when I was passing 100% correct subscription name or subscription Id that I found on Azure portal and from powershell:

$account = Login-AzureRmAccount
$account.Context.Subscription.SubscriptionId
$account.Context.Subscription.SubscriptionName

Adding Azure account fixed the problem for me:

Add-AzureAccount


问:
SimpleSchema: Depending values instead of optional values
This is how my SimpleSchema validation looks like:

```<code>validate: new SimpleSchema({
    type: { type: String, allowedValues: ['start', 'stop'] },
    _id : { type: SimpleSchema.RegEx.Id, optional: true },
    item: { type: String, optional: true }
}).validator()
</code>```

But it is not exactly what I am needing:

If type is start, there must be a item value and if type is stop there must be an _id value.

答:
You can achieve this by changing your code like below

```<code>validate: new SimpleSchema({
  type: { type: String, allowedValues: ['start', 'stop'] },
  _id : {
    type: SimpleSchema.RegEx.Id,
    optional: true,
    custom: function () {
      if (this.field('type').value == 'stop') {
        return SimpleSchema.ErrorTypes.REQUIRED
      }
    }
  },
  item: {
    type: String,
    optional: true,
    custom: function () {
      if (this.field('type').value == 'start') {
        if(!this.isSet || this.value === null || this.value === "") {
          return SimpleSchema.ErrorTypes.REQUIRED
        }
      }
    }
  }
}).validator()
</code>```

If you use atmosphere package of SimpleSchema you can replace return SimpleSchema.ErrorTypes.REQUIRED with return 'required'. I tested above code only using NPM package and both versions worked fine.

This is a very basic implementation of this functionality. SimpleSchema even allows to conditionally require field depending on the performed operation(insert, update).

You can read more about it in the docs

If you use old atmosphere package
https://github.com/aldeed/meteor-simple-schema#make-a-field-conditionally-required

If  you use new NPM package https://github.com/aldeed/node-simple-schema#make-a-field-conditionally-required

Body:
This is how my SimpleSchema validation looks like:

validate: new SimpleSchema({
    type: { type: String, allowedValues: ['start', 'stop'] },
    _id : { type: SimpleSchema.RegEx.Id, optional: true },
    item: { type: String, optional: true }
}).validator()

But it is not exactly what I am needing:

If type is start, there must be a item value and if type is stop there must be an _id value.

Body:
You can achieve this by changing your code like below

validate: new SimpleSchema({
  type: { type: String, allowedValues: ['start', 'stop'] },
  _id : {
    type: SimpleSchema.RegEx.Id,
    optional: true,
    custom: function () {
      if (this.field('type').value == 'stop') {
        return SimpleSchema.ErrorTypes.REQUIRED
      }
    }
  },
  item: {
    type: String,
    optional: true,
    custom: function () {
      if (this.field('type').value == 'start') {
        if(!this.isSet || this.value === null || this.value === "") {
          return SimpleSchema.ErrorTypes.REQUIRED
        }
      }
    }
  }
}).validator()

If you use atmosphere package of SimpleSchema you can replace return SimpleSchema.ErrorTypes.REQUIRED with return 'required'. I tested above code only using NPM package and both versions worked fine.

This is a very basic implementation of this functionality. SimpleSchema even allows to conditionally require field depending on the performed operation(insert, update).

You can read more about it in the docs

If you use old atmosphere package
https://github.com/aldeed/meteor-simple-schema#make-a-field-conditionally-required

If  you use new NPM package https://github.com/aldeed/node-simple-schema#make-a-field-conditionally-required


问:
Update UITableView height when tweet loaded
I have a UITableViewCell which contains a TWTRTweetView with auto layout. I am loading a tweet like this:

```<code>- (void)loadTweetWithId:(NSString *)tweetId {

    if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
        mTweetId = tweetId;
        [[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {
            if (tweet) {
                NSLog(@"Tweet loaded!");
                [mTweetView configureWithTweet:tweet];
                [mTweetView setShowActionButtons:YES];
                //[mTweetView setDelegate:self];
                [mTweetView setPresenterViewController:self.viewController];
                [mTweetView setNeedsLayout];
                [mTweetView layoutIfNeeded];
                [mTweetView layoutSubviews];
                hc.constant = mTweetView.frame.size.height;
                [self updateConstraints];
                [self layoutIfNeeded];
                [self layoutSubviews];
                [self.tableView setNeedsLayout];
                [self.tableView layoutIfNeeded];
                [self.tableView layoutSubviews];
            } else {
                NSLog(@"Tweet load error: %@", [error localizedDescription]);
            }
        }];
    }
}
</code>```

When tweet loaded cell doesn't resize unless I scroll it out and scroll it to back. I have tried several approaches as you can see in code snippet. But non of these works. My table view uses full auto layout approach which doesn't implement cell height for row function. How can i fix this?

UPDATE:

Using:

```<code>[self.tableView beginUpdates];
[self.tableView endUpdates];
</code>```

is not possible because when I do that all cells being redrawn and very big jumping happens and that is not acceptable. Also I have confirmed that tweet completion block runs in main thread.

UPDATE 2:

I have also tried to cache tweet view with tweet id and reload cell for related index path and give the same tweet view for tweet id. The cell height is corrected but it doesn't become visible until scroll out/in.

UPDATE 3:

I give constraints to tweet view in xib of the cell and height constraint is connected. So this is not a main thread issue. I have also mentioned that reloading particular cell at index doesn't work.

While working an other solution I have seen some sample TwitterKit codes that uses TWTRTweetTableViewCell but was preloading tweets to configure the cells. So I have done the same. This is a workaround of course.

答:
Updated Answer:

You're doing a couple of things wrong that are likely to cause (or at least contribute to) the jumping:

Never call layoutSubviews yourself.
It's a method called by the system to resolve your constraints. It's automatically triggered when calling setNeedsLayout and layoutIfNeeded in a row.

The same applies to updateConstraints. It is called by the system during a layout pass. You can manually trigger it by subsequently calling setNeedsUpdateContraints and updateConstraintsIfNeeded. Furthermore, it only has an effect if you actually implemented (overrode) that method in your custom view (or cell).

When you call layoutIfNeeded on a view it layouts its subviews. Thus, when you change the constant of a constraint that constrains your mTweetView, it probably won't have any effect (unless the view hierarchy is invalidated during the triggered layout pass). You need to call layoutIfNeeded on mTweetView's superview which is the cell's content view (judging from the screenshot you added to your post):

```<code>[contentView layoutIfNeeded];
</code>```

Furthermore, there is one more thing you need to be aware of that can cause flickering as well:

Cells in a table view are being recycled. Each time a cell is reused you load a new tweet. I guess it's from an asynchronous network request? If so, there is the possibility that the completion block from the first tweet you load for that cell instance returns after the completion block from the second tweet you load for that (recycled) cell when you scroll really fast or you internet connection is really slow. Make sure you cancel the request or invalidate it somehow when your cell is reused (prepareForReuse method).

Please make sure you've fixed all these issues and see if animation now works as expected. (My original answer below remains valid.)

Original Answer:

I'm pretty sure that

```<code>[self.tableView beginUpdates];
[self.tableView endUpdates];
</code>```

is the only way to have a cell auto-resize itself while being displayed.

Reason:

For historic and performance reasons a UITableView always works with fixed-height cells (internally). Even when using self-sizing cells by setting an estimatedRowHeight etc. the table view will compute the height of a cell when it's dequeued, i.e. before it appears on screen. It will then add some internal constraints to the cell to give it a fixed width and a fixed height that just match the size computed by Auto Layout.

These internal constraints are only updated when needed, i.e. when a row is reloaded. Now when you add any constraints inside you cell you will "fight" against these internal constraints which have a required priority (aka 1000). In other words: There's no way to win!

The only way to update these internal (fixed) cell constraints is to tell the table view that it should. And as far as I know the only public (documented) API for that is

```<code>- (void)beginUpdates;
- (void)endUpdates;
</code>```

So the only question that remains is:

Why is this approach not an option for you?

I think it's legitimate to redraw a cell after it's been resized. When you expand the cell to show a longer tweet than before the cell needs to be redrawn anyway!

You probably won't (and shouldn't) resize all visible cells all the time. (That would be quite confusing for the user...)

Body:
I have a UITableViewCell which contains a TWTRTweetView with auto layout. I am loading a tweet like this:

- (void)loadTweetWithId:(NSString *)tweetId {

    if (mTweetId == nil || ![mTweetId isEqualToString:tweetId]) {
        mTweetId = tweetId;
        [[[TWTRAPIClient alloc] init] loadTweetWithID:tweetId completion:^(TWTRTweet *tweet, NSError *error) {
            if (tweet) {
                NSLog(@"Tweet loaded!");
                [mTweetView configureWithTweet:tweet];
                [mTweetView setShowActionButtons:YES];
                //[mTweetView setDelegate:self];
                [mTweetView setPresenterViewController:self.viewController];
                [mTweetView setNeedsLayout];
                [mTweetView layoutIfNeeded];
                [mTweetView layoutSubviews];
                hc.constant = mTweetView.frame.size.height;
                [self updateConstraints];
                [self layoutIfNeeded];
                [self layoutSubviews];
                [self.tableView setNeedsLayout];
                [self.tableView layoutIfNeeded];
                [self.tableView layoutSubviews];
            } else {
                NSLog(@"Tweet load error: %@", [error localizedDescription]);
            }
        }];
    }
}

When tweet loaded cell doesn't resize unless I scroll it out and scroll it to back. I have tried several approaches as you can see in code snippet. But non of these works. My table view uses full auto layout approach which doesn't implement cell height for row function. How can i fix this?

UPDATE:

Using:

[self.tableView beginUpdates];
[self.tableView endUpdates];

is not possible because when I do that all cells being redrawn and very big jumping happens and that is not acceptable. Also I have confirmed that tweet completion block runs in main thread.

UPDATE 2:

I have also tried to cache tweet view with tweet id and reload cell for related index path and give the same tweet view for tweet id. The cell height is corrected but it doesn't become visible until scroll out/in.

UPDATE 3:

I give constraints to tweet view in xib of the cell and height constraint is connected. So this is not a main thread issue. I have also mentioned that reloading particular cell at index doesn't work.

While working an other solution I have seen some sample TwitterKit codes that uses TWTRTweetTableViewCell but was preloading tweets to configure the cells. So I have done the same. This is a workaround of course.

Body:
Updated Answer:

You're doing a couple of things wrong that are likely to cause (or at least contribute to) the jumping:

Never call layoutSubviews yourself.
It's a method called by the system to resolve your constraints. It's automatically triggered when calling setNeedsLayout and layoutIfNeeded in a row.

The same applies to updateConstraints. It is called by the system during a layout pass. You can manually trigger it by subsequently calling setNeedsUpdateContraints and updateConstraintsIfNeeded. Furthermore, it only has an effect if you actually implemented (overrode) that method in your custom view (or cell).

When you call layoutIfNeeded on a view it layouts its subviews. Thus, when you change the constant of a constraint that constrains your mTweetView, it probably won't have any effect (unless the view hierarchy is invalidated during the triggered layout pass). You need to call layoutIfNeeded on mTweetView's superview which is the cell's content view (judging from the screenshot you added to your post):

[contentView layoutIfNeeded];

Furthermore, there is one more thing you need to be aware of that can cause flickering as well:

Cells in a table view are being recycled. Each time a cell is reused you load a new tweet. I guess it's from an asynchronous network request? If so, there is the possibility that the completion block from the first tweet you load for that cell instance returns after the completion block from the second tweet you load for that (recycled) cell when you scroll really fast or you internet connection is really slow. Make sure you cancel the request or invalidate it somehow when your cell is reused (prepareForReuse method).

Please make sure you've fixed all these issues and see if animation now works as expected. (My original answer below remains valid.)

Original Answer:

I'm pretty sure that

[self.tableView beginUpdates];
[self.tableView endUpdates];

is the only way to have a cell auto-resize itself while being displayed.

Reason:

For historic and performance reasons a UITableView always works with fixed-height cells (internally). Even when using self-sizing cells by setting an estimatedRowHeight etc. the table view will compute the height of a cell when it's dequeued, i.e. before it appears on screen. It will then add some internal constraints to the cell to give it a fixed width and a fixed height that just match the size computed by Auto Layout.

These internal constraints are only updated when needed, i.e. when a row is reloaded. Now when you add any constraints inside you cell you will "fight" against these internal constraints which have a required priority (aka 1000). In other words: There's no way to win!

The only way to update these internal (fixed) cell constraints is to tell the table view that it should. And as far as I know the only public (documented) API for that is

- (void)beginUpdates;
- (void)endUpdates;

So the only question that remains is:

Why is this approach not an option for you?

I think it's legitimate to redraw a cell after it's been resized. When you expand the cell to show a longer tweet than before the cell needs to be redrawn anyway!

You probably won't (and shouldn't) resize all visible cells all the time. (That would be quite confusing for the user...)


问:
Affectiva SDK best practices
Is there some document like development guidelines for Linux platform?

For example questions that I have in my mind after playing a little with the SDK:
1. Does the CameraDetector (or any other detector) should be used in a different thread than the main GUI thread? Is it blocking somehow or is it spawning another thread by itself?
2. When listener notifications are executed - is it the same thread in which detector was created?
3. Is it costly to start and stop detector? Should it be done once when application is started and closed or can it be done on demand when user performs some action on which I should use the detector?

Do other detectors behave the same way?
Are there any other best practices for using the SDK?

答:
CameraDetector::start() creates a background thread that connects to the camera and begins processing frames.  CameraDetector::stop() signals the background thread to disconnect from the camera, stop processing frames, and shut down.

Thus, there is some overhead to calling start() and stop(), but whether this is impactful to your main thread's performance is up to you to assess. I would suggest doing on the main thread as an initial approach and see.

Callbacks are made on a background thread.

Regarding the alternatives of (a) starting once at client startup and stopping at client shutdown vs. (b) starting and stopping as needed when there is detection work to be done, there isn't really a single best practice.  As noted, during an active session (i.e. after start() and before stop()) there are additional resources in use, so this is a factor that may bias things toward (b) if the sessions are infrequent in the larger context of the client application.

In addition, in the specific case of CameraDetector, the camera itself is potentially a hardware resource that other applications would be interested in accessing as well, so minimizing its use would be friendlier to those other applications.

Title: Affectiva SDK best practices


答:
Try using Newtwonsoft for this:</p>

```<code>var json = "{\"users\":[{\"id\":64,\"username\":\"100146\",\"firstname\":\"NAME\",\"lastname\":\"LASTNAME PROFILI\",\"department\":\"\",\"firstaccess\":0,\"lastaccess\":0}],\"warnings\":[]}";

dynamic data = JObject.Parse(json);

var id = data.users[0].id;
</code>```

Title: get the value of JSON parameter c#

Body:
Try using Newtwonsoft for this:

var json = "{\"users\":[{\"id\":64,\"username\":\"100146\",\"firstname\":\"NAME\",\"lastname\":\"LASTNAME PROFILI\",\"department\":\"\",\"firstaccess\":0,\"lastaccess\":0}],\"warnings\":[]}";

dynamic data = JObject.Parse(json);

var id = data.users[0].id;


答: I haven't tried but try using object1["users"]["id"]</p>

Title: get the value of JSON parameter c#


问:
check if a number is present in a list, app engine templates
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?

Update

Lukes answer solved my problem of automatically inserting the break.

But I still need to find a way to check for each number if it is present in a list and give it a specific class. Is there any way to achieve something like this:

```<code>{% for number in list }
  <td {% if number in another_list %}class="special"{% endif %}>{{number}}</td>
{% endfor }
</code>```

答: You should be pre-processing the data in your code to be more easily usable in the template. Break up your array of 100 elements into a nested array of 10 arrays of 10 elements each, and provide the information needed there to assign a CSS class to them.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to generate a board (10X10) using the app engine templates and html table. So this means basically putting a break after 10 iterations of the loop. How can I acieve this using the app engine's inbuilt template engine (django 0.96)?

Update

Lukes answer solved my problem of automatically inserting the break.

But I still need to find a way to check for each number if it is present in a list and give it a specific class. Is there any way to achieve something like this:

{% for number in list }
  {{number}}
{% endfor }


问:
How execute an exe file with dynamic parameters within a loop
I have a database table with 20 columns and 40 rows. In the third column is an identifier that is unique.

I have a .exe written in VB.NET that connects to a datasource and downloads a dataset depending on the identifier. So this VB.NET programm needs an input parameter.

Now I want SSIS to loop over the rows and execute the .exe 40 times (for each identifier). I have found the possibility to do this with a static variable in this solution but I just can not complete the task to do this with my identifiers.

Could anyone help me here?

答:
Assuming you have an SSIS variable of User::MyParameter

In your Foreach Loop, you'd want to get the set of values from your source or whatever and assign that to User::MyParameter. Once that is looking as expected (via temporary Script task or something), then connect it up to the Execute Process Task.

In the Execute Process Task, you will connect User::MyParameter to the StandardInputVariable property in the editor.


问:
Remove = and ? from get method in PHP without htaccess
I want to remove the = and ? from the URL from the get method in PHP. I'm working on the pagination structure of my website and currently this is what the URLs look like:

```<code>www.example/test/?page=3
</code>```

I want it to look like this:

```<code>www.example/test/3
</code>```

This is the PHP code that generates the URL.

```<code> <?php
   class Pagination {
   public $current_page;
   public $per_page;
   public $total_count;
   public $pages_articles;

  public function __construct($page=1, $per_page=20, $total_count=0) {
  $this->current_page = (int)$page;
  $this->per_page = (int)$per_page;
  $this->total_count = (int)$total_count;
  $this->pages_articles=array(
   '<div class="article-loop"><img src="http://i.imgur.com/CmU3tnl.jpg"> </div>',
'<div class="article-loop"><img src="http://i.imgur.com/TDdxS9H.png"></div>',
 '<div class="article-loop"><img src="http://i.imgur.com/39rpmwB.jpg"></div>',
 '<div class="article-loop"><img src="http://i.imgur.com/1lBZQ1B.png"></div>',
 '<div class="article-loop"><img src="https://i.imgur.com/Y5Ld4Qfh.jpg"></div>',
 '<div class="article-loop"><img src="http://i.imgur.com/8HumESY.jpg"></div>',
 '<div class="article-loop"><img src="http://i.imgur.com/CqCZBvk.png"></div>',
 '<div class="article-loop"><img src="http://i.imgur.com/wQVPRVp.png"></div>');
 }

   public function offset() {
 return ($this->current_page - 1) * $this->per_page;
  }
   public function total_pages() {

 return ceil($this->total_count/$this->per_page);
  }
   public function previous_page() {
 return $this->current_page - 1;
  }
   public function next_page() {
 return $this->current_page + 1;
  }
   public function has_previous_page() {
 return $this->previous_page() >= 1 ? true : false;
  }
   public function has_next_page() {
 return $this->next_page() <= $this->total_pages() ? true : false;
  }
 }
   $page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
   $per_page = 3;
   $total_count=8;
   $pagination = new Pagination($page, $per_page, $total_count);
   ?>

 <html>
 <body>
 <div>
 <?php
   $i = $pagination->offset()  ;
  $limit = $pagination->per_page;
   while($i<$pagination->total_count && $limit>0) {
    echo $pagination->pages_articles[$i]."<br>";
    $i++;
    $limit--;
   }
  ?>
  </div>
  <ul>
    <?php
   if($pagination->has_previous_page()) {
    echo '<li style="display:inline"><a  href="index.php?page='.$pagination->previous_page().'">«</a></li>';
    } else {
    echo '<li style="display:inline" class="disabled"><a href="#">«   </a></li>';
   }
   for($i=1; $i<=$pagination->total_pages(); $i++) {
    echo '<a href="index.php?page='.$i.'"><li style="display:inline; margin-left:5px; margin-right:5px">'.$i.'</li></a>';
   }
  if($pagination->has_next_page()) {
    echo '<li style="display:inline"><a href="index.php?page='.$pagination->next_page().'">»</a></li>';
   } else {
    echo '<li style="display:inline" class="disabled"><a href="#">»</a></li>';
   }
  ?>
 </ul>
 </body>
 </html>
</code>```

https://3v4l.org/i4GZQ

答:
Your webserver has to map the URL onto your PHP program somehow.

The traditional way is to use a .php file extension and map the URLs directly onto it, but that won't give the effect you want.

To get that effect; the use of mod_rewrite is common, and putting mod_rewrite directives in a .htaccess file is also common. This is what the Apache manual has to say about it:

You should avoid using .htaccess files completely if you have access to httpd main server config file. Using .htaccess files slows down your Apache http server. Any directive that you can include in a .htaccess file is better set in a Directory block, as it will have the same effect with better performance.

So you can follow that advice and put the mod_rewrite directives you don't want to put in .htaccess in your Apache configuration files.

Assuming you are using Apache and have access to those files.

Body:
I want to remove the = and ? from the URL from the get method in PHP. I'm working on the pagination structure of my website and currently this is what the URLs look like:

www.example/test/?page=3

I want it to look like this:

www.example/test/3

This is the PHP code that generates the URL.

 <?php
   class Pagination {
   public $current_page;
   public $per_page;
   public $total_count;
   public $pages_articles;

  public function __construct($page=1, $per_page=20, $total_count=0) {
  $this->current_page = (int)$page;
  $this->per_page = (int)$per_page;
  $this->total_count = (int)$total_count;
  $this->pages_articles=array(
   '

',
'

',
 '

',
 '

',
 '

',
 '

',
 '

',
 '

');
 }

   public function offset() {
 return ($this->current_page - 1) * $this->per_page;
  }
   public function total_pages() {

 return ceil($this->total_count/$this->per_page);
  }
   public function previous_page() {
 return $this->current_page - 1;
  }
   public function next_page() {
 return $this->current_page + 1;
  }
   public function has_previous_page() {
 return $this->previous_page() >= 1 ? true : false;
  }
   public function has_next_page() {
 return $this->next_page() <= $this->total_pages() ? true : false;
  }
 }
   $page = !empty($_GET['page']) ? (int)$_GET['page'] : 1;
   $per_page = 3;
   $total_count=8;
   $pagination = new Pagination($page, $per_page, $total_count);
   ?>

 <?php
   $i = $pagination->offset()  ;
  $limit = $pagination->per_page;
   while($i<$pagination->total_count && $limit>0) {
    echo $pagination->pages_articles[$i]."
";
    $i++;
    $limit--;
   }
  ?>

    <?php
   if($pagination->has_previous_page()) {
    echo '
previous_page().'">«
';
    } else {
    echo '
«
';
   }
   for($i=1; $i<=$pagination->total_pages(); $i++) {
    echo '
'.$i.'
';
   }
  if($pagination->has_next_page()) {
    echo '
next_page().'">»
';
   } else {
    echo '
»
';
   }
  ?>

https://3v4l.org/i4GZQ


问:
Elo rating system alternative for non competitor vs competitor ladder
I'm working on a ladder system that will have let's say 100 contestants pitted against each other. But these contestants do not battle each other as groups or individually. Instead, they battle each other based on their own individual performance.

For example. A beer brewing competition. Each beer made by each contestant is not being compared directly against another beer. But instead each beer will be rated on 4 stats. Taste, Look, Smell, Feel.

The problem is, some contestants may only submit 1 beer and some may submit a lot more beers.

If contestant #1 submitted only 1 beer but it rated really high in all 4 stats but contestant #2 submitted 6 beers that rated fairly high in all stats, if I just averaged for each contestant, #1 would win. In this situation it should be taken into account that contestant #2 submitted 6 beers in the same time frame.

I'm looking for an algorithm or rating system that takes into account the quantity as well. Or even if the elo system could work in this situation, some help on how to tweak / use it properly to balance the competition considering some contestants may have less submissions than others.

答: Couldn't you just have a rating for each beer rather than each contender. Highest rated beer wins rather than highest rated contender? </p>


问:
Django - Passing Custom Form Parameters to modelfactory
I have a Django ModelForm like this:

```<code>class ContactPhoneForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContactPhoneForm, self).__init__(*args, **kwargs)
    #....
</code>```

...and a view where I try to get a respective formset:

```<code>ContactPhoneFormSet = modelformset_factory(ContactPhone,
                                           ContactPhoneForm,
                                           extra=1,
                                           can_delete = True)
</code>```

Now, I want an additional parameter to be passed to the __init__method of the form:

```<code> class ContactPhoneForm(forms.ModelForm):
        def __init__(self, contact_id, *args, **kwargs):
            self.contact_id = contact_id
            super(ContactPhoneForm, self).__init__(*args, **kwargs)
        #....
</code>```

I tried to the rewrite my view according to this post:

```<code>ContactPhoneFormSet = modelformset_factory(ContactPhone,
                                           wraps(ContactPhoneForm)(partial(ContactPhoneForm, contact_id=contact_id)),
                                           extra=1,
                                           can_delete = True)
</code>```

but I end up with TypeError: the first argument must be callable error. Any help on this?

答:
Django 1.9 added a form_kwargs arguement so you should be able to do:</p>

```<code>ContactPhoneFormSet = modelformset_factory(
    ContactPhone, ContactPhoneForm, extra=1, can_delete=True)
formset = ContactPhoneFormSet(form_kwargs={'contact_id': contact_id})
</code>```

Body:
I have a Django ModelForm like this:

class ContactPhoneForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ContactPhoneForm, self).__init__(*args, **kwargs)
    #....

...and a view where I try to get a respective formset:

ContactPhoneFormSet = modelformset_factory(ContactPhone,
                                           ContactPhoneForm,
                                           extra=1,
                                           can_delete = True)

Now, I want an additional parameter to be passed to the __init__method of the form:

 class ContactPhoneForm(forms.ModelForm):
        def __init__(self, contact_id, *args, **kwargs):
            self.contact_id = contact_id
            super(ContactPhoneForm, self).__init__(*args, **kwargs)
        #....

I tried to the rewrite my view according to this post:

ContactPhoneFormSet = modelformset_factory(ContactPhone,
                                           wraps(ContactPhoneForm)(partial(ContactPhoneForm, contact_id=contact_id)),
                                           extra=1,
                                           can_delete = True)

but I end up with TypeError: the first argument must be callable error. Any help on this?

Body:
Django 1.9 added a form_kwargs arguement so you should be able to do:

ContactPhoneFormSet = modelformset_factory(
    ContactPhone, ContactPhoneForm, extra=1, can_delete=True)
formset = ContactPhoneFormSet(form_kwargs={'contact_id': contact_id})


问:
using powershell to pin an application shortcut on the Taskbar
My question is about the right use of PowerShell command about the way to pin an application shortcut on the Taskbar, my problem is as mentioned below:

If I execute this PowerShell line directly when prompted on PowerShell console:

```<code>(New-Object -com Shell.Application).NameSpace("directoryfile").ParseName("programname").InvokeVerb("taskbarpin")
</code>```

that works perfectly, but I'm not able to do it when calling the PowerShell console from CMD prompt as below:

```<code> c:>powershell -command "(New-Object -com Shell.Application).NameSpace("directoryfile").ParseName("programname").InvokeVerb("taskbarpin")"
</code>```

I don't know why it's not working but if there is any error in that script please help me to solve it

答:
As Jeroen Mostert already pointed out :

either escape the inner double quotes (so cmd doesn't interfere)

```<code>powershell -NonI -NoP -Command "(New-Object -com Shell.Application).NameSpace(\"directoryfile\").ParseName(\"programname\").InvokeVerb(\"taskbarpin\")"
</code>```

or replace them with single ones:

```<code>powershell -NonI -NoP -Command "(New-Object -com Shell.Application).NameSpace('directoryfile').ParseName('programname').InvokeVerb('taskbarpin')"
</code>```

Body:
My question is about the right use of PowerShell command about the way to pin an application shortcut on the Taskbar, my problem is as mentioned below:

If I execute this PowerShell line directly when prompted on PowerShell console:

(New-Object -com Shell.Application).NameSpace("directoryfile").ParseName("programname").InvokeVerb("taskbarpin")

that works perfectly, but I'm not able to do it when calling the PowerShell console from CMD prompt as below:

 c:>powershell -command "(New-Object -com Shell.Application).NameSpace("directoryfile").ParseName("programname").InvokeVerb("taskbarpin")"

I don't know why it's not working but if there is any error in that script please help me to solve it

Body:
As Jeroen Mostert already pointed out :

either escape the inner double quotes (so cmd doesn't interfere)

powershell -NonI -NoP -Command "(New-Object -com Shell.Application).NameSpace(\"directoryfile\").ParseName(\"programname\").InvokeVerb(\"taskbarpin\")"

or replace them with single ones:

powershell -NonI -NoP -Command "(New-Object -com Shell.Application).NameSpace('directoryfile').ParseName('programname').InvokeVerb('taskbarpin')"


问:
How would you represent a hashtable collection in a database schema?
If you were trying to create a domain object in a database schema, and in your code said domain object has a hashtable/list member, like so:

```<code>public class SpaceQuadrant : PersistentObject
{

    public SpaceQuadrant()
    {
    }

    public virtual Dictionary<SpaceCoordinate, SpaceObject> Space
    {
        get;
        set;
    }
}
</code>```

A Dictionary is just a hashtable/list mapping object keys to value keys, I've come up with multiple ways to do this, creating various join tables or loading techniques, but they all kind of suck in terms of getting that O(1) access time that you get in a hashtable.

How would you represent the SpaceQuadrant, SpaceCoordinate, and Space Object in a database schema?
A simple schema code description would be nice,
ie.

```<code>table SpaceQuadrant
{
    ID int not null primary key,
    EntryName varchar(255) not null,
    SpaceQuadrantJoinTableId int not null
                 foreign key references ...anothertable...
}
</code>```

but any thoughts at all would be nice as well, thanks for reading!

More Information:

Thanks for the great answers, already, I've only skimmed them, and I want to take some time thinking about each before I respond.

If you think there is a better way to define these classes, then by all means show me an example, any language your comfortable with is cool

答:
A dictionary is a table.  The hash is a question of what kind of index is used.  Most RDBMS assume that tables are big and densely packed, making a hashed index not appropriate.

```<code>table SpaceQuadrant {
    ID Primary Key,
    -- whatever other attributes are relevant
}

table Space {
    SpaceCoordinate Primary Key,
    Quadrant Foreign Key SpaceQuadrant(ID),
    SpaceObject -- whatever the object is
}
</code>```

Your Space objects have FK references to the Quadrant in which they're located.

Depending on your RDBMS, you might be able to find a hash-based index that gets you the performance you're hoping for.  For example MySQL, using the HEAP storage engine supports HASH indexes.

Body:
If you were trying to create a domain object in a database schema, and in your code said domain object has a hashtable/list member, like so:

public class SpaceQuadrant : PersistentObject
{

    public SpaceQuadrant()
    {
    }

    public virtual Dictionary<SpaceCoordinate, SpaceObject> Space
    {
        get;
        set;
    }
}

A Dictionary is just a hashtable/list mapping object keys to value keys, I've come up with multiple ways to do this, creating various join tables or loading techniques, but they all kind of suck in terms of getting that O(1) access time that you get in a hashtable.

How would you represent the SpaceQuadrant, SpaceCoordinate, and Space Object in a database schema?
A simple schema code description would be nice,
ie.

table SpaceQuadrant
{
    ID int not null primary key,
    EntryName varchar(255) not null,
    SpaceQuadrantJoinTableId int not null
                 foreign key references ...anothertable...
}

but any thoughts at all would be nice as well, thanks for reading!

More Information:

Thanks for the great answers, already, I've only skimmed them, and I want to take some time thinking about each before I respond.

If you think there is a better way to define these classes, then by all means show me an example, any language your comfortable with is cool

Body:
A dictionary is a table.  The hash is a question of what kind of index is used.  Most RDBMS assume that tables are big and densely packed, making a hashed index not appropriate.

table SpaceQuadrant {
    ID Primary Key,
    -- whatever other attributes are relevant
}

table Space {
    SpaceCoordinate Primary Key,
    Quadrant Foreign Key SpaceQuadrant(ID),
    SpaceObject -- whatever the object is
}

Your Space objects have FK references to the Quadrant in which they're located.

Depending on your RDBMS, you might be able to find a hash-based index that gets you the performance you're hoping for.  For example MySQL, using the HEAP storage engine supports HASH indexes.


问:
Laravel Auth::user() has no code completion for User model functions
I am using Laravel and PHPStorm.

The auto completion works for all models, just not for the 'User', when I call it with Auth::user().

When I call the Auth::user() I get the right user object, but the return type of Auth::user() is Authenticatable and not User. So I get no code completion for my user object which is very anoying because I use it very often. I think the problem has something to do with the return type of Auth::user() because it is Authenticatable and not User.

In the config/auth.php I already set the model to app/User::class.

Can you tell me how to cast the return value to the User model?

In this example you can see the behaviour.

答:
```<code>Auth::user()
</code>```

Auth is an Alias from ServiceProviders array in config/app.php if you directly use use Illuminate\Support\Facades\Auth;
 you will get a nice completion in PHPstorm as well as Sublime but it depends on the IDE.

Body:
Auth::user()

Auth is an Alias from ServiceProviders array in config/app.php if you directly use use Illuminate\Support\Facades\Auth;
 you will get a nice completion in PHPstorm as well as Sublime but it depends on the IDE.


问:
Fxed world-wide IPs for testing country detection?
I am integrating my application with some country-detection module.
Overall logic is:

detect client IP

lookup IP in Geo IP DB (for simplicity let's
assume it is MaxMind DB)

identify country code based on IP

Some other business logic based off that country code

That works very well, but I am having problems writing automated integration tests.

There is a way to override (force) certain test IPs, but the problem is that all IPs are periodically changing, and time to time I am getting my tests failed because of that.

Any ideas how to stabilize such tests?
One thought I had is if there was a directory of main ISPs across the world, but could not find it.

Thanks!

答:
You can override the GeoIP lookup service in your test environment to return fixed values for certain test IPs. But this only tests #4. To test #1,2,3, you need to use real IP addresses.

If your needs are limited to only a few countries, you can purchase private proxies with fixed IPs and run your tests through a proxied client with a fixed IP.

To automate at scale, you can look at https://www.geoscreenshot.com, it provides an API for visually testing many locations simultaneously.


问:
How to reload synonyms.txt in Solr?
When I changed my synonyms.txt I only see the diferences when I do this:

restart solr server

indexed some item (empty commit?)

Some knows a way to reload synonyms.txt file without restart server?

Tks a lot.

答: Reloading the core should also reload synonyms. I almost always map indexes to cores (even if it's only one core per instance) due to the enhanced flexibility it provides (as in this case).</p>

Title: How to reload synonyms.txt in Solr?


问:
HTTP error when uploading large size images
I am trying to upload an image using the WordPress Media Uploader (WP Admin > Media > Add new). Smaller size image up to 460kb uploading fine without any error. But when i try to upload large size image it showing HTTP error. I have tried adding the below line in wp-config file. But No luck :(

```<code>define('WP_MEMORY_LIMIT', '64MB');
</code>```

Anyone have idea on this. Please help me.
I have attached screenshot too

Thanks..

答: In your wordpress dashboard go to Settings -> Media. There you have different sizes (width x height) defined for Thumbnails, Medium Size and Large. By default, for large wordpress has a size of 1024 x 1024. If you try to upload a bigger resolution image like 4096 x 2048 let's say, you'll get an error. Try increasing the resolution for the Large images and try again and see if that works. Check phpinfo() for memory_limit settings on your server. If it's limited to some amount at the server level, setting it on wp-config.php won't really help.

Body:
I am trying to upload an image using the WordPress Media Uploader (WP Admin > Media > Add new). Smaller size image up to 460kb uploading fine without any error. But when i try to upload large size image it showing HTTP error. I have tried adding the below line in wp-config file. But No luck :(

define('WP_MEMORY_LIMIT', '64MB');

Anyone have idea on this. Please help me.
I have attached screenshot too

Thanks..


问:
how to use ng-show to display specific divs inside an ng-repeat?
I have an ng-repeat div to dynamically display a set of div tags based on a dynamic list of items, that each have a unique Id , a type and a "title" value which are both strings and I have a click function assigned to each of them. When I want to click on one of these divs , I want to display an separate div associated to that clicked div and I want to do that using an ng-show which at the moment has a condition where the id of this item/div should be equal/equivalent to a
scope variable I've defined in a controller associated with the html for this new div to be displayed.

The problem I'm getting is that every one of these separate divs is showing and assuming that all the ng-shows are true which shouldn't be the case and I'm not sure why this is happening as all the id's for the items are unique. I've printed out to the console and can't see anything wrong with the assigning of the variable but not sure if I've missed something with regards to the ng-show condition.

Here is what I have so far  in html with 2 div examples (don't worry about replicating all the styling, i just want to figure out what is going on with the html/angular stuff):

```<code><div class="col-md-12 col-sm-12 col-xs-12  " ng-repeat="item in items track by item.id"  ng-click="onClick(item.id)">

  //first type div that is clickable
  <div class="row">
    <div>
      <header class="text">
        <h1 data-ng-if="item.title" ng-bind-html="item.title"></h1>
      </header>
    </div>
  </div>

  //div to be displayed after associated first div type is clicked
  <div class=" col-sm-11 row"  ng-show="displayMessage===item.id"   >
      <header class="col-sm-12 text">
          <h1  data-ng-if="item.title" ng-bind-html="item.title"></h1>
      </header>
      <p class="col-sm-12" > text about {{item.id]} </p>
  </div>

  //2nd type of  div
  <div class="row"  style=" background: linear-gradient(135deg, #156570, #1e9d8b);">
      <h1 data-ng-if="item.title" ng-bind-html="item.title"></h1>
      <i class="ms-icon ms-icon-heart-rate"></i>
      <div class="clearfix"></div>
  </div>

  //div to be displayed after associated second div is clicked
  <div class="col-md-11 col-sm-11 col-xs-11"  ng-show="displayMessage===item.id">

    <div style="background: linear-gradient(135deg, #156570, #1e9d8b);"></div>

    <h1 class="col-sm-12 col-xs-12"  data-ng-if="item.title" ng-bind-html="item.title" style="color:#000"></h1>

    <p class="col-sm-12 col-xs-12 "> text associated with {{item.id}}
    </p>

  </div>

</div>
</code>```

And here is the simple click function I have . $scope.displayMessage is defined earlier on during the controller setup where its set to an empty string:

```<code>$scope.onClick = function (itemId) {
    $scope.displayMessage = itemId;
}
</code>```

Let me know if I need to add more code.

答:
This will be easier for you to accomplish if you had properties on each item to key off of.

For example,

```<code>$scope.items = [
  {
    id: 1,
    title: "first item",
    isFirstDivSelected: false,
    isSecondDivSelected: false
   },
  {
    id: 2,
    title: "second item",
    isFirstDivSelected: false,
    isSecondDivSelected: false
   }
  {
    id: 3,
    title: "third item",
    isFirstDivSelected: false,
    isSecondDivSelected: false
   }
];
</code>```

This will allow you to add an ng-click to your children items.

  //first type div that is clickable

  //div to be displayed after associated first div is clicked

 text about {{item.id]}

   //more divs.........```

Right now, there is no good way to for your application to know that any of your children divs have been clicked. There are other ways you can do this, but in my opinion, adding properties that are well defined and straightforward is the best way.

Body:
I have an ng-repeat div to dynamically display a set of div tags based on a dynamic list of items, that each have a unique Id , a type and a "title" value which are both strings and I have a click function assigned to each of them. When I want to click on one of these divs , I want to display an separate div associated to that clicked div and I want to do that using an ng-show which at the moment has a condition where the id of this item/div should be equal/equivalent to a
scope variable I've defined in a controller associated with the html for this new div to be displayed.

The problem I'm getting is that every one of these separate divs is showing and assuming that all the ng-shows are true which shouldn't be the case and I'm not sure why this is happening as all the id's for the items are unique. I've printed out to the console and can't see anything wrong with the assigning of the variable but not sure if I've missed something with regards to the ng-show condition.

Here is what I have so far  in html with 2 div examples (don't worry about replicating all the styling, i just want to figure out what is going on with the html/angular stuff):

  //first type div that is clickable

  //div to be displayed after associated first div type is clicked

 text about {{item.id]}

  //2nd type of  div

  //div to be displayed after associated second div is clicked

 text associated with {{item.id}}

And here is the simple click function I have . $scope.displayMessage is defined earlier on during the controller setup where its set to an empty string:

$scope.onClick = function (itemId) {
    $scope.displayMessage = itemId;
}

Let me know if I need to add more code.

Body:
This will be easier for you to accomplish if you had properties on each item to key off of.

For example,

$scope.items = [
  {
    id: 1,
    title: "first item",
    isFirstDivSelected: false,
    isSecondDivSelected: false
   },
  {
    id: 2,
    title: "second item",
    isFirstDivSelected: false,
    isSecondDivSelected: false
   }
  {
    id: 3,
    title: "third item",
    isFirstDivSelected: false,
    isSecondDivSelected: false
   }
];

This will allow you to add an ng-click to your children items.

<div class="col-md-12 col-sm-12 col-xs-12  " ng-repeat="item in items track by item.id"  ng-click="onClick(item.id)">

  //first type div that is clickable
  <div class="row" ng-click="item.isFirstDivSelected = true;">
    <div>
      <header class="text">
        <h1 data-ng-if="item.title" ng-bind-html="item.title"></h1>
      </header>
    </div>
  </div>

  //div to be displayed after associated first div is clicked
  <div class=" col-sm-11 row"  ng-show="item.isFirstDivSelected"   >
      <header class="col-sm-12 text">
          <h1  data-ng-if="item.title" ng-bind-html="item.title"></h1>
      </header>
      <p class="col-sm-12" > text about {{item.id]} </p>
  </div>

   //more divs.........

Right now, there is no good way to for your application to know that any of your children divs have been clicked. There are other ways you can do this, but in my opinion, adding properties that are well defined and straightforward is the best way.