问:
Codeigniter Access DB object in another model
In Codeigniter models is there a way to make this work?

```<code>class Mdl_my_model extends CI_Model
{
protected $my_db = NULL;

public function __construct()
{
    parent::__construct();
    $this->my_db = $this->load->database('my_db', TRUE);
}

public function some_cool_method()
{
    $this->load->model('Mdl_other_model');
    $this->Mdl_other_model->other_method();
}
}
</code>```

Can model below make use of the $my_db object or do I have to load db again?

```<code>class Mdl_other_model extends CI_Model
{

public function __construct()
{
    parent::__construct();
}

public function other_method()
{
    //is it possible to use the $my_db object here?
}
}
</code>```

答:
You don't have to load the database on to a class property. You can simple just load it as you do a model $this->load->database('name'). It should be accessible to everything beneath when you load it. However I usually just load it in a MY_Controller on the first line in __construct to which I extend all my separate controllers off of.

If you are trying to assign different database names to individual properties (which is the only reason why you would assign it as you are doing), you would have to make your other model extend the first and then you can access that property. But this means whenever you load the other model you have to load the first one first. Generally I would also then assign them in to public properties in MY_Controller controller and the variable would be available throughout.

Body:
In Codeigniter models is there a way to make this work?

class Mdl_my_model extends CI_Model
{
protected $my_db = NULL;

public function __construct()
{
    parent::__construct();
    $this->my_db = $this->load->database('my_db', TRUE);
}

public function some_cool_method()
{
    $this->load->model('Mdl_other_model');
    $this->Mdl_other_model->other_method();
}
}

Can model below make use of the $my_db object or do I have to load db again?

class Mdl_other_model extends CI_Model
{

public function __construct()
{
    parent::__construct();
}

public function other_method()
{
    //is it possible to use the $my_db object here?
}
}


来源: stackexchange

问:
Hide button based on reference from firebase
I am trying to hide some buttons based on whether the user is an admin. I have added this in the database to show true or false. I have created an if statement so that when oncreate starts if the users admin is false the buttons should be hidden but this is not what is happening

The buttons are showing as normal

// this is the code i have in the on create

```<code>        databaseUsers.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot venueSnapshot: dataSnapshot.getChildren()){
                User user = venueSnapshot.getValue(User.class);

                if(user.getAdminUser() == true)
                                    {
                    buttonAddProducts.setVisibility(View.VISIBLE);
                    buttonAddBeverages.setVisibility(View.VISIBLE);
                }
            }

        }

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

//This is the entire oncreate
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        buttonAddBeverages = (Button) findViewById(R.id.buttonAddBeverages);
        buttonAddProducts = (Button) findViewById(R.id.buttonAddProducts);
        databaseUsers = FirebaseDatabase.getInstance().getReference("users");
        //initializing firebase authentication object
        firebaseAuth = FirebaseAuth.getInstance();

        buttonAddProducts.setVisibility(View.GONE);
        buttonAddBeverages.setVisibility(View.GONE);

        //if the user is not logged in
        //that means current user will return null
        if(firebaseAuth.getCurrentUser() == null){
            //closing this activity
            finish();
            //starting login activity
            startActivity(new Intent(this, LoginActivity.class));
        }

        //getting current user
        FirebaseUser user = firebaseAuth.getCurrentUser();

        //initializing views
        textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail);
        buttonLogout = (Button) findViewById(R.id.buttonLogout);

        //displaying logged in user name
        textViewUserEmail.setText("Welcome "+user.getEmail());

        databaseUsers.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot venueSnapshot: dataSnapshot.getChildren()){
                    User user = venueSnapshot.getValue(User.class);

                    if(user.getAdminUser() == true)
                                        {
                        buttonAddProducts.setVisibility(View.VISIBLE);
                        buttonAddBeverages.setVisibility(View.VISIBLE);
                    }
                }

            }

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

        buttonLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //logging out the user
                firebaseAuth.signOut();
                //closing activity
                finish();
                //starting login activity
                startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
            }
        });
    }
</code>```

答:
```<code>Do this in reverse. First hide button, then if true show the button.

    buttonAddProducts.setVisibility(View.GONE);
    if(user.equals(true))
      buttonAddProducts.setVisibility(View.VISIBLE);

Or you may put your code when activity start
or in xml  <Button ... android:visibility="gone"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to hide some buttons based on whether the user is an admin. I have added this in the database to show true or false. I have created an if statement so that when oncreate starts if the users admin is false the buttons should be hidden but this is not what is happening

The buttons are showing as normal

// this is the code i have in the on create

        databaseUsers.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot venueSnapshot: dataSnapshot.getChildren()){
                User user = venueSnapshot.getValue(User.class);

                if(user.getAdminUser() == true)
                                    {
                    buttonAddProducts.setVisibility(View.VISIBLE);
                    buttonAddBeverages.setVisibility(View.VISIBLE);
                }
            }

        }

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

//This is the entire oncreate
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);

        buttonAddBeverages = (Button) findViewById(R.id.buttonAddBeverages);
        buttonAddProducts = (Button) findViewById(R.id.buttonAddProducts);
        databaseUsers = FirebaseDatabase.getInstance().getReference("users");
        //initializing firebase authentication object
        firebaseAuth = FirebaseAuth.getInstance();

        buttonAddProducts.setVisibility(View.GONE);
        buttonAddBeverages.setVisibility(View.GONE);

        //if the user is not logged in
        //that means current user will return null
        if(firebaseAuth.getCurrentUser() == null){
            //closing this activity
            finish();
            //starting login activity
            startActivity(new Intent(this, LoginActivity.class));
        }

        //getting current user
        FirebaseUser user = firebaseAuth.getCurrentUser();

        //initializing views
        textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail);
        buttonLogout = (Button) findViewById(R.id.buttonLogout);

        //displaying logged in user name
        textViewUserEmail.setText("Welcome "+user.getEmail());

        databaseUsers.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot venueSnapshot: dataSnapshot.getChildren()){
                    User user = venueSnapshot.getValue(User.class);

                    if(user.getAdminUser() == true)
                                        {
                        buttonAddProducts.setVisibility(View.VISIBLE);
                        buttonAddBeverages.setVisibility(View.VISIBLE);
                    }
                }

            }

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

        buttonLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //logging out the user
                firebaseAuth.signOut();
                //closing activity
                finish();
                //starting login activity
                startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
            }
        });
    }


问:
How to combine two DataFrame Structures in Python
I'm looking for a combination of two DataFrame structures in Python using a (shared) index value column.

Data snippet:

```<code>d1 = {'col1': ['entry1', 'entry2', 'entry3'], 'col2': [1, 2,3]}
df1 = pd.DataFrame(data=d1)

d2= {'col1': ['entry2', 'entry3', 'entry1'], 'priority': [4, 2 , 7]}
df2 = pd.DataFrame(data=d2)
</code>```

The result should be something like

```<code>col1     col2    priority
----     ----    ----
entry1   1       7
entry2   2       4
entry3   3       2
</code>```

How can I achieve that?

答:
Simple as </p>

```<code>frames = [df1.set_index('col1'), df2.set_index('col1'), axis = 1]

result = pd.concat(frames)
</code>```

Body:
I'm looking for a combination of two DataFrame structures in Python using a (shared) index value column.

Data snippet:

d1 = {'col1': ['entry1', 'entry2', 'entry3'], 'col2': [1, 2,3]}
df1 = pd.DataFrame(data=d1)

d2= {'col1': ['entry2', 'entry3', 'entry1'], 'priority': [4, 2 , 7]}
df2 = pd.DataFrame(data=d2)

The result should be something like

col1     col2    priority
----     ----    ----
entry1   1       7
entry2   2       4
entry3   3       2

How can I achieve that?

Body:
Simple as

frames = [df1.set_index('col1'), df2.set_index('col1'), axis = 1]

result = pd.concat(frames)


问:
int rosu=Color.red.getRGB() from Java to C#
I am converting by hand a code from Java to C#, and I don't know how to convert

private static int rosu = Color.Red.getRGB;

I get this error:

```<code>'System.Drawing.Color' does not contain a definition for 'getRGB' and no extension method 'getRGB' accepting a first argument of type 'System.Drawing.Color' could be found (are you missing a using directive or an assembly reference?)
</code>```

I use the declared rosu in this context:

```<code>       for (uy=0;uy<h;uy++)
            for (ux=0;ux<w;ux++)
                if(curba[uy][ux]==255)
                      curba[uy][ux]=rosu;
</code>```

Thank you

答:
This is what you want:

```<code>private static int rosu = Color.Red.ToArgb();
</code>```

The .Net Color class is basically just a wrapper around int anyway, so in your conversion you may want to instead change all your color variables from int to Color.

ContentLicense: CC BY-SA 2.5

Body:
I am converting by hand a code from Java to C#, and I don't know how to convert

private static int rosu = Color.Red.getRGB;

I get this error:

'System.Drawing.Color' does not contain a definition for 'getRGB' and no extension method 'getRGB' accepting a first argument of type 'System.Drawing.Color' could be found (are you missing a using directive or an assembly reference?)

I use the declared rosu in this context:

       for (uy=0;uy<h;uy++)
            for (ux=0;ux<w;ux++)
                if(curba[uy][ux]==255)
                      curba[uy][ux]=rosu;

Thank you

Body:
This is what you want:

private static int rosu = Color.Red.ToArgb();

The .Net Color class is basically just a wrapper around int anyway, so in your conversion you may want to instead change all your color variables from int to Color.


问:
Perforce adding a folder to depot
I am new to Perforce. Could you add a new folder under the branch in the depot? I also tried to add one in my workplace but how could I get it to the depot? Do I have to do a merge/integrate or something?

Thanks.

答: I had a situation that I need to add entire folder with files having wildcard name, so had to do it through command line using -f (force), I used "dir /b /s /a-d | p4 -x - add -f" </p>

Title: Perforce adding a folder to depot


问:
How can we implement loop constructs in genetic programming?
I've been playing around with genetic programming for some time and started wondering how to implement looping constructs.

In the case of for loops I can think of 3 parameters:

start: starting value of counter

end: counter upper limit

expression:  the expression to execute while counter < end

Now the tricky part is the expression because it generates the same value in every iteration unless counter is somehow injected into it. So I could allow the symbol for counter to be present in the expressions but then how do I prevent it from appearing outside of for loops?

Another problem is using the result of the expression. I could have a for loop which sums the results, another one that multiplies them together but that's limiting and doesn't seem right. I would like a general solution, not one for every operator.

So does anyone know a good method to implement loops in genetic programming?

答:
The issue with zegkjan's answer is that there is more than one way to skin a cat.

Theres actually a simpler, and at times, better solution to creating GP datastructures than koza trees, instead using stacks.

This method is called Stack Based Genetic Programming, which is quite old (1993).  This method of genetic programming removes trees entirely, you have a instruction list, and a data stack (where your functional and terminal set remain the same).   You iterate through your instruction list, pushing values to the data stack, and pulling values to consume them, and returning a new value/values to the stack given your instruction.  For example, consider the following genetic program.

```<code>0: PUSH TERMINAL X
1: PUSH TERMINAL X
2: MULTIPLY (A,B)
</code>```

Iterating through this program will give you:

```<code>step1: DATASTACK X
step2: DATASTACK X, X
step3: DATASTACK X^2
</code>```

Once you have executed all program list statements, you then just take off the number of elements from the stack that you care about (you can get multiple values out of the GP program this way).   This ends up being a fast and extremely flexible method (memory locality, number of parameters doesn't matter, nor number of elements returned) you can implement fairly quickly.

To loop in this method, you can create a separate stack, an execution stack, where new special operators are used to push and pop multiple statements from the execution stack at once to be executed afterwards.

Additionally you can simply include a jump statement to move backwards in your program list, make a loop statement, or have a separate stack holding loop information.  With this a genetic program could theoretically develop its own for loop.

```<code>0: PUSH TERMINAL X
1: START_LOOP 2
2: PUSH TERMINAL X
3: MULTIPLY (A, B)
4: DECREMENT_LOOP_NOT_ZERO

step1: DATASTACK X
       LOOPSTACK
step2: DATASTACK X
       LOOPSTACK [1,2]
step3: DATASTACK X, X
       LOOPSTACK [1,2]
step4: DATASTACK X^2
       LOOPSTACK [1,2]
step5: DATASTACK X^2
       LOOPSTACK [1,1]
step6: DATASTACK X^2, X
       LOOPSTACK [1,1]
step7: DATASTACK X^3
       LOOPSTACK [1,1]
step8: DATASTACK X^3
       LOOPSTACK [1,0]
</code>```

Note however, with any method, it may be difficult for a GP program to actually evolve a member that has a loop, and even if it does, its likely that such a mechanism would result in a poor fitness evaluation at the start, likely removing it from the population any way.   To fix this type of problem (potentially good innovations dying early due to poor early fitness), you'll need to include the concepts of demes in your genetic program to isolate genetically disparate populations.

ContentLicense: CC BY-SA 4.0

Body:
The issue with zegkjan's answer is that there is more than one way to skin a cat.

Theres actually a simpler, and at times, better solution to creating GP datastructures than koza trees, instead using stacks.

This method is called Stack Based Genetic Programming, which is quite old (1993).  This method of genetic programming removes trees entirely, you have a instruction list, and a data stack (where your functional and terminal set remain the same).   You iterate through your instruction list, pushing values to the data stack, and pulling values to consume them, and returning a new value/values to the stack given your instruction.  For example, consider the following genetic program.

0: PUSH TERMINAL X
1: PUSH TERMINAL X
2: MULTIPLY (A,B)

Iterating through this program will give you:

step1: DATASTACK X
step2: DATASTACK X, X
step3: DATASTACK X^2

Once you have executed all program list statements, you then just take off the number of elements from the stack that you care about (you can get multiple values out of the GP program this way).   This ends up being a fast and extremely flexible method (memory locality, number of parameters doesn't matter, nor number of elements returned) you can implement fairly quickly.

To loop in this method, you can create a separate stack, an execution stack, where new special operators are used to push and pop multiple statements from the execution stack at once to be executed afterwards.

Additionally you can simply include a jump statement to move backwards in your program list, make a loop statement, or have a separate stack holding loop information.  With this a genetic program could theoretically develop its own for loop.

0: PUSH TERMINAL X
1: START_LOOP 2
2: PUSH TERMINAL X
3: MULTIPLY (A, B)
4: DECREMENT_LOOP_NOT_ZERO

step1: DATASTACK X
       LOOPSTACK
step2: DATASTACK X
       LOOPSTACK [1,2]
step3: DATASTACK X, X
       LOOPSTACK [1,2]
step4: DATASTACK X^2
       LOOPSTACK [1,2]
step5: DATASTACK X^2
       LOOPSTACK [1,1]
step6: DATASTACK X^2, X
       LOOPSTACK [1,1]
step7: DATASTACK X^3
       LOOPSTACK [1,1]
step8: DATASTACK X^3
       LOOPSTACK [1,0]

Note however, with any method, it may be difficult for a GP program to actually evolve a member that has a loop, and even if it does, its likely that such a mechanism would result in a poor fitness evaluation at the start, likely removing it from the population any way.   To fix this type of problem (potentially good innovations dying early due to poor early fitness), you'll need to include the concepts of demes in your genetic program to isolate genetically disparate populations.


答:
There are quite a few options:

You can use pd.concat

```<code>pd.concat([df1.set_index('col1'), df2.set_index('col1')], axis=1)
</code>```

This gives you

```<code>       col2  priority
entry1     1         7
entry2     2         4
entry3     3         2
</code>```

So col1 becomes your index.

If it should be a column, you can use merge

```<code>df1.merge(df2)
</code>```

which gives

```<code>     col1  col2  priority
0  entry1     1         7
1  entry2     2         4
2  entry3     3         2
</code>```

or

```<code>pd.merge(df1, df2, on='col1')
</code>```

yielding

```<code>     col1  col2  priority
0  entry1     1         7
1  entry2     2         4
2  entry3     3         2
</code>```

Another option is then also join

```<code>df1.set_index('col1').join(df2.set_index('col1'))
</code>```

which gives

```<code>        col2  priority
col1
entry1     1         7
entry2     2         4
entry3     3         2
</code>```

Title: How to combine two DataFrame Structures in Python

Body:
There are quite a few options:

You can use pd.concat

pd.concat([df1.set_index('col1'), df2.set_index('col1')], axis=1)

This gives you

       col2  priority
entry1     1         7
entry2     2         4
entry3     3         2

So col1 becomes your index.

If it should be a column, you can use merge

df1.merge(df2)

which gives

     col1  col2  priority
0  entry1     1         7
1  entry2     2         4
2  entry3     3         2

or

pd.merge(df1, df2, on='col1')

yielding

     col1  col2  priority
0  entry1     1         7
1  entry2     2         4
2  entry3     3         2

Another option is then also join

df1.set_index('col1').join(df2.set_index('col1'))

which gives

        col2  priority
col1
entry1     1         7
entry2     2         4
entry3     3         2


问:
Remote debugging Chrome on Android while offline
If I'm on a plane or do not have connectivity, remote debugging Chrome on Android fails with a blank window. What can I do?</p>

答:
When you remote debug, Chrome need a version of devtools that matches your mobile browser version. So it loads that specific version off the network. Once they are downloaded, they are kept in AppCache, so you only need to have network available once.

So as long as you start debugging a device (that particular Chrome version) once while you're online, you should then have all those files available later when you're offline.

But there's another workaround to avoid downloading the devtools version:

follow the instructions of https://developer.chrome.com/devtools/docs/remote-debugging-legacy down to (and including) the adb forward tcp:9222 ... section.

open http://localhost:9222/json/list (on your desktop)

find the tab you care about and copy the webSocketDebuggerUrl of it

wsurl = webSocketDebuggerUrl.replace('ws://','')

open this URL (on your desktop):
chrome-devtools://devtools/bundled/inspector.html?ws=${wsurl}

This will use your desktop's locally installed version of DevTools to inspect the phone. There is a possibility of a compatibility problem, but hopefully it should be small.


问:
ERROR in Error: Metadata version mismatch for module ../node_modules/angularfire2/index.d.ts, found version 4, expected 3,
ERROR in Error: Metadata version mismatch for module C:/projects/youtube-angular/firestore-app/node_modules/angularfire2/index.d.ts, found version 4, expected 3,

I have never seen this. I tried to uninstall everything and reinstall to newest versions and still getting that error. No one else running the project seems to have this issue. So i am guessing that is some local setting or install i have wrong but can't figure this one out.

```<code>package.json
{
  "name": "firestore-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.4",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "angularfire2": "^5.0.0-rc.4",
    "core-js": "^2.4.1",
    "firebase": "^4.6.2",
    "font-awesome": "^4.7.0",
    "jquery": "^3.2.1",
    "materialize-css": "^0.100.2",
    "rxjs": "^5.4.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.4.7",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }
}
</code>```

答:
In my case I had to change the cli version and the angularfire2 version too</p>

```<code>npm install @angular/cli@ version 1.2.1 --save

npm install angularfire2@5.0.0-rc.3 --save
</code>```

Body:
ERROR in Error: Metadata version mismatch for module C:/projects/youtube-angular/firestore-app/node_modules/angularfire2/index.d.ts, found version 4, expected 3,

I have never seen this. I tried to uninstall everything and reinstall to newest versions and still getting that error. No one else running the project seems to have this issue. So i am guessing that is some local setting or install i have wrong but can't figure this one out.

package.json
{
  "name": "firestore-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^4.2.4",
    "@angular/common": "^4.2.4",
    "@angular/compiler": "^4.2.4",
    "@angular/core": "^4.2.4",
    "@angular/forms": "^4.2.4",
    "@angular/http": "^4.2.4",
    "@angular/platform-browser": "^4.2.4",
    "@angular/platform-browser-dynamic": "^4.2.4",
    "@angular/router": "^4.2.4",
    "angularfire2": "^5.0.0-rc.4",
    "core-js": "^2.4.1",
    "firebase": "^4.6.2",
    "font-awesome": "^4.7.0",
    "jquery": "^3.2.1",
    "materialize-css": "^0.100.2",
    "rxjs": "^5.4.2",
    "zone.js": "^0.8.14"
  },
  "devDependencies": {
    "@angular/cli": "1.4.7",
    "@angular/compiler-cli": "^4.2.4",
    "@angular/language-service": "^4.2.4",
    "@types/jasmine": "~2.5.53",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "~3.2.0",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.7.0",
    "typescript": "~2.3.3"
  }
}

Body:
In my case I had to change the cli version and the angularfire2 version too

npm install @angular/cli@ version 1.2.1 --save

npm install angularfire2@5.0.0-rc.3 --save


问:
Why is my RegEx code replacing some strings, but not others?
I have abstracts of academic articles. Sometimes, the abstract will contain lines like "PurposeThis article explores...." or "Design/methodology/approachThe design of our study....". I call terms like "Purpose" and "Design/methodology/approach" labels. I want the string to look like this: [label][:][space]. For example: "Purpose: This article explores...."

The code below gets me the result I want when the original string has a space between the label and the text (e.g. "Purpose This article explores....". But I don't understand why it also doesn't work when there is no space. May I ask what I need to do to the code below so that the labels are formatted the way I want, even when the original text has no space between the label and the text? Note that I imported re.sub.

```<code>def clean_abstract(my_abstract):
    labels = ['Purpose', 'Design/methodology/approach', 'Methodology/Approach', 'Methodology/approach' 'Findings', 'Research limitations/implications', 'Research limitations/Implications' 'Practical implications', 'Social implications', 'Originality/value']
    for i in labels:
        cleaned_abstract = sub(i, i + ': ', cleaned_abstract)
    return cleaned_abstract
</code>```

答:
Code

See code in use here

```<code>labels = ['Purpose', 'Design/methodology/approach', 'Methodology/Approach', 'Methodology/approach' 'Findings', 'Research limitations/implications', 'Research limitations/Implications' 'Practical implications', 'Social implications', 'Originality/value']
strings = ['PurposeThis article explores....', 'Design/methodology/approachThe design of our study....']
print [l + ": " + s.split(l)[1].lstrip() for l in labels for s in strings if l in s]
</code>```

Results

```<code>[
    'Purpose: This article explores....',
    'Design/methodology/approach: The design of our study....'
]
</code>```

Explanation

Using the logic from this post.

print [] returns a list of results

l + ": " + s.split(l)[1].lstrip() creates our strings

l is explained below

: literally

s.split(l).lstrip() Split s on l and remove any whitespace from the left side of the string

for l in labels Loops over labels setting l to the value upon each iteration

for s in strings Loops over strings setting s to the value upon each iteration

if l in s If l is found in s

Body:
I have abstracts of academic articles. Sometimes, the abstract will contain lines like "PurposeThis article explores...." or "Design/methodology/approachThe design of our study....". I call terms like "Purpose" and "Design/methodology/approach" labels. I want the string to look like this: [label][:][space]. For example: "Purpose: This article explores...."

The code below gets me the result I want when the original string has a space between the label and the text (e.g. "Purpose This article explores....". But I don't understand why it also doesn't work when there is no space. May I ask what I need to do to the code below so that the labels are formatted the way I want, even when the original text has no space between the label and the text? Note that I imported re.sub.

def clean_abstract(my_abstract):
    labels = ['Purpose', 'Design/methodology/approach', 'Methodology/Approach', 'Methodology/approach' 'Findings', 'Research limitations/implications', 'Research limitations/Implications' 'Practical implications', 'Social implications', 'Originality/value']
    for i in labels:
        cleaned_abstract = sub(i, i + ': ', cleaned_abstract)
    return cleaned_abstract

Body:
Code

See code in use here

labels = ['Purpose', 'Design/methodology/approach', 'Methodology/Approach', 'Methodology/approach' 'Findings', 'Research limitations/implications', 'Research limitations/Implications' 'Practical implications', 'Social implications', 'Originality/value']
strings = ['PurposeThis article explores....', 'Design/methodology/approachThe design of our study....']
print [l + ": " + s.split(l)[1].lstrip() for l in labels for s in strings if l in s]

Results

[
    'Purpose: This article explores....',
    'Design/methodology/approach: The design of our study....'
]

Explanation

Using the logic from this post.

print [] returns a list of results

l + ": " + s.split(l)[1].lstrip() creates our strings

l is explained below

: literally

s.split(l).lstrip() Split s on l and remove any whitespace from the left side of the string

for l in labels Loops over labels setting l to the value upon each iteration

for s in strings Loops over strings setting s to the value upon each iteration

if l in s If l is found in s


问:
How to complete authentication required in API call in Cloudera with python programming
Cloudera provides API interface for a user to retrieve information, here is an example of Linux command line:

```<code>curl -v -k -X GET -u user:password "https://hostname:7183/api/v11/clusters/cluster/services/impala/impalaQueries"
</code>```

As you can see there is authentication in place.

I want to write a program in python to send a request to retrieve the same result.

This is what I did:

```<code>import requests

url = "https://hostname:7183/api/v11/clusters/cluster/services/impala/impalaQueries"
requests.get(url, auth=('username', 'password'))
</code>```

I receive the following error:
bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')]

What is wrong here? Can anyone help to sort it out? the expected data is in JSON format.

Thank you very much.

答:
It is failing on verifying your SSL certificate. Try setting verify=False. From the documentation http://docs.python-requests.org/en/master/user/advanced/:

Requests can also ignore verifying the SSL certificate if you set verify to False:

requests.get('https://kennethreitz.org', verify=False)

so use:

```<code>requests.get(url, verify=False, auth=('username', 'password'))
</code>```

You can suppress the waring given like this:

```<code>import requests
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

url = "https://hostname:7183/api/v11/clusters/cluster/services/impala/impalaQueries"
x = requests.get(url, verify=False, auth=('username', 'password'))
print (x.json())
</code>```

This is similar to using the the -k (or --insecure) flag you are passing to cURL.

Body:
Cloudera provides API interface for a user to retrieve information, here is an example of Linux command line:

curl -v -k -X GET -u user:password "https://hostname:7183/api/v11/clusters/cluster/services/impala/impalaQueries"

As you can see there is authentication in place.

I want to write a program in python to send a request to retrieve the same result.

This is what I did:

import requests

url = "https://hostname:7183/api/v11/clusters/cluster/services/impala/impalaQueries"
requests.get(url, auth=('username', 'password'))

I receive the following error:
bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')]

What is wrong here? Can anyone help to sort it out? the expected data is in JSON format.

Thank you very much.

Body:
It is failing on verifying your SSL certificate. Try setting verify=False. From the documentation http://docs.python-requests.org/en/master/user/advanced/:

Requests can also ignore verifying the SSL certificate if you set verify to False:

requests.get('https://kennethreitz.org', verify=False)

so use:

requests.get(url, verify=False, auth=('username', 'password'))

You can suppress the waring given like this:

import requests
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

url = "https://hostname:7183/api/v11/clusters/cluster/services/impala/impalaQueries"
x = requests.get(url, verify=False, auth=('username', 'password'))
print (x.json())

This is similar to using the the -k (or --insecure) flag you are passing to cURL.


问:
Drupal 7, taxonomy exposed filter
I am working with drupal 7. How do I limit a taxonomy dropdown exposed filter to only display the terms used by nodes in view results?

I understand that the list is populated before the views takes place, but this means that i am often left with tags that display nothing ( since they are hidden with my view) any help would be much appreciated

答:
In views:

Filter Criteria

Add - Content: Has taxonomy terms

Settings: Select the Vocabulary name.

Checkbox Expose this filter to visitors.

If you are using single filter select that, where you can see the list of Taxonomy terms. If you have child terms select hierarchy check box and specify the depth of it. only appears when you Add - Content: Has taxonomy terms (with Depth) -- refer to second step above.

Now select the terms you want to display, and make sure to checkbox Limit list to selected items

You can also add (Global: text area) under No result behavior in Advanced if you still want to show all taxonomy terms but want to show some thing to user like coming soon instead of leaving the selected taxonomy term showing empty page.

Title: Drupal 7, taxonomy exposed filter


问:
Training using mxnet in ipython console of Spyder not working
I'm running the mnist example of mxnet in Spyder IDE. The training does not progress, just as if the learning rate were 0 (see output below).

If I run the same file on the console using either python or ipython, it works as expected (seeing improvements in the second epoch).

If I run the file using the normal Python console of Spyder, it also works.
But if I run the file using the ipython console, I get the output shown below.

I'm new to Python. Any ideas?

Source code

```<code>#!/usr/bin/env python2
# -*- coding: utf-8 -*-

#%%
import mxnet as mx

#%% load mnist

mnist = mx.test_utils.get_mnist()

#%% define data iterators

batch_size = 100
train_iter = mx.io.NDArrayIter(mnist['train_data'], mnist['train_label'], batch_size, shuffle=True)
val_iter = mx.io.NDArrayIter(mnist['test_data'], mnist['test_label'], batch_size)

#%% create input variable

data = mx.sym.var('data')
# Flatten the data from 4-D shape into 2-D (batch_size, num_channel*width*height)
data = mx.sym.flatten(data=data)

#%% Multilayer Perceptron with softmax

# The first fully-connected layer and the corresponding activation function
fc1  = mx.sym.FullyConnected(data=data, num_hidden=128)
act1 = mx.sym.Activation(data=fc1, act_type="relu")

# The second fully-connected layer and the corresponding activation function
fc2  = mx.sym.FullyConnected(data=act1, num_hidden = 64)
act2 = mx.sym.Activation(data=fc2, act_type="relu")

# MNIST has 10 classes
fc3  = mx.sym.FullyConnected(data=act2, num_hidden=10)
# Softmax with cross entropy loss
mlp  = mx.sym.SoftmaxOutput(data=fc3, name='softmax')

#%% Training
import logging
logging.getLogger().setLevel(logging.DEBUG)  # logging to stdout
# create a trainable module on CPU
mlp_model = mx.mod.Module(symbol=mlp, context=mx.cpu())
mlp_model.fit(train_iter,  # train data
              eval_data=val_iter,  # validation data
              optimizer='sgd',  # use SGD to train
              optimizer_params={'learning_rate':0.1},  # use fixed learning rate
              eval_metric='acc',  # report accuracy during training
              batch_end_callback = mx.callback.Speedometer(batch_size, 100), # output progress for each 100 data batches
              num_epoch=10)  # train for at most 10 dataset passes
</code>```

Output of ipython console in Spyder

```<code>runfile('/home/thomas/workspace/clover-python/mnist.py', wdir='/home/thomas/workspace/clover-python')
INFO:root:train-labels-idx1-ubyte.gz exists, skipping download
INFO:root:train-images-idx3-ubyte.gz exists, skipping download
INFO:root:t10k-labels-idx1-ubyte.gz exists, skipping download
INFO:root:t10k-images-idx3-ubyte.gz exists, skipping download
INFO:root:Epoch[0] Batch [100]  Speed: 1304.05 samples/sec      accuracy=0.097921
INFO:root:Epoch[0] Batch [200]  Speed: 1059.19 samples/sec      accuracy=0.098200
INFO:root:Epoch[0] Batch [300]  Speed: 1178.64 samples/sec      accuracy=0.099600
INFO:root:Epoch[0] Batch [400]  Speed: 1292.71 samples/sec      accuracy=0.098900
INFO:root:Epoch[0] Batch [500]  Speed: 1394.21 samples/sec      accuracy=0.096500
INFO:root:Epoch[0] Train-accuracy=0.101212
INFO:root:Epoch[0] Time cost=47.798
INFO:root:Epoch[0] Validation-accuracy=0.098000
INFO:root:Epoch[1] Batch [100]  Speed: 1247.47 samples/sec      accuracy=0.097921
INFO:root:Epoch[1] Batch [200]  Speed: 1673.79 samples/sec      accuracy=0.098200
INFO:root:Epoch[1] Batch [300]  Speed: 1283.91 samples/sec      accuracy=0.099600
INFO:root:Epoch[1] Batch [400]  Speed: 1247.79 samples/sec      accuracy=0.098900
INFO:root:Epoch[1] Batch [500]  Speed: 1371.93 samples/sec      accuracy=0.096500
INFO:root:Epoch[1] Train-accuracy=0.101212
INFO:root:Epoch[1] Time cost=44.201
INFO:root:Epoch[1] Validation-accuracy=0.098000
INFO:root:Epoch[2] Batch [100]  Speed: 1387.72 samples/sec      accuracy=0.097921
INFO:root:Epoch[2] Batch [200]  Speed: 1196.37 samples/sec      accuracy=0.098200
INFO:root:Epoch[2] Batch [300]  Speed: 1220.44 samples/sec      accuracy=0.099600
INFO:root:Epoch[2] Batch [400]  Speed: 1387.75 samples/sec      accuracy=0.098900
INFO:root:Epoch[2] Batch [500]  Speed: 1279.58 samples/sec      accuracy=0.096500
INFO:root:Epoch[2] Train-accuracy=0.101212
INFO:root:Epoch[2] Time cost=46.929
INFO:root:Epoch[2] Validation-accuracy=0.098000
INFO:root:Epoch[3] Batch [100]  Speed: 1266.24 samples/sec      accuracy=0.097921

and so on…
</code>```

答:
Per Eric's comment, let's verify that you're running the same version of mxnet in each environment. You can type</p>

```<code>import mxnet
print(mxnet.__version__)
</code>```

Body:
I'm running the mnist example of mxnet in Spyder IDE. The training does not progress, just as if the learning rate were 0 (see output below).

If I run the same file on the console using either python or ipython, it works as expected (seeing improvements in the second epoch).

If I run the file using the normal Python console of Spyder, it also works.
But if I run the file using the ipython console, I get the output shown below.

I'm new to Python. Any ideas?

Source code

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

#%%
import mxnet as mx

#%% load mnist

mnist = mx.test_utils.get_mnist()

#%% define data iterators

batch_size = 100
train_iter = mx.io.NDArrayIter(mnist['train_data'], mnist['train_label'], batch_size, shuffle=True)
val_iter = mx.io.NDArrayIter(mnist['test_data'], mnist['test_label'], batch_size)

#%% create input variable

data = mx.sym.var('data')
# Flatten the data from 4-D shape into 2-D (batch_size, num_channel*width*height)
data = mx.sym.flatten(data=data)

#%% Multilayer Perceptron with softmax

# The first fully-connected layer and the corresponding activation function
fc1  = mx.sym.FullyConnected(data=data, num_hidden=128)
act1 = mx.sym.Activation(data=fc1, act_type="relu")

# The second fully-connected layer and the corresponding activation function
fc2  = mx.sym.FullyConnected(data=act1, num_hidden = 64)
act2 = mx.sym.Activation(data=fc2, act_type="relu")

# MNIST has 10 classes
fc3  = mx.sym.FullyConnected(data=act2, num_hidden=10)
# Softmax with cross entropy loss
mlp  = mx.sym.SoftmaxOutput(data=fc3, name='softmax')

#%% Training
import logging
logging.getLogger().setLevel(logging.DEBUG)  # logging to stdout
# create a trainable module on CPU
mlp_model = mx.mod.Module(symbol=mlp, context=mx.cpu())
mlp_model.fit(train_iter,  # train data
              eval_data=val_iter,  # validation data
              optimizer='sgd',  # use SGD to train
              optimizer_params={'learning_rate':0.1},  # use fixed learning rate
              eval_metric='acc',  # report accuracy during training
              batch_end_callback = mx.callback.Speedometer(batch_size, 100), # output progress for each 100 data batches
              num_epoch=10)  # train for at most 10 dataset passes

Output of ipython console in Spyder

runfile('/home/thomas/workspace/clover-python/mnist.py', wdir='/home/thomas/workspace/clover-python')
INFO:root:train-labels-idx1-ubyte.gz exists, skipping download
INFO:root:train-images-idx3-ubyte.gz exists, skipping download
INFO:root:t10k-labels-idx1-ubyte.gz exists, skipping download
INFO:root:t10k-images-idx3-ubyte.gz exists, skipping download
INFO:root:Epoch[0] Batch [100]  Speed: 1304.05 samples/sec      accuracy=0.097921
INFO:root:Epoch[0] Batch [200]  Speed: 1059.19 samples/sec      accuracy=0.098200
INFO:root:Epoch[0] Batch [300]  Speed: 1178.64 samples/sec      accuracy=0.099600
INFO:root:Epoch[0] Batch [400]  Speed: 1292.71 samples/sec      accuracy=0.098900
INFO:root:Epoch[0] Batch [500]  Speed: 1394.21 samples/sec      accuracy=0.096500
INFO:root:Epoch[0] Train-accuracy=0.101212
INFO:root:Epoch[0] Time cost=47.798
INFO:root:Epoch[0] Validation-accuracy=0.098000
INFO:root:Epoch[1] Batch [100]  Speed: 1247.47 samples/sec      accuracy=0.097921
INFO:root:Epoch[1] Batch [200]  Speed: 1673.79 samples/sec      accuracy=0.098200
INFO:root:Epoch[1] Batch [300]  Speed: 1283.91 samples/sec      accuracy=0.099600
INFO:root:Epoch[1] Batch [400]  Speed: 1247.79 samples/sec      accuracy=0.098900
INFO:root:Epoch[1] Batch [500]  Speed: 1371.93 samples/sec      accuracy=0.096500
INFO:root:Epoch[1] Train-accuracy=0.101212
INFO:root:Epoch[1] Time cost=44.201
INFO:root:Epoch[1] Validation-accuracy=0.098000
INFO:root:Epoch[2] Batch [100]  Speed: 1387.72 samples/sec      accuracy=0.097921
INFO:root:Epoch[2] Batch [200]  Speed: 1196.37 samples/sec      accuracy=0.098200
INFO:root:Epoch[2] Batch [300]  Speed: 1220.44 samples/sec      accuracy=0.099600
INFO:root:Epoch[2] Batch [400]  Speed: 1387.75 samples/sec      accuracy=0.098900
INFO:root:Epoch[2] Batch [500]  Speed: 1279.58 samples/sec      accuracy=0.096500
INFO:root:Epoch[2] Train-accuracy=0.101212
INFO:root:Epoch[2] Time cost=46.929
INFO:root:Epoch[2] Validation-accuracy=0.098000
INFO:root:Epoch[3] Batch [100]  Speed: 1266.24 samples/sec      accuracy=0.097921

and so on…

Body:
Per Eric's comment, let's verify that you're running the same version of mxnet in each environment. You can type

import mxnet
print(mxnet.__version__)


问:
Switching the value with order
Is there a pythonic shorter version for the flowing code:</p>

```<code>def method(a,b)
    if a > b:
        pass
    else:
        a, b = b, a
</code>```

答:
You can do it in a single assignment:</p>

```<code>a, b = max(a, b), min(a, b)
</code>```

Title: Switching the value with order

Body:
Is there a pythonic shorter version for the flowing code:

def method(a,b)
    if a > b:
        pass
    else:
        a, b = b, a

Body:
You can do it in a single assignment:

a, b = max(a, b), min(a, b)


问:
How to remove fieldset border only but not the border of elements inside the fieldset?
Example below

I have a form with a fieldset and a button.  Both button and fieldset have borders around them.  I want the border gone only for the fieldset.  How?

(The CSS in my example removes both borders - for fieldset and for button when I want button to remain untoched)

#select_spec_form #submit_button {
  border: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="select_spec_form">
  <fieldset id="submit_button">
    <input name="submit[submit]" id="submit_button" value="View" type="submit">
  </fieldset>
</form></code>```

答:
First things first: you cannot use the same id for multiple elements. if you need to do this for css use the class attribute instead.

When it comes to the CSS you must refer to each object separately even though they both share the parent #select_spec_form.

#select_spec_form fieldset{
border:1px solid red;
}

#select_spec_form input{
border:1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="select_spec_form">
  <fieldset>
    <input name="submit[submit]" id="submit_button" value="View" type="submit">
  </fieldset>
</form></code>```

Body:
Example below

I have a form with a fieldset and a button.  Both button and fieldset have borders around them.  I want the border gone only for the fieldset.  How?

(The CSS in my example removes both borders - for fieldset and for button when I want button to remain untoched)

#select_spec_form #submit_button {
  border: 0;
}

<form id="select_spec_form">
  <fieldset id="submit_button">
    <input name="submit[submit]" id="submit_button" value="View" type="submit">
  </fieldset>
</form>

Body:
First things first: you cannot use the same id for multiple elements. if you need to do this for css use the class attribute instead.

When it comes to the CSS you must refer to each object separately even though they both share the parent #select_spec_form.

#select_spec_form fieldset{
border:1px solid red;
}

#select_spec_form input{
border:1px solid black;
}

<form id="select_spec_form">
  <fieldset>
    <input name="submit[submit]" id="submit_button" value="View" type="submit">
  </fieldset>
</form>


问:
How to find the Qt5 CMake module on Windows
I'm trying to make a very basic Qt5 application using CMake on Windows.
I used the documentation of Qt5 to use CMake, and my main.cpp file just contains a main function.

My CMakeLists.txt is exactly:

```<code>cmake_minimum_required(VERSION 2.8.9)

project(testproject)

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)

# Find the QtWidgets library
find_package(Qt5Widgets)

# Tell CMake to create the helloworld executable
add_executable(helloworld hello.cpp)

# Use the Widgets module from Qt 5.
qt5_use_modules(helloworld Widgets)
</code>```

When in MSysGit bash I enter

```<code>$ cmake -G"Visual Studio 11"
</code>```

I get this output:

```<code>$ cmake -G"Visual Studio 11"
-- The C compiler identification is MSVC 17.0.60204.1
-- The CXX compiler identification is MSVC 17.0.60204.1
-- Check for working C compiler using: Visual Studio 11
-- Check for working C compiler using: Visual Studio 11 -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler using: Visual Studio 11
-- Check for working CXX compiler using: Visual Studio 11 -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
CMake Warning at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5Widgets.cmake" in CMAKE_MODULE_PATH this project
  has asked CMake to find a package configuration file provided by
  "Qt5Widgets", but CMake did not find one.

  Could not find a package configuration file provided by "Qt5Widgets" with
  any of the following names:

    Qt5WidgetsConfig.cmake
    qt5widgets-config.cmake

  Add the installation prefix of "Qt5Widgets" to CMAKE_PREFIX_PATH or set
  "Qt5Widgets_DIR" to a directory containing one of the above files.  If
  "Qt5Widgets" provides a separate development package or SDK, be sure it has
  been installed.

CMake Error at CMakeLists.txt:17 (qt5_use_modules):
  Unknown CMake command "qt5_use_modules".

-- Configuring incomplete, errors occurred!
</code>```

Do you have any ideas?

答:
Here's a technique that takes advantage of cmake's ability to read the registry to coerce a registry value into locating the matching msvc's Qt5Config.cmake.

It attempts to use the highest available Qt5 version by doing a reverse sort on the various "5.x" folder names inside (e.g. C:\Qt\).

This could be placed inside a module as well, e.g. QtLocator.cmake.

```<code>SET(QT_MISSING True)
# msvc only; mingw will need different logic
IF(MSVC)
    # look for user-registry pointing to qtcreator
    GET_FILENAME_COMPONENT(QT_BIN [HKEY_CURRENT_USER\\Software\\Classes\\Applications\\QtProject.QtCreator.cpp\\shell\\Open\\Command] PATH)

    # get root path so we can search for 5.3, 5.4, 5.5, etc
    STRING(REPLACE "/Tools" ";" QT_BIN "${QT_BIN}")
    LIST(GET QT_BIN 0 QT_BIN)
    FILE(GLOB QT_VERSIONS "${QT_BIN}/5.*")
    LIST(SORT QT_VERSIONS)

    # assume the latest version will be last alphabetically
    LIST(REVERSE QT_VERSIONS)

    LIST(GET QT_VERSIONS 0 QT_VERSION)

    # fix any double slashes which seem to be common
    STRING(REPLACE "//" "/"  QT_VERSION "${QT_VERSION}")

    # do some math trickery to guess folder
    # - qt uses (e.g.) "msvc2012"
    # - cmake uses (e.g.) "1800"
    # - see also https://cmake.org/cmake/help/v3.0/variable/MSVC_VERSION.html
    MATH(EXPR QT_MSVC "2000 + (${MSVC_VERSION} - 600) / 100")

    # check for 64-bit os
    # may need to be removed for older compilers as it wasn't always offered
    IF(CMAKE_SYSTEM_PROCESSOR MATCHES 64)
        SET(QT_MSVC "${QT_MSVC}_64")
    ENDIF()
    SET(QT_PATH "${QT_VERSION}/msvc${QT_MSVC}")
    SET(QT_MISSING False)
ENDIF()

# use Qt_DIR approach so you can find Qt after cmake has been invoked
IF(NOT QT_MISSING)
    MESSAGE("-- Qt found: ${QT_PATH}")
    SET(Qt5_DIR "${QT_PATH}/lib/cmake/Qt5/")
    SET(Qt5Test_DIR "${QT_PATH}/lib/cmake/Qt5Test")
ENDIF()
</code>```

And then..

```<code># finally, use Qt5 + COMPONENTS technique, compatible with Qt_DIR
FIND_PACKAGE(Qt5 COMPONENTS Core Gui Widgets Xml REQUIRED)
</code>```

Body:
I'm trying to make a very basic Qt5 application using CMake on Windows.
I used the documentation of Qt5 to use CMake, and my main.cpp file just contains a main function.

My CMakeLists.txt is exactly:

cmake_minimum_required(VERSION 2.8.9)

project(testproject)

# Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)
# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)

# Find the QtWidgets library
find_package(Qt5Widgets)

# Tell CMake to create the helloworld executable
add_executable(helloworld hello.cpp)

# Use the Widgets module from Qt 5.
qt5_use_modules(helloworld Widgets)

When in MSysGit bash I enter

$ cmake -G"Visual Studio 11"

I get this output:

$ cmake -G"Visual Studio 11"
-- The C compiler identification is MSVC 17.0.60204.1
-- The CXX compiler identification is MSVC 17.0.60204.1
-- Check for working C compiler using: Visual Studio 11
-- Check for working C compiler using: Visual Studio 11 -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler using: Visual Studio 11
-- Check for working CXX compiler using: Visual Studio 11 -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
CMake Warning at CMakeLists.txt:11 (find_package):
  By not providing "FindQt5Widgets.cmake" in CMAKE_MODULE_PATH this project
  has asked CMake to find a package configuration file provided by
  "Qt5Widgets", but CMake did not find one.

  Could not find a package configuration file provided by "Qt5Widgets" with
  any of the following names:

    Qt5WidgetsConfig.cmake
    qt5widgets-config.cmake

  Add the installation prefix of "Qt5Widgets" to CMAKE_PREFIX_PATH or set
  "Qt5Widgets_DIR" to a directory containing one of the above files.  If
  "Qt5Widgets" provides a separate development package or SDK, be sure it has
  been installed.

CMake Error at CMakeLists.txt:17 (qt5_use_modules):
  Unknown CMake command "qt5_use_modules".

-- Configuring incomplete, errors occurred!

Do you have any ideas?

Body:
Here's a technique that takes advantage of cmake's ability to read the registry to coerce a registry value into locating the matching msvc's Qt5Config.cmake.

It attempts to use the highest available Qt5 version by doing a reverse sort on the various "5.x" folder names inside (e.g. C:\Qt\).

This could be placed inside a module as well, e.g. QtLocator.cmake.

SET(QT_MISSING True)
# msvc only; mingw will need different logic
IF(MSVC)
    # look for user-registry pointing to qtcreator
    GET_FILENAME_COMPONENT(QT_BIN [HKEY_CURRENT_USER\\Software\\Classes\\Applications\\QtProject.QtCreator.cpp\\shell\\Open\\Command] PATH)

    # get root path so we can search for 5.3, 5.4, 5.5, etc
    STRING(REPLACE "/Tools" ";" QT_BIN "${QT_BIN}")
    LIST(GET QT_BIN 0 QT_BIN)
    FILE(GLOB QT_VERSIONS "${QT_BIN}/5.*")
    LIST(SORT QT_VERSIONS)

    # assume the latest version will be last alphabetically
    LIST(REVERSE QT_VERSIONS)

    LIST(GET QT_VERSIONS 0 QT_VERSION)

    # fix any double slashes which seem to be common
    STRING(REPLACE "//" "/"  QT_VERSION "${QT_VERSION}")

    # do some math trickery to guess folder
    # - qt uses (e.g.) "msvc2012"
    # - cmake uses (e.g.) "1800"
    # - see also https://cmake.org/cmake/help/v3.0/variable/MSVC_VERSION.html
    MATH(EXPR QT_MSVC "2000 + (${MSVC_VERSION} - 600) / 100")

    # check for 64-bit os
    # may need to be removed for older compilers as it wasn't always offered
    IF(CMAKE_SYSTEM_PROCESSOR MATCHES 64)
        SET(QT_MSVC "${QT_MSVC}_64")
    ENDIF()
    SET(QT_PATH "${QT_VERSION}/msvc${QT_MSVC}")
    SET(QT_MISSING False)
ENDIF()

# use Qt_DIR approach so you can find Qt after cmake has been invoked
IF(NOT QT_MISSING)
    MESSAGE("-- Qt found: ${QT_PATH}")
    SET(Qt5_DIR "${QT_PATH}/lib/cmake/Qt5/")
    SET(Qt5Test_DIR "${QT_PATH}/lib/cmake/Qt5Test")
ENDIF()

And then..

# finally, use Qt5 + COMPONENTS technique, compatible with Qt_DIR
FIND_PACKAGE(Qt5 COMPONENTS Core Gui Widgets Xml REQUIRED)


问:
memcpy and C++ class templates - how to use it?
So.. How can we call something like
memcpy(dataCopy, data, length); to copy abstract data T?

Or if abstract T is not safe lets say we know that T is a POD (plain old data, basically a C struct) - is it possible to copy it?

答: Do you mean working for some arbitrary C++ type T?  Unless you know that T is a POD (plain old data, basically a C struct) type, it is not safe to copy objects of type T with memcpy.  That would prevent T's copy constructor from running, for example, which might lead to an incorrect copy (trying to memcpy an std::vector would not copy the data buffer, for example).


问:
HSQLDB + junit : intermittent "connection exception: closed"
I am seeing a strange problem when using HSQLDB in my unit test.

I have a unit test using in-memory HSQLDB which is failing intermittently with the following:

```<code>org.hsqldb.HsqlException: connection exception: closed
</code>```

along with

```<code>org.hsqldb.HsqlException: connection exception: connection does not exist
</code>```

My suspicion is that the in-memory DB is somehow persisting between the different test runs.

My test looks like this:

```<code>private static final String DRIVER = "org.hsqldb.jdbc.JDBCDriver";
private static final String URL = "jdbc:hsqldb:mem:test2";

@BeforeClass
public static void init() throws SQLException, ClassNotFoundException, IOException {
    Class.forName(DRIVER);
    populateDatabase();
}

private static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(URL, user, user);
}

private static void populateDatabase() throws SQLException {
    try (Connection connection = getConnection(); Statement statement = connection
            .createStatement()) {
        statement.execute(
                "CREATE TABLE employee (name VARCHAR(50) NOT NULL, "
                        + " age INT NOT NULL, outputcol FLOAT)");
        connection.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@AfterClass
public static void destroy() throws SQLException, ClassNotFoundException, IOException {
    try (Connection connection = DriverManager
            .getConnection(URL + ";shutdown=true", user, user);
            Statement statement = connection.createStatement()) {
        statement.executeUpdate("DROP TABLE employee");
        connection.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

The fact that the error is inconsistent points to something hanging around in memory between test runs, which is bizarre.

I have tried:

adding the 'shutdown=true' option to the destroy method

making the DB name in the URL different in each class

using @After and @AfterClass for cleaning up the connection

changing the name of the hsqldb each time the test is run

Note that the test should create a DB in memory, then pass the credentials to the class under test, which uses those credentials to connect via DriverManager.  After the test is over, we drop the tables and basically want to then empty and destroy the DB.

I'm running these tests from the command line with mvn clean install.

答:
The semantics of ;shutdown=true added to a URL is as follows:

it is effective on the first connection to the database, not on subsequent connections

when the last connection is closed (by calling the close() method), the database is also shutdown

You can execute SHUTDOWN as an SQL statement in your destroy() method, instead of counting on all connections getting closed.

Body:
I am seeing a strange problem when using HSQLDB in my unit test.

I have a unit test using in-memory HSQLDB which is failing intermittently with the following:

org.hsqldb.HsqlException: connection exception: closed

along with

org.hsqldb.HsqlException: connection exception: connection does not exist

My suspicion is that the in-memory DB is somehow persisting between the different test runs.

My test looks like this:

private static final String DRIVER = "org.hsqldb.jdbc.JDBCDriver";
private static final String URL = "jdbc:hsqldb:mem:test2";

@BeforeClass
public static void init() throws SQLException, ClassNotFoundException, IOException {
    Class.forName(DRIVER);
    populateDatabase();
}

private static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(URL, user, user);
}

private static void populateDatabase() throws SQLException {
    try (Connection connection = getConnection(); Statement statement = connection
            .createStatement()) {
        statement.execute(
                "CREATE TABLE employee (name VARCHAR(50) NOT NULL, "
                        + " age INT NOT NULL, outputcol FLOAT)");
        connection.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@AfterClass
public static void destroy() throws SQLException, ClassNotFoundException, IOException {
    try (Connection connection = DriverManager
            .getConnection(URL + ";shutdown=true", user, user);
            Statement statement = connection.createStatement()) {
        statement.executeUpdate("DROP TABLE employee");
        connection.commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The fact that the error is inconsistent points to something hanging around in memory between test runs, which is bizarre.

I have tried:

adding the 'shutdown=true' option to the destroy method

making the DB name in the URL different in each class

using @After and @AfterClass for cleaning up the connection

changing the name of the hsqldb each time the test is run

Note that the test should create a DB in memory, then pass the credentials to the class under test, which uses those credentials to connect via DriverManager.  After the test is over, we drop the tables and basically want to then empty and destroy the DB.

I'm running these tests from the command line with mvn clean install.


问:
Long text pushing other elements off screen with react native
I'm trying to build a layout in React-Native using Flexbox and I'm having trouble when the text is long. I want the layout to look like this:

However, when the blue text gets long, it pushes the date off of the right side of the screen like this:

I'm intentionally making the text stay on 1 line. What I want is for the blue text to expand as much as possible without making the text shrink. I'm new to RN and my work with CSS is very limited so I don't have much experience doing things like this. Here is my stylesheet code:

```<code>const styles = StyleSheet.create({
  textContainer: {
    flex: 1
  },
  separator: {
    height: 1,
    backgroundColor: '#dddddd'
  },
  title: {
    fontSize: 25,
    fontWeight: 'bold',
    color: '#48BBEC'
  },
  subtitle: {
    fontSize: 20,
    color: '#656565'
  },
  dateContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'flex-end'
  },
  rowContainer: {
    flexDirection: 'row',
    padding: 10
  }
});
</code>```

And, finally, my layout code:

```<code><TouchableHighlight
    underlayColor='#dddddd'>
      <View style={styles.rowContainer}>
          <View  cstyle={styles.textContainer}>
            <Text numberOfLines={1} style={styles.title}>{rowData.name}</Text>
            <Text style={styles.subtitle}>{rowData.teacher}</Text>
          </View>
          <View style={styles.dateContainer}>
            <Text style={styles.subtitle}>{result}</Text>
          </View>
        <View style={styles.separator}/>
      </View>
    </TouchableHighlight>
</code>```

答:
I ended up solving this by measuring the parent view's width (with the onLayout callback) and then setting the width of the text's parent to the remainder.

This means having some state in the component, but it could be turned in to  a general component with a left-side dynamic-sized component and a right-side static component.

Body:
I'm trying to build a layout in React-Native using Flexbox and I'm having trouble when the text is long. I want the layout to look like this:

However, when the blue text gets long, it pushes the date off of the right side of the screen like this:

I'm intentionally making the text stay on 1 line. What I want is for the blue text to expand as much as possible without making the text shrink. I'm new to RN and my work with CSS is very limited so I don't have much experience doing things like this. Here is my stylesheet code:

const styles = StyleSheet.create({
  textContainer: {
    flex: 1
  },
  separator: {
    height: 1,
    backgroundColor: '#dddddd'
  },
  title: {
    fontSize: 25,
    fontWeight: 'bold',
    color: '#48BBEC'
  },
  subtitle: {
    fontSize: 20,
    color: '#656565'
  },
  dateContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'flex-end'
  },
  rowContainer: {
    flexDirection: 'row',
    padding: 10
  }
});

And, finally, my layout code:

<TouchableHighlight
    underlayColor='#dddddd'>
      <View style={styles.rowContainer}>
          <View  cstyle={styles.textContainer}>
            <Text numberOfLines={1} style={styles.title}>{rowData.name}</Text>
            <Text style={styles.subtitle}>{rowData.teacher}</Text>
          </View>
          <View style={styles.dateContainer}>
            <Text style={styles.subtitle}>{result}</Text>
          </View>
        <View style={styles.separator}/>
      </View>
    </TouchableHighlight>


问:
Successful build in Maven still showing errors in Eclipse
I'm having something quite peculiar here, my build is successful in maven when I type "mvn clean install" however once imported into Eclipse it's showing errors.

See for yourself:

I guess exluding quartz from the `pom.xml solved the problem but I'd like to know why.

PS: Here is the pom.xml in case you want to see it:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.nantes.mpclient</groupId>
  <artifactId>MyClient</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MyClient</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.nantes.mp</groupId>
        <artifactId>MyEjb</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.jbossas</groupId>
        <artifactId>jboss-as-client</artifactId>
        <version>5.1.0.GA</version>
        <type>pom</type>
    </dependency>
  </dependencies>
</project>
```

###EDIT
As you can see quartz is here:

答:
In my case there were also problems with Java build path like the following:
"Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment." Fixing this resolved compilation errors.</p>

Body:
I'm having something quite peculiar here, my build is successful in maven when I type "mvn clean install" however once imported into Eclipse it's showing errors.

See for yourself:

I guess exluding quartz from the `pom.xml solved the problem but I'd like to know why.

PS: Here is the pom.xml in case you want to see it:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.nantes.mpclient</groupId>
  <artifactId>MyClient</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MyClient</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.nantes.mp</groupId>
        <artifactId>MyEjb</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.jbossas</groupId>
        <artifactId>jboss-as-client</artifactId>
        <version>5.1.0.GA</version>
        <type>pom</type>
    </dependency>
  </dependencies>
</project>

###EDIT
As you can see quartz is here:


问:
SQL Joins vs Single Table : Performance Difference?
I am trying to stick to the practice of keeping the database normalized, but that leads to the need to run multiple join queries. Is there a performance degradation if many queries use joins vs having a call to a single table that might contain redundant data?</p>

答:
One of the ultimate hyperoptimizations available through some of the cloud sites is, in fact, using a smaller number of wider, limited-capability tables for efficiency. So far in the future if you need to wildly scale, this is one way. But it's not considered desirable practice for any relational dbms (which those aren't).

If you're having performance problems, there are a lot of things to work on first, before any kind of denormalizing.

OwnerDisplayName: zsharp

LastEditorDisplayName: mwigdahl

OwnerDisplayName: le dorfier


问:
Removing \r from lines read from file
I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

```<code>    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOutput.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }
</code>```

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

```<code>cleanLine.Replace("\r",""); //assigns a value to nothing
</code>```

I should have assigned cleanLine to cleanLine.Replace();

```<code>cleanLine = cleanLine.Replace("\r","");
</code>```

答: I'm pretty sure running fileOutput.Replace("\r","") would be better than calling a replace for each of the strings attained after the split. It might fix your problem as well.

Title: Removing \r from lines read from file

Body:
I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOutput.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

cleanLine.Replace("\r",""); //assigns a value to nothing

I should have assigned cleanLine to cleanLine.Replace();

cleanLine = cleanLine.Replace("\r","");


问:
SCSS partials (@import) vs. Webpack file import?
I'm building a simple app and am setting up my own Webpack configuration to better understand how it works. Currently, I have one main.scss file (where I'm writing all my styles) which I'm importing into my index.js file (which is the entry point I've set for Webpack). So far, so good.

Now I want to split my SCSS into separate, smaller files (normalize, variables, mixins, etc.) Before Webpack, what I'd do was make every file a SCSS partial and then import all of them into my main.scss file. But now that I'm using Webpack, I'm wondering if I should keep doing that or if I should import all of my SCSS files into Webpack instead and forgo partials entirely? Any clarification on the topic would be useful; I haven't found much online about the advantages of one approach over the other.

答:
Here's a setup I've used in past React projects:

import main.scss from your index.js

In your main.scss use import-glob-loader to automate the process of importing new sass files -- it's easy to forget to add every new sass file to main.scss. Your main.scss would look something like:

main.scss

```<code>@import "src/normalize"
@import "src/components/**/*"
</code>```

Webpack.config.js (Webpack 2+)

```<code> rules: [
    {
        test: /\.scss/,
        enforce: "pre",
        loader: "import-glob-loader"
    },
    // ... other loaders
]
</code>```

This will automatically bundle new sass files that you add to src. When using this setup it's important to minimize @imports in your sass files as this will increase the overall size of the generated CSS file. The exception is @importing files that only contain mixins and variables, as these imports do not add to the file size.

This setup makes the most sense when used with a framework like React, where you would have many sass files in many different directories (usually in the respective component's directory)

Body:
Here's a setup I've used in past React projects:

import main.scss from your index.js

In your main.scss use import-glob-loader to automate the process of importing new sass files -- it's easy to forget to add every new sass file to main.scss. Your main.scss would look something like:

main.scss

@import "src/normalize"
@import "src/components/**/*"

Webpack.config.js (Webpack 2+)

 rules: [
    {
        test: /\.scss/,
        enforce: "pre",
        loader: "import-glob-loader"
    },
    // ... other loaders
]

This will automatically bundle new sass files that you add to src. When using this setup it's important to minimize @imports in your sass files as this will increase the overall size of the generated CSS file. The exception is @importing files that only contain mixins and variables, as these imports do not add to the file size.

This setup makes the most sense when used with a framework like React, where you would have many sass files in many different directories (usually in the respective component's directory)


问:
Load and store contents of a webpage on local host with PHP or Javascript
I need to read and store contents of a page, stored on my local PC, with PHP or JavaScript .
I am running a loaclhost on my PC at the following address and it has contents that I like to load the page and store the contents:

http://10.0.0.210:10009

obviously, I cannot use CURL or file_get_contents() from PHP as they pertain to the server side.
I could do a Location : url and open the local page, but I need to get the content and store it in a variable, so I can parse them.
What is the best way to achieve this? Javascript, jQuery. How? Thank you

答: Try out JS APIs like localStorage, indexDB, sessionStorage for data. If you want to cache files, try out Application Cache.</p>


问:
Bootstrap 4 Container with half reaching to edge
I'm trying to achieve a .container with two halves.

The left half acts normally as a .col-6, and the right half stretches all the way to the right side of the screen, as if it were a .col-6 inside of a .container-fluid.

So, similiar to this...

```<code><section>
  <div class="container">
    <div class="row">
      <div class="col-md-6">
        <p>Curabitur ipsum nisl, volutpat non vulputate in, aliquet id ipsum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin dolor velit, tristique eget leo eu.</p>
      </div>
      <div class="col-md-6"> <!-- this needs to stretch out all the way to the right -->
        <p>Aliquam dapibus consequat diam, a luctus nisi fermentum eu. Proin at enim at dolor convallis vestibulum. Etiam tempor vel enim sed sodales. Vestibulum rhoncus odio felis.</p>
        <p>Sed sodales turpis posuere vel. Proin at scelerisque elit, vitae feugiat lectus. Ut nisl dui, pulvinar at fringilla vitae, bibendum imperdiet mi. </p>
      </div>
    </div>
  </div>
</section>
</code>```

I hope that makes sense, thanks in advance.

答:
I don't think Bootstrap 4 has an out-of-the-box solution for such a layout, however it can be implemented easily with a couple of additional style sets.

In the solution below I approach this with a top level .container-fluid tag, as that covers the entire viewport width. Then for mimicking a “half container” in the left column, I have created the .container-half class. This is based on the .container class but the width of it is set to the half of the original. Also, in order to demonstrate how responsivity can be taken care of, the .container-half-md-left serves as an example.

Note: the css below serves as an example with manually crafted media queries. In production I would compile the entire set from scss.

Check this CodePen.

HTML

```<code><section>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 px-0" style="background-color: LightCyan;">
                <div class="container container-half container-half-md-left h-100" style="background-color: LightBlue;">
                    <p>Curabitur ipsum nisl, volutpat non vulputate in, aliquet id ipsum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin dolor velit, tristique eget leo eu.</p>
                </div>
            </div>

            <div class="col-md-6" style="background-color: LightSteelBlue;">
                <p>Aliquam dapibus consequat diam, a luctus nisi fermentum eu. Proin at enim at dolor convallis vestibulum. Etiam tempor vel enim sed sodales. Vestibulum rhoncus odio felis.</p>
                <p>Sed sodales turpis posuere vel. Proin at scelerisque elit, vitae feugiat lectus. Ut nisl dui, pulvinar at fringilla vitae, bibendum imperdiet mi. </p>
            </div>
        </div>
    </div>
</section>
</code>```

CSS

```<code>@media (min-width: 576px) {
    .container-half { max-width: calc(540px / 2); }
}

@media (min-width: 768px) {
    .container-half { max-width: calc(720px / 2); }
    .container-half-md-left { margin-right: 0; }
}

@media (min-width: 992px) {
    .container-half { max-width: calc(960px / 2); }
}

@media (min-width: 1200px) {
    .container-half { max-width: calc(1140px / 2); }
}
</code>```

Body:
I'm trying to achieve a .container with two halves.

The left half acts normally as a .col-6, and the right half stretches all the way to the right side of the screen, as if it were a .col-6 inside of a .container-fluid.

So, similiar to this...

Curabitur ipsum nisl, volutpat non vulputate in, aliquet id ipsum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin dolor velit, tristique eget leo eu.

Aliquam dapibus consequat diam, a luctus nisi fermentum eu. Proin at enim at dolor convallis vestibulum. Etiam tempor vel enim sed sodales. Vestibulum rhoncus odio felis.

Sed sodales turpis posuere vel. Proin at scelerisque elit, vitae feugiat lectus. Ut nisl dui, pulvinar at fringilla vitae, bibendum imperdiet mi.

I hope that makes sense, thanks in advance.

Body:
I don't think Bootstrap 4 has an out-of-the-box solution for such a layout, however it can be implemented easily with a couple of additional style sets.

In the solution below I approach this with a top level .container-fluid tag, as that covers the entire viewport width. Then for mimicking a “half container” in the left column, I have created the .container-half class. This is based on the .container class but the width of it is set to the half of the original. Also, in order to demonstrate how responsivity can be taken care of, the .container-half-md-left serves as an example.

Note: the css below serves as an example with manually crafted media queries. In production I would compile the entire set from scss.

Check this CodePen.

HTML

<section>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 px-0" style="background-color: LightCyan;">
                <div class="container container-half container-half-md-left h-100" style="background-color: LightBlue;">
                    <p>Curabitur ipsum nisl, volutpat non vulputate in, aliquet id ipsum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin dolor velit, tristique eget leo eu.</p>
                </div>
            </div>

            <div class="col-md-6" style="background-color: LightSteelBlue;">
                <p>Aliquam dapibus consequat diam, a luctus nisi fermentum eu. Proin at enim at dolor convallis vestibulum. Etiam tempor vel enim sed sodales. Vestibulum rhoncus odio felis.</p>
                <p>Sed sodales turpis posuere vel. Proin at scelerisque elit, vitae feugiat lectus. Ut nisl dui, pulvinar at fringilla vitae, bibendum imperdiet mi. </p>
            </div>
        </div>
    </div>
</section>

CSS

@media (min-width: 576px) {
    .container-half { max-width: calc(540px / 2); }
}

@media (min-width: 768px) {
    .container-half { max-width: calc(720px / 2); }
    .container-half-md-left { margin-right: 0; }
}

@media (min-width: 992px) {
    .container-half { max-width: calc(960px / 2); }
}

@media (min-width: 1200px) {
    .container-half { max-width: calc(1140px / 2); }
}


问:
Class instance reference from property
I have a class with an annotation as a property

```<code>class UserClass {
   var id : String?
   var annot : MKPointAnnotation?
}
</code>```

Then I make several instances of this class like:

```<code>var user1 = UserClass()
</code>```

and then define, create and add each user's annotation on the map.

Later in the code user taps on an annotation and I need a reference to the corresponding user instance. How do I get it?

```<code>@objc(mapView:didSelectAnnotationView:) func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annot = view.annotation as? MKPointAnnotation {
        let user = // Need the user instance here to acces user id etc
    }
}
</code>```

答:
You probably have all the users in an array in the class you are populating the map view with the annotations. If not, have all the users stored in an array and then:</p>

```<code>@objc(mapView:didSelectAnnotationView:) func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
   if let annot = view.annotation as? MKPointAnnotation {
      let user = usersArray.first(where:{$0.annot == annot})
   }
}
</code>```

Title: Class instance reference from property

Body:
I have a class with an annotation as a property

class UserClass {
   var id : String?
   var annot : MKPointAnnotation?
}

Then I make several instances of this class like:

var user1 = UserClass()

and then define, create and add each user's annotation on the map.

Later in the code user taps on an annotation and I need a reference to the corresponding user instance. How do I get it?

@objc(mapView:didSelectAnnotationView:) func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    if let annot = view.annotation as? MKPointAnnotation {
        let user = // Need the user instance here to acces user id etc
    }
}

Body:
You probably have all the users in an array in the class you are populating the map view with the annotations. If not, have all the users stored in an array and then:

@objc(mapView:didSelectAnnotationView:) func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
   if let annot = view.annotation as? MKPointAnnotation {
      let user = usersArray.first(where:{$0.annot == annot})
   }
}


问:
Can't write large owl file with Jena
I'm trying to convert data contained in a database table in a set of triples so I'm writing an owl file using Jena java library.
I have successfully done it with a small number of table records (100) which corresponds to nearly 20.000 rows in the .owl file and I'm happy with it.

To write the owl file I have used the following code (m is an OntModel object):

```<code> BufferedWriter out = null;
 try {
    out = new BufferedWriter (new FileWriter(FILENAME));
    m.write(out);
    out.close();
 }catch(IOException e) {};
</code>```

Unfortunately when I try to do the same with the entire result set of the table (800.000 records) eclipse console shows me the exception:

```<code>Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
</code>```

the exception is raised by

```<code>m.write(out);
</code>```

I'm absolutely sure the model is correctly filled because I tried to execute the program without creating the owl file and all worked fine.
To fix it, I tried to increase heap memory setting -Xmx4096Minrun->configuration->vm arguments but the error still appears.

I'm executing the application on a macbook so I have no unlimited memory. Are there chances to complete the task? maybe is there a more efficient way to store the model?

答:
The default format is RDF/XML is a pretty form, but to calculate the "pretty", quite a lot of work needs to be done before writing starts. This includes building up internal datstructures. Some shapes of data cause quite extensive work to be done searching for the "most pretty" variation.

RDF/XML in pretty form is the most expensive format.  Even the pretty Turtle form is cheaper though it still involves some preparation calculations.

To write in RDF/XML in a simpler format, with no complex pretty features:

RDFDataMgr.write(System.out, m, RDFFormat.RDFXML_PLAIN);

Output streams are preferred, and the output will be UTF-8 - "new BufferedWriter (new FileWriter(FILENAME));" will use the platform default character set.

See the documentation for other formats and variations:

https://jena.apache.org/documentation/io/rdf-output.html

such as RDFFormat.TURTLE_BLOCKS.

Title: Can't write large owl file with Jena

Body:
I'm trying to convert data contained in a database table in a set of triples so I'm writing an owl file using Jena java library.
I have successfully done it with a small number of table records (100) which corresponds to nearly 20.000 rows in the .owl file and I'm happy with it.

To write the owl file I have used the following code (m is an OntModel object):

 BufferedWriter out = null;
 try {
    out = new BufferedWriter (new FileWriter(FILENAME));
    m.write(out);
    out.close();
 }catch(IOException e) {};

Unfortunately when I try to do the same with the entire result set of the table (800.000 records) eclipse console shows me the exception:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

the exception is raised by

m.write(out);

I'm absolutely sure the model is correctly filled because I tried to execute the program without creating the owl file and all worked fine.
To fix it, I tried to increase heap memory setting -Xmx4096Minrun->configuration->vm arguments but the error still appears.

I'm executing the application on a macbook so I have no unlimited memory. Are there chances to complete the task? maybe is there a more efficient way to store the model?


问:
Azure B2B with SharePoint Online and Yammer
I have a scenario that I am hoping someone can assist me with. I have a requirement to build an extranet in SharePoint Online (Office 365).

We have a main Office 365 Tenant. There are 15 member organisations that need access and these DO NOT have Office 365. on premise only.

So I can use Azure B2B to grant access to SharePoint Sites no problems. I need the social aspect and Yammer Fits PERFECTLY but identities are separate.

I can create and External Yammer Network and invite users but obviously these are a separate set of credentials to that of Azure AD.

Has anyone done such a thing and is there a way to grant Azure B2B users access to an external Yammer network?

答:
Yammer should allow you to sync with your Azure Active Directory. This should allow users to have the same logins.

Here is some information I found on this matter:

https://products.office.com/en-gb/yammer/yammer-network-administration


问:
Reading binary values in c
I can read unsigned ints from a binary file but one of the values is printing out negative.

Expected values:

45788331,
281302247,
461354227,
13127,
299215653,
2356985123,

Values printed out:

45788331,
281302247,
461354227,
13127,
299215653,
-1932982173,

The 6th value is printing out as negative but I am reading a list of unsigned ints?

My code below

```<code>#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        FILE * fp;
        ssize_t read;
        int r = 0;

        fp = fopen("numbers.bin", "rb");
        if (fp == NULL)
                exit(-1);

        while(fread(&r, sizeof(unsigned int), 1, fp) == 1)
        {
                printf("%d\n", r);
        }

        fclose(fp);
        if (line) free(line);

        exit(0);
}
</code>```

答:
printf("%d\n", r); prints out a signed decimal integer.

You want: printf("%u\n", r);

Additionally, r is declared as int not unsigned int.

Title: Reading binary values in c

Body:
I can read unsigned ints from a binary file but one of the values is printing out negative.

Expected values:

45788331,
281302247,
461354227,
13127,
299215653,
2356985123,

Values printed out:

45788331,
281302247,
461354227,
13127,
299215653,
-1932982173,

The 6th value is printing out as negative but I am reading a list of unsigned ints?

My code below

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
        FILE * fp;
        ssize_t read;
        int r = 0;

        fp = fopen("numbers.bin", "rb");
        if (fp == NULL)
                exit(-1);

        while(fread(&r, sizeof(unsigned int), 1, fp) == 1)
        {
                printf("%d\n", r);
        }

        fclose(fp);
        if (line) free(line);

        exit(0);
}


问:
CakePHP confusion over ACL
On the CakePHP website it shows that you would create a users table and a groups table for users and user groups using ACL: http://book.cakephp.org/view/1544/Preparing-our-Application

However most other tutorials e.g. NetTuts shows creating three tables (in addition to the users table) to use ACL: http://net.tutsplus.com/tutorials/php/how-to-use-cakephps-access-control-lists/

What is the difference between the two? Thanls

答:
if you are asking about the extra tables named Acos,Aros and aros_acos

In both tutorial we need to use these tables.In the cakephp.org. there is a section called Initialize the Db Acl tables where they running a command to create those tables. where as in nettuts they showing us creating it manually.

Any way cakePHP need 5 tables to run the ACL perfectly.In that Acos,Aros and aros_acos are cakePHP defined tables and Users and Groups are user defined tables.

CakePHP is storing the User permissions as a Tree with Aros(Access Request Objects means users)  hasAndBeongsToMany relation with Acos (Access Control Objects means actions)

Title: CakePHP confusion over ACL


问:
How does glmnet standardize variables when weights are present?
glmnet allows the user to input a vector of observation weights through the weights argument. glmnet also standardizes (by default) the predictor variables to have zero mean and unit variance. My question is: when weights is provided, does glmnet standardize the predictors using the weighted mean (and standard deviation) of each column or the unweighted mean (and standard deviation)?

答:
For what it's worth, consistent with the accepted answer, the weights in glmnet are sampling weights, and not inverse variance weights. For example if you have many more observations than unique observations, you can compress your dataset and get the same coefficient estimates:

```<code>n <- 50
m <- 5

y_norm <- rnorm(n)
y_bool <- rbinom(n,1,.5)
x <- matrix(rnorm(n*m),n)
w <- rpois(n,3) + 1 # weights
w_indx <- rep(1:n,times=w) # weights index

m1 = glmnet(x, y_norm, weights = w)
m2 = glmnet(x[w_indx,] ,y_norm[w_indx])
all.equal(coef(m1,s=.1),
          coef(m2,s=.1))
>>> TRUE

M1 = glmnet(x,y_bool,weights = w,family = "binomial")
M2 = glmnet(x[w_indx,],y_bool[w_indx],family = "binomial")
all.equal(coef(M1,s=.1),
          coef(M2,s=.1))
>>> TRUE
</code>```

Of course, a bit more care needs to be used when using weights with cv.glmnet since the weights of aggregated records should be spread across folds using a multinomial distribution...

Body:
For what it's worth, consistent with the accepted answer, the weights in glmnet are sampling weights, and not inverse variance weights. For example if you have many more observations than unique observations, you can compress your dataset and get the same coefficient estimates:

n <- 50
m <- 5

y_norm <- rnorm(n)
y_bool <- rbinom(n,1,.5)
x <- matrix(rnorm(n*m),n)
w <- rpois(n,3) + 1 # weights
w_indx <- rep(1:n,times=w) # weights index

m1 = glmnet(x, y_norm, weights = w)
m2 = glmnet(x[w_indx,] ,y_norm[w_indx])
all.equal(coef(m1,s=.1),
          coef(m2,s=.1))
>>> TRUE

M1 = glmnet(x,y_bool,weights = w,family = "binomial")
M2 = glmnet(x[w_indx,],y_bool[w_indx],family = "binomial")
all.equal(coef(M1,s=.1),
          coef(M2,s=.1))
>>> TRUE

Of course, a bit more care needs to be used when using weights with cv.glmnet since the weights of aggregated records should be spread across folds using a multinomial distribution...