问:
c# returning from sub form to main form at same location
I have a main form , from where another form is opened to verify password, I want to return to same point from where this form was opened so that I can proceed accorddingly to the password verification, please see the code:-</p>

```<code>        this.TopMost = false;

        FormPassword fPass = new FormPassword();

        fPass.Show();

        //I need it should wait here , but dosent,

        // i tried adding here

        // while(fPass.Visible); //but didn't helped

        if (Variables.IsPasswordCorrect == true)//IsPasswordCorrect defined in variables.cs, to make it common in both the forms
        {

            DialogResult result2 = MessageBox.Show("Start the Process?", "START?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

            if (result2 == DialogResult.Yes)
            {
                StartAll();

            }

        }
</code>```

答:
If you use ShowDialog like you are doing with result2, your code will wait for the dialog to complete before continuing:</p>

```<code>  this.TopMost = false;

  FormPassword fPass = new FormPassword();

  fPass.ShowDialog();
</code>```

Body:
I have a main form , from where another form is opened to verify password, I want to return to same point from where this form was opened so that I can proceed accorddingly to the password verification, please see the code:-

        this.TopMost = false;

        FormPassword fPass = new FormPassword();

        fPass.Show();

        //I need it should wait here , but dosent,

        // i tried adding here

        // while(fPass.Visible); //but didn't helped

        if (Variables.IsPasswordCorrect == true)//IsPasswordCorrect defined in variables.cs, to make it common in both the forms
        {

            DialogResult result2 = MessageBox.Show("Start the Process?", "START?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

            if (result2 == DialogResult.Yes)
            {
                StartAll();

            }

        }

Body:
If you use ShowDialog like you are doing with result2, your code will wait for the dialog to complete before continuing:

  this.TopMost = false;

  FormPassword fPass = new FormPassword();

  fPass.ShowDialog();


来源: stackexchange

问:
Android Studio - Bottom navigation crash when changing between fragments
I am creating and app and so far everything was good. Today I was dealing with the data in a fragment to reach my webservice and return the json and then insert that data into my sqlite and after that show it in a listview and update the data second by second.

Everything was right until i find that if I click too fast in the bottom navigation where the items from the fragments are, it will crash the aplication while it is doing the transaction on the fragment. it only occurs when I click between that fragment and more 1 of the other 4.

So my question is, is there anyway I can deal with this problem? like if I click in another item from bottom navigation the transitions from the last item stops? if so how?

答:
As far as I can understand (with little info), the issue is mostly likely that the fragment is getting destroyed (when the code logic is trying to connect to the server and return the json data to the app) and you're trying to access the destroyed fragment elements (or items, here in this case, list view, to populate it with the received data).

Inside your each and every fragment, after the json data is received and before doing anything else, check if the fragment is still visible and attached to the activity and also the activity is not destroyed.

```<code>// Check the activity is not destroyed and the
// fragment is still connected to the activity
if (getActivity() != null && isAdded()) {
    // Parse the JSON data
    // Write to your SQL database
    // Load the data into the list view
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As far as I can understand (with little info), the issue is mostly likely that the fragment is getting destroyed (when the code logic is trying to connect to the server and return the json data to the app) and you're trying to access the destroyed fragment elements (or items, here in this case, list view, to populate it with the received data).

Inside your each and every fragment, after the json data is received and before doing anything else, check if the fragment is still visible and attached to the activity and also the activity is not destroyed.

// Check the activity is not destroyed and the
// fragment is still connected to the activity
if (getActivity() != null && isAdded()) {
    // Parse the JSON data
    // Write to your SQL database
    // Load the data into the list view
}


问:
Compound/Complex C-String in Xcode/Cocoa
I am creating an SQLite3 program.  I am creating the database within the code.  I have about 15 columns. Example below:

```<code>NSString *createSQL = "CREATE TABLE IF NOT EXISTS FIELDS (DATE TEXT PRIMARY KEY,
                   NAME TEXT,           /*COLUMN #1 */
                   CLASS TEXT,          /*COLUMN #2 */
                   ...
                   COMPLETED TEXT);";  /*COLUMN #15 */
</code>```

When I compile I am getting "missing terminating character error.  I did some research and saw that because it is a C-String it will process the CR\LF as a continuation character. I don't want to create a line of codes that scrolls the right most margin of the screen every time I need to do something with SQL.   Is there a way that I can create a string that can be broken up on separate lines without getting this error?

答:
In Objective-C, just as in C, you can use the line continuation marker \ to break a string literal across multiple lines. You example would be (note the @ to indicate an NSString literal):

```<code>NSString *createSQL = @"CREATE TABLE IF NOT EXISTS FIELDS (DATE TEXT PRIMARY KEY, \
                   NAME TEXT,  \       /*COLUMN #1 */
                   CLASS TEXT, \       /*COLUMN #2 */
                   ...         \
                   COMPLETED TEXT);";  /*COLUMN #15 */
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am creating an SQLite3 program.  I am creating the database within the code.  I have about 15 columns. Example below:

NSString *createSQL = "CREATE TABLE IF NOT EXISTS FIELDS (DATE TEXT PRIMARY KEY,
                   NAME TEXT,           /*COLUMN #1 */
                   CLASS TEXT,          /*COLUMN #2 */
                   ...
                   COMPLETED TEXT);";  /*COLUMN #15 */

When I compile I am getting "missing terminating character error.  I did some research and saw that because it is a C-String it will process the CR\LF as a continuation character. I don't want to create a line of codes that scrolls the right most margin of the screen every time I need to do something with SQL.   Is there a way that I can create a string that can be broken up on separate lines without getting this error?

Body:
In Objective-C, just as in C, you can use the line continuation marker \ to break a string literal across multiple lines. You example would be (note the @ to indicate an NSString literal):

NSString *createSQL = @"CREATE TABLE IF NOT EXISTS FIELDS (DATE TEXT PRIMARY KEY, \
                   NAME TEXT,  \       /*COLUMN #1 */
                   CLASS TEXT, \       /*COLUMN #2 */
                   ...         \
                   COMPLETED TEXT);";  /*COLUMN #15 */


问:
Converting fat arrow to standard notation
How do I convert this piece of code to not use the fat arrow?

```<code>propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}
</code>```

I changed the first line to

```<code>propertyOf = function (object) {
</code>```

and the code still worked. When I changed also the second line to

```<code>return propName = function () {
</code>```

I got an error saying "undefined" when I tried to call the function. I also got an error beside the second line saying 'Did you mean to run a conditional instead of an assignment?'

The full code is this:

```<code>let bob = {
  name: 'Bob',
  age: 87
},
searchBob;

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

searchBob = propertyOf(bob);

console.log(searchBob('age'));
</code>```

答:
I will do it this way:</p>

```<code>let bob = {
  name: 'Bob',
  age: 87
},
searchBob;

propertyOf = function (person,propName) {

    for (let key in person) {
       if(key === propName) return person[key]
    }

}

searchBob = propertyOf(bob, "name");
</code>```

Body:
How do I convert this piece of code to not use the fat arrow?

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

I changed the first line to

propertyOf = function (object) {

and the code still worked. When I changed also the second line to

return propName = function () {

I got an error saying "undefined" when I tried to call the function. I also got an error beside the second line saying 'Did you mean to run a conditional instead of an assignment?'

The full code is this:

let bob = {
  name: 'Bob',
  age: 87
},
searchBob;

propertyOf = object => {
  return propName => {
    for (let key in object) {
  if(key === propName) return object[key]
    }
  }
}

searchBob = propertyOf(bob);

console.log(searchBob('age'));

Body:
I will do it this way:

let bob = {
  name: 'Bob',
  age: 87
},
searchBob;

propertyOf = function (person,propName) {

    for (let key in person) {
       if(key === propName) return person[key]
    }

}

searchBob = propertyOf(bob, "name");


问:
gsoap 2.8.43 with onvif
Does the onvif have any problem with gsoap 2.8.43 version?
we have two different vendors onvif camera (one is Cohu and one is Axis) that we need to test it under Oracle Linux 7.1
If I use gsoap 2.8.17r wsdl2h with devicemgmt.wsdl and use GetSystemDateAndTime, I can get response with both camera.
But with gsoap 2.8.43 with same code I cannot compile it.
It keep complain that
main.cpp:26:98: error: no matching function for call to ‘DeviceBindingProxy::GetSystemDateAndTime(_tds__GetSystemDateAndTime*&, _tds__GetSystemDateAndTimeResponse*&)’
  result = proxy.GetSystemDateAndTime(tds__GetSystemDateAndTime, tds__GetSystemDateAndTimeResponse);

Any idea what I do wrong?

many thanks in advance

答:
Is the GetSystemDateAndTime function signature different when using wsdl2h 2.8.43? That might be the problem.

If so, then simply use the 2.8.17r version to generate the .h file and use the 2.8.43 version to generate all the rest with soapcpp2. You can use an older .h file generated with wsdl2h with a newer gSOAP version of soapcpp2 and libraries.

Title: gsoap 2.8.43 with onvif


问:
Ionic 2 Side menu not working after number of pushes
Hi,
I am facing a problem ionic 2 side menu not working when i go through number of pages some page are set as root and some page are pushes on stack.

Here is the Flow for Pages i am going through.

Navigation Stack:

```<code>RootPage -> navCtrl.push(Page1) -> navCtrl.setRoot(Page2) -> this.navCtrl.push(Page3) ->

this.navCtrl.push(Page4) -> this.navCtrl.push(Page5) -> this.navCtrl.setRoot(Page6) ->

this.navCtrl.setRoot( Page7)
</code>```

Code:

```<code><ion-menu  class="sproglets_menu"  [content]="content" persistent="true" >

  <!-- (ionOpen)="menuOpened()" (ionClose)="menuClosed()"
   -->
  <ion-content>

    <ion-item no-lines color="transparnt">
      <ion-avatar item-start>
        <img src="assets/images/addimage.png">
      </ion-avatar>
      <h2>Umer</h2>
      <p>Sproglets</p>
    </ion-item>

    <ion-list class="rr-menu" no-lines>

      <button class="search_button" ion-button block item-left round outline color="light" icon-only (click)="Place_order()">
        <ion-icon name='search'></ion-icon>
        Search Jobs
      </button>

      <button ion-item color="transparnt" (click)="Profile()"  detail-none>
        Profile
      </button>

      <button ion-item color="transparnt" (click)="Notifications()"  detail-none>
        Notifications
        <span ion-button clear item-end color="login_btn_color">28</span>
      </button>

      <button ion-item color="transparnt"   detail-none>
        Timesheets
        <span ion-button clear item-end color="login_btn_color">28</span>
      </button>

      <button ion-item color="transparnt" (click)="Payment()"  detail-none>
        Payments
        <span ion-button clear item-end color="login_btn_color">28</span>
      </button>

      <button ion-item color="transparnt" (click)="Setting()"  detail-none>
        Settings
      </button>

      <button ion-item color="transparnt" (click)="Logout()"  detail-none>
        Logout
      </button>

    </ion-list>

  </ion-content>

</ion-menu>

<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
</code>```

Ionic Info:

Cordova CLI: 6.5.0

Ionic Framework Version: 3.4.2

Ionic CLI Version: 2.2.1

Ionic App Lib Version: 2.2.0

Ionic App Scripts Version: 1.3.7

ios-deploy version: Not installed

ios-sim version: Not installed

OS: Windows 8.1

Node Version: v4.5.0

Xcode version: Not installed

Side menu works properly if i set Page7 as a root.

Please guide what i am doing wrong. Thanks!

答:
Add id for your menu:

```<code> <ion-menu id="mymenu"  class="sproglets_menu"  [content]="content" persistent="true" >
</code>```

In page2, page6, page7 (page which is set as rootpage) enable your menu

```<code> constructor(public menuCtrl: MenuController){}
 ionViewDidLoad() {
    this.menuCtrl.enable(true, "mymenu");
 }
</code>```

Body:
Hi,
I am facing a problem ionic 2 side menu not working when i go through number of pages some page are set as root and some page are pushes on stack.

Here is the Flow for Pages i am going through.

Navigation Stack:

RootPage -> navCtrl.push(Page1) -> navCtrl.setRoot(Page2) -> this.navCtrl.push(Page3) ->

this.navCtrl.push(Page4) -> this.navCtrl.push(Page5) -> this.navCtrl.setRoot(Page6) ->

this.navCtrl.setRoot( Page7)

Code:

<ion-menu  class="sproglets_menu"  [content]="content" persistent="true" >

  <ion-content>

    <ion-item no-lines color="transparnt">
      <ion-avatar item-start>

      </ion-avatar>

Umer

Sproglets

    </ion-item>

    <ion-list class="rr-menu" no-lines>

      <button class="search_button" ion-button block item-left round outline color="light" icon-only (click)="Place_order()">
        <ion-icon name='search'></ion-icon>
        Search Jobs
      </button>

      <button ion-item color="transparnt" (click)="Profile()"  detail-none>
        Profile
      </button>

      <button ion-item color="transparnt" (click)="Notifications()"  detail-none>
        Notifications
        28
      </button>

      <button ion-item color="transparnt"   detail-none>
        Timesheets
        28
      </button>

      <button ion-item color="transparnt" (click)="Payment()"  detail-none>
        Payments
        28
      </button>

      <button ion-item color="transparnt" (click)="Setting()"  detail-none>
        Settings
      </button>

      <button ion-item color="transparnt" (click)="Logout()"  detail-none>
        Logout
      </button>

    </ion-list>

  </ion-content>

</ion-menu>

<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

Ionic Info:

Cordova CLI: 6.5.0

Ionic Framework Version: 3.4.2

Ionic CLI Version: 2.2.1

Ionic App Lib Version: 2.2.0

Ionic App Scripts Version: 1.3.7

ios-deploy version: Not installed

ios-sim version: Not installed

OS: Windows 8.1

Node Version: v4.5.0

Xcode version: Not installed

Side menu works properly if i set Page7 as a root.

Please guide what i am doing wrong. Thanks!

Body:
Add id for your menu:

 <ion-menu id="mymenu"  class="sproglets_menu"  [content]="content" persistent="true" >

In page2, page6, page7 (page which is set as rootpage) enable your menu

 constructor(public menuCtrl: MenuController){}
 ionViewDidLoad() {
    this.menuCtrl.enable(true, "mymenu");
 }


问:
Postgresql plpgsql function syntax error
I want to create a function returning a set of records but I get a syntax error. The query is working but when I embed it in a function I get an error. What can be done to return the set?

Error

  ERROR:  syntax error at or near "select"

  LINE 27:  select id, user_id, project_id, record_date, parselid, pars...

   ________^

  ********** Error **********

      ERROR: syntax error at or near "select"

      SQL state: 42601

      Character: 832

Function code

```<code>CREATE OR REPLACE FUNCTION getloggeom(
    IN p_lat double precision,
    IN p_lng double precision,
    OUT id integer,
    OUT user_id bigint,
    OUT project_id bigint,
    OUT record_date timestamp without time zone,
    OUT parselid integer,
    OUT parselno character varying,
    OUT adano character varying,
    OUT ilid integer,
    OUT ilad character varying,
    OUT ilceid integer,
    OUT ilcead character varying,
    OUT mahallead character varying,
    OUT mahalleid integer,
    OUT pafta character varying,
    OUT nitelik character varying,
    OUT mevkii character varying,
    OUT yuzolcum character varying,
    OUT alan double precision,
    OUT lat double precision,
    OUT lng double precision,
    OUT feature json)
  RETURNS SETOF record AS
$BODY$
    select id, user_id, project_id, record_date, parselid, parselno, adano, ilid, ilad, ilceid, ilcead, mahallead, mahalleid, pafta, nitelik, mevkii, yuzolcum, alan, st_x(st_centroid(st_transform(geom,4326))) as lng, st_y(st_centroid(st_transform(geom,4326))) as lat, (SELECT row_to_json(fc) as data
                     FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) as features
                     FROM ( SELECT 'Feature' as type
                        , ST_AsGeoJSON(st_transform(ST_MakeValid(geom),4326))::json as geometry
                        , row_to_json(( parselid, ilad, ilcead, mahallead, adano, parselno, yuzolcum, st_y(st_centroid(st_transform(geom,4326))), st_x(st_centroid(st_transform(geom,4326))))) As properties
                       FROM log_geom where st_intersects((st_transform(st_setsrid(st_point(p_lng, p_lat), 4326), 500000)),geom ) limit 1)as f )  as fc) as feature  from log_geom where
        ST_Intersects(
        st_transform(st_setsrid(st_point(p_lng, p_lat), 4326), 500000),geom
    )limit 1;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 1000
  ROWS 1000;
</code>```

答:
If you use plpgsql, you must include the begin / end statements and you must use RETURN QUERY ...  RETURN; as per the doc.

Otherwise you can switch to using SQL instead of PLPGSQL and your function would work as is.

```<code>CREATE OR REPLACE FUNCTION getloggeom([...])
  RETURNS SETOF record AS
$BODY$
    [...]
$BODY$
  LANGUAGE SQL
  COST 1000
  ROWS 1000;
</code>```

Body:
I want to create a function returning a set of records but I get a syntax error. The query is working but when I embed it in a function I get an error. What can be done to return the set?

Error

  ERROR:  syntax error at or near "select"

  LINE 27:  select id, user_id, project_id, record_date, parselid, pars...

   ________^

  ********** Error **********

      ERROR: syntax error at or near "select"

      SQL state: 42601

      Character: 832

Function code

CREATE OR REPLACE FUNCTION getloggeom(
    IN p_lat double precision,
    IN p_lng double precision,
    OUT id integer,
    OUT user_id bigint,
    OUT project_id bigint,
    OUT record_date timestamp without time zone,
    OUT parselid integer,
    OUT parselno character varying,
    OUT adano character varying,
    OUT ilid integer,
    OUT ilad character varying,
    OUT ilceid integer,
    OUT ilcead character varying,
    OUT mahallead character varying,
    OUT mahalleid integer,
    OUT pafta character varying,
    OUT nitelik character varying,
    OUT mevkii character varying,
    OUT yuzolcum character varying,
    OUT alan double precision,
    OUT lat double precision,
    OUT lng double precision,
    OUT feature json)
  RETURNS SETOF record AS
$BODY$
    select id, user_id, project_id, record_date, parselid, parselno, adano, ilid, ilad, ilceid, ilcead, mahallead, mahalleid, pafta, nitelik, mevkii, yuzolcum, alan, st_x(st_centroid(st_transform(geom,4326))) as lng, st_y(st_centroid(st_transform(geom,4326))) as lat, (SELECT row_to_json(fc) as data
                     FROM ( SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) as features
                     FROM ( SELECT 'Feature' as type
                        , ST_AsGeoJSON(st_transform(ST_MakeValid(geom),4326))::json as geometry
                        , row_to_json(( parselid, ilad, ilcead, mahallead, adano, parselno, yuzolcum, st_y(st_centroid(st_transform(geom,4326))), st_x(st_centroid(st_transform(geom,4326))))) As properties
                       FROM log_geom where st_intersects((st_transform(st_setsrid(st_point(p_lng, p_lat), 4326), 500000)),geom ) limit 1)as f )  as fc) as feature  from log_geom where
        ST_Intersects(
        st_transform(st_setsrid(st_point(p_lng, p_lat), 4326), 500000),geom
    )limit 1;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 1000
  ROWS 1000;

Body:
If you use plpgsql, you must include the begin / end statements and you must use RETURN QUERY ...  RETURN; as per the doc.

Otherwise you can switch to using SQL instead of PLPGSQL and your function would work as is.

CREATE OR REPLACE FUNCTION getloggeom([...])
  RETURNS SETOF record AS
$BODY$
    [...]
$BODY$
  LANGUAGE SQL
  COST 1000
  ROWS 1000;


问:
Images are not showing
I'm using this template, and when I upload it to my domain just to test it, the images are not showing, as you can see it here. The website should look like the demo.
You can download the template to your self, I would have liked to make a pastebin for you guys, but I don't have 10 reputation.

So what you guys think is the problem?

答: While it is the best to correct url("../images/banner.jpg") of #banner, if you still only want the background image, put background-image: url("http://templated.co/items/demos/ion/images/banner.jpg");

Title: Images are not showing


问:
Java makefile can't find JAR resource
I have a problem with this line in a Make file:

```<code>"%JDK%\bin\Javac" -classpath .;..;..\..\..\inc\Java\com.abbyy.FREngine.jar *.java
</code>```

Error message is saying that the path couldn't be found.
I'm not familiar with make files at all. Can somebody help me with this?
What does %JDK% mean?
And what does this ".;..;......" mean? This can't be right. I tried to modify the path a few times to link directly to the jar file but unfortunately it didn't work.

答:
%JDK% points to location specified by environment variable.

Take a look here for more info: https://www.java.com/en/download/help/path.xml

This line

```<code>-classpath .;..;..\..\..\inc\Java\com.abbyy.FREngine.jar
</code>```

tells Java where to look for classes/packages. In your case these are

```<code>. - directory where you are
.. - directory one level up
..\..\..\inc\Java\com.abbyy.FREngine.jar - jar file that is few levels up
</code>```

and you compile all java files using *.java

What you need to do, is to make sure that %JDK% points to your JDK installation and you have to make sure that you have provided proper location of jar file.

Title: Java makefile can't find JAR resource

Body:
I have a problem with this line in a Make file:

"%JDK%\bin\Javac" -classpath .;..;..\..\..\inc\Java\com.abbyy.FREngine.jar *.java

Error message is saying that the path couldn't be found.
I'm not familiar with make files at all. Can somebody help me with this?
What does %JDK% mean?
And what does this ".;..;......" mean? This can't be right. I tried to modify the path a few times to link directly to the jar file but unfortunately it didn't work.

Body:
%JDK% points to location specified by environment variable.

Take a look here for more info: https://www.java.com/en/download/help/path.xml

This line

-classpath .;..;..\..\..\inc\Java\com.abbyy.FREngine.jar

tells Java where to look for classes/packages. In your case these are

. - directory where you are
.. - directory one level up
..\..\..\inc\Java\com.abbyy.FREngine.jar - jar file that is few levels up

and you compile all java files using *.java

What you need to do, is to make sure that %JDK% points to your JDK installation and you have to make sure that you have provided proper location of jar file.


问:
algorithm to evenly space objects across containers
I have a line of 12 cups and I will receive a random number of balls to be placed in those cups. I could receive between 1 and 12 balls (inclusive). No matter the number of balls I receive, I want to evenly space them across the line of cups. Each cup may only contain one ball.

The concept of "even" is up for debate. For instance, if I get 6 balls, I can space them every-other cup, but if I get 7 balls, the location of that 7th ball isn't terribly important to me, as long as it follows a logical pattern. Similarly, the location of the extra space between balls when I only have 5 balls is not important to me either.

So, is anyone familiar with an distribution algorithm of this sort? I've cobbled something together, but it's so bad that it will never see the light of day.

答:
Sorry i can not tell you this in English. But i can help with code and math.

```<code>F(x,b)  ->  {0,1}
x € [0,11] , b  € [1,12]
</code>```

F (x,b) is : this is blue box or white box function.
x are boxes;
b are balls.

```<code>int F(x,b){
   if (    (int)(x % 12/b)   == 0 ) return 1;
   else return 0;
}
</code>```

**Second Way*

```<code>float i = 0;
int b = 1; // Balls
while(i<12){
   printf( '%d. box', (int) i);
   i +=  (float)12 /(float)b ;
}
</code>```

You can see this algorithm in https://jsfiddle.net/k0r18yba/

Body:
Sorry i can not tell you this in English. But i can help with code and math.

F(x,b)  ->  {0,1}
x € [0,11] , b  € [1,12]

F (x,b) is : this is blue box or white box function.
x are boxes;
b are balls.

int F(x,b){
   if (    (int)(x % 12/b)   == 0 ) return 1;
   else return 0;
}

**Second Way*

float i = 0;
int b = 1; // Balls
while(i<12){
   printf( '%d. box', (int) i);
   i +=  (float)12 /(float)b ;
}

You can see this algorithm in https://jsfiddle.net/k0r18yba/


问:
Error when saving to a mapped drive in Sublime only: cannot save a file with a user-mapped section open
When I try to save a file in sublime from a mapped network drive I get an error:

Unable to save Y:\MySite\index.html

  Error: The requested operation cannot be performed on a file with a user-mapped section

This error does not happen in Notepad, and is coming from Sublime Text rather than windows, which makes me think Sublime is trying to do something funky during the save process.

What I've tried:

The file is open somewhere else. No, I can save the file in Notepad.

There may be an issue with user permissions Maybe, however I'm not sure how to fix it.

The linked post is not specific. I shared the folder by

Right-Click > Properties > Sharing > Share, added "Everyone", and gave them "Read/Write" permission.

Could it be that "Everyone" doesn't cover the Sublime user? (Note: I have tried to run sublime as admin, to no avail)

More Details:

Environment:

My local computer ("The Host") hosts a Windows 7 Virtual Machine ("The Guest"), which is running Jetty

Jetty serves folders from webapps as web servers

I set up webapps to be shared with Everyone

On the host I mapped webapps so I can edit files locally.

Here's a pic of my Network Folder setup:

The Issue:

When I locally edit a webapps file in Sublime, and Jetty is running in the guest, I get this error when I try to save it:

However, if I edit the same file in Notepad it works fine.

This seems like a Sublime error rather than a windows error, meaning it's perhaps trying to do something funky with the file rather than saving it. Has anyone else experienced this?

答:
Thanks to Joakim Erdfelt's answer to my other question I got this figured out!

This is an issue with windows' memory buffering, but you can fix it in a Jetty config file. See the docs for more info. Here's what I did:

Find your webdefault.xml file.

Mine was in C:\Place_where_Jetty_was_installed\Jetty\etc\

Open it and search for UseFileMappedBuffer. Look for this:

```<code><init-param>
  <param-name>useFileMappedBuffer</param-name>
  <param-value>true</param-value>
</init-param>
</code>```

Set param-value to false

```<code><param-value>false</param-value>
</code>```

Body:
Thanks to Joakim Erdfelt's answer to my other question I got this figured out!

This is an issue with windows' memory buffering, but you can fix it in a Jetty config file. See the docs for more info. Here's what I did:

Find your webdefault.xml file.

Mine was in C:\Place_where_Jetty_was_installed\Jetty\etc\

Open it and search for UseFileMappedBuffer. Look for this:

<init-param>
  <param-name>useFileMappedBuffer</param-name>
  <param-value>true</param-value>
</init-param>

Set param-value to false

<param-value>false</param-value>


问:
Complex branching and merging in history TFS
It is possible to create a branch from a historic changeset. The situation that I have now is that I have created a branch of a repository from a (for example) 3 months ago. After that I have created the branch, I want to  and I want to merge only specific changesets from 1 month ago, and want to keep the rest of the branch the same.

When I try to tell visual studio (source control explorer) that I want to merge specific changesets to that new branch, the changeset of the previous months are not shown. Is there any other way than manual work to merge the changes of the specific changeset on the historic branch that I have created?

答:
It is possible to create a branch from a historic changeset?

When a branch is created you could choose the historical point in time when it takes effect (date, changeset, etc).

For more detail steps please refer this tutorial in MSDN: Branch a branch

When I try to tell visual studio (source control explorer) that I want
  to merge specific changesets to that new branch, the changeset of the
  previous months are not shown.

Not sure why the changeset are not shown, make sure you have select the right option when you do the merge. Another way is directly using tf merge command to do the merge. For example:

```<code>tf merge /version:C137~C1xx  oldbranch newbranch /recursive
</code>```

Note: you could only merge a single changeset or continuous changesets

Body:
It is possible to create a branch from a historic changeset?

When a branch is created you could choose the historical point in time when it takes effect (date, changeset, etc).

For more detail steps please refer this tutorial in MSDN: Branch a branch

When I try to tell visual studio (source control explorer) that I want
  to merge specific changesets to that new branch, the changeset of the
  previous months are not shown.

Not sure why the changeset are not shown, make sure you have select the right option when you do the merge. Another way is directly using tf merge command to do the merge. For example:

tf merge /version:C137~C1xx  oldbranch newbranch /recursive

Note: you could only merge a single changeset or continuous changesets


问:
How to include density coloring in pairwise correlation scatter plot
I have the following code:

```<code>library(GGally)
library(nycflights13)
library(tidyverse)

dat <- nycflights13::flights %>%
       select(dep_time, sched_dep_time, dep_delay,  arr_time, sched_arr_time, arr_delay)  %>%
       sample_frac(0.01)
dat
ggpairs(dat)
</code>```

It produces this:

How can I add the density coloring so that it looks like this:

答:
Using ideas from How to reproduce smoothScatter's outlier plotting in ggplot? , R - Smoothing color and adding a legend to a scatterplot, and How to use loess method in GGally::ggpairs using wrap function you can define your own function to pass to ggpairs.

```<code>my_fn <- function(data, mapping, ...){
      p <- ggplot(data = data, mapping = mapping) +
        stat_density2d(aes(fill=..density..), geom="tile", contour = FALSE) +
        scale_fill_gradientn(colours=rainbow(100))
      p
}

ggpairs(dat, lower=list(continuous=my_fn))
</code>```

EDIT

From comment: How do you add histogram in the diagonal and remove "Corr:" in the correlation value?

You can set the diagonal and upper arguments. So to add the histogram (assuming you mean geom_histogram) you can use diag=list(continuous=wrap("barDiag", binwidth=100)) and to remove the correlation completely use upper=list(continuous="blank"). If you want to  actually remove the text *corr:*, you will need to define a new function - please see the function cor_fun at Change colors in ggpairs now that params is deprecated .

So your plot becomes

```<code>ggpairs(dat, lower=list(continuous=my_fn),
        diag=list(continuous=wrap("barDiag", binwidth=100)),
        upper=list(continuous=wrap(cor_fun, sz=10, stars=FALSE))
        )
</code>```

EDIT

From comment: How do you color the diagonal histogram like in OP?

To colour just add the relevant arguments to the barDiag function, in this case fill and colour. So diag would then be

```<code>diag=list(continuous=wrap("barDiag", binwidth=100, fill="brown", col="black"))
</code>```

(fill gives the main colour, and col gives the colour to outline the bars)

Body:
I have the following code:

library(GGally)
library(nycflights13)
library(tidyverse)

dat <- nycflights13::flights %>%
       select(dep_time, sched_dep_time, dep_delay,  arr_time, sched_arr_time, arr_delay)  %>%
       sample_frac(0.01)
dat
ggpairs(dat)

It produces this:

How can I add the density coloring so that it looks like this:

Body:
Using ideas from How to reproduce smoothScatter's outlier plotting in ggplot? , R - Smoothing color and adding a legend to a scatterplot, and How to use loess method in GGally::ggpairs using wrap function you can define your own function to pass to ggpairs.

my_fn <- function(data, mapping, ...){
      p <- ggplot(data = data, mapping = mapping) +
        stat_density2d(aes(fill=..density..), geom="tile", contour = FALSE) +
        scale_fill_gradientn(colours=rainbow(100))
      p
}

ggpairs(dat, lower=list(continuous=my_fn))

EDIT

From comment: How do you add histogram in the diagonal and remove "Corr:" in the correlation value?

You can set the diagonal and upper arguments. So to add the histogram (assuming you mean geom_histogram) you can use diag=list(continuous=wrap("barDiag", binwidth=100)) and to remove the correlation completely use upper=list(continuous="blank"). If you want to  actually remove the text *corr:*, you will need to define a new function - please see the function cor_fun at Change colors in ggpairs now that params is deprecated .

So your plot becomes

ggpairs(dat, lower=list(continuous=my_fn),
        diag=list(continuous=wrap("barDiag", binwidth=100)),
        upper=list(continuous=wrap(cor_fun, sz=10, stars=FALSE))
        )

EDIT

From comment: How do you color the diagonal histogram like in OP?

To colour just add the relevant arguments to the barDiag function, in this case fill and colour. So diag would then be

diag=list(continuous=wrap("barDiag", binwidth=100, fill="brown", col="black"))

(fill gives the main colour, and col gives the colour to outline the bars)


问:
Compile roscpp without ros (using g++)
I'm trying to compile roscpp without using the rest of ROS (I only need to subscribe to a node but the one that own that uses an old version of ROS and I couldn't integrate my program with his due to compilation troubles). I downloaded the source code from git (https://github.com/ros/ros_comm) and now I need to compile it, but Cmake throw me errors:

```<code> INFOBuilding GTest from source.
 TODO: implement add_roslaunch_check() in rostest-extras.cmake.
 CMake Error at CMakeLists.txt:8 (catkin_package_xml):
     Unknown CMake command "catkin_package_xml".
</code>```

How can I build it? I'm calling cmake CMakeList.txt, but it doesn't work.

答:
Use this command line to compile your code directly with g++:

```<code>g++ yourtest.cpp -o yourtest -I/opt/ros/indigo/include -L/opt/ros/indigo/lib \
-Wl,-rpath,/opt/ros/indigo/lib -lroscpp -lrosconsole -lrostime \
-lroscpp_serialization -lboost_system -lboost_thread -pthread -lactionlib
</code>```

Where yourtest.cpp is your c++ file that has some ros code.

If you are using a ros version different of the indigo replace de indigo string by the string of your version.

Title: Compile roscpp without ros (using g++)

Body:
I'm trying to compile roscpp without using the rest of ROS (I only need to subscribe to a node but the one that own that uses an old version of ROS and I couldn't integrate my program with his due to compilation troubles). I downloaded the source code from git (https://github.com/ros/ros_comm) and now I need to compile it, but Cmake throw me errors:

 INFOBuilding GTest from source.
 TODO: implement add_roslaunch_check() in rostest-extras.cmake.
 CMake Error at CMakeLists.txt:8 (catkin_package_xml):
     Unknown CMake command "catkin_package_xml".

How can I build it? I'm calling cmake CMakeList.txt, but it doesn't work.

Body:
Use this command line to compile your code directly with g++:

g++ yourtest.cpp -o yourtest -I/opt/ros/indigo/include -L/opt/ros/indigo/lib \
-Wl,-rpath,/opt/ros/indigo/lib -lroscpp -lrosconsole -lrostime \
-lroscpp_serialization -lboost_system -lboost_thread -pthread -lactionlib

Where yourtest.cpp is your c++ file that has some ros code.

If you are using a ros version different of the indigo replace de indigo string by the string of your version.


问:
read and write i2c in other existing driver in Linux
I want to modify a existing device driver to make it capable to read and write via i2c. Is it possible and how can I achive that?

Lots of posts are about how to write a standalone i2c driver (with init / probe). I guess there should be a simple way to read and write just like gpio does (with gpio_request)..

答: I answer my question myself. Finally, I add all I2C driver code in the existing driver. The first time I know that any Linux driver module can contain more than one drivers in it (each with probe). Data is shared with module-scope global variables. (Is there any better approaches?)</p>


答:
Two things:

You need a @ character before the string begins. NSString literals @"look like this".

Your string is split over multiple lines, which is confusing the compiler (this is the error you're seeing). You need to have it be entirely on one line. If you want to split it like this, wrap each line in quotes, like this:

_

```<code>NSString * foo = @"foo "
                  "bar "
                  "baz";
</code>```

Or do as Barry says here and use a trailing backslash at the end of each line to indicate continuation.

Title: Compound/Complex C-String in Xcode/Cocoa

Body:
I am creating an SQLite3 program.  I am creating the database within the code.  I have about 15 columns. Example below:

NSString *createSQL = "CREATE TABLE IF NOT EXISTS FIELDS (DATE TEXT PRIMARY KEY,
                   NAME TEXT,           /*COLUMN #1 */
                   CLASS TEXT,          /*COLUMN #2 */
                   ...
                   COMPLETED TEXT);";  /*COLUMN #15 */

When I compile I am getting "missing terminating character error.  I did some research and saw that because it is a C-String it will process the CR\LF as a continuation character. I don't want to create a line of codes that scrolls the right most margin of the screen every time I need to do something with SQL.   Is there a way that I can create a string that can be broken up on separate lines without getting this error?

Body:
Two things:

You need a @ character before the string begins. NSString literals @"look like this".

Your string is split over multiple lines, which is confusing the compiler (this is the error you're seeing). You need to have it be entirely on one line. If you want to split it like this, wrap each line in quotes, like this:

_

NSString * foo = @"foo "
                  "bar "
                  "baz";

Or do as Barry says here and use a trailing backslash at the end of each line to indicate continuation.


问:
I want to set a variable 's value from another php file
So i have dashboard.php

```<code>$value1;
$value1 = 1;
</code>```

and file.php

```<code>$value;
echo value;
</code>```

So i want to print "1" on the file file.php. How can i tell file.php to get the variable 's value from dashboard.php

答:
Here are some ways to send a data to another page:

Using $_GET:

dashboard.php

```<code><?php
    $value = 1;
?>
<a href="file.php?value=<?php echo $value; ?>">Go to file.php</a>
</code>```

file.php

```<code><?php
    if(isset($_GET['value'])){
        $value = $_GET['value'];
        echo $value;
    }
?>
</code>```

Using $_POST:

dashboard.php

```<code><?php
    $value = 1;
?>
<form action="file.php" method="POST">
    <input type="text" name="value" value="<?php echo $value; ?>" hidden />
    <input type="submit" name="submit" value="submit" />
</form>
</code>```

file.php

```<code><?php
    if(isset($_POST['submit'])){
        $value = $_POST['value'];
        echo $value;
    }
?>
</code>```

Using $_SESSION:

dashboard.php

```<code><?php
    session_start();
    $_SESSION['value'] = 1;
?>
</code>```

file.php

```<code><?php
    session_start();
    echo $_SESSION['value'];
?>
</code>```

Body:
So i have dashboard.php

$value1;
$value1 = 1;

and file.php

$value;
echo value;

So i want to print "1" on the file file.php. How can i tell file.php to get the variable 's value from dashboard.php

Body:
Here are some ways to send a data to another page:

Using $_GET:

dashboard.php

<?php
    $value = 1;
?>
<a href="file.php?value=<?php echo $value; ?>">Go to file.php</a>

file.php

<?php
    if(isset($_GET['value'])){
        $value = $_GET['value'];
        echo $value;
    }
?>

Using $_POST:

dashboard.php

<?php
    $value = 1;
?>
<form action="file.php" method="POST">
    <input type="text" name="value" value="<?php echo $value; ?>" hidden />
    <input type="submit" name="submit" value="submit" />
</form>

file.php

<?php
    if(isset($_POST['submit'])){
        $value = $_POST['value'];
        echo $value;
    }
?>

Using $_SESSION:

dashboard.php

<?php
    session_start();
    $_SESSION['value'] = 1;
?>

file.php

<?php
    session_start();
    echo $_SESSION['value'];
?>


问:
CSS selector: applying :focus on navbar
Following with ADA-compliant, I need to make the navbar expand either when the user's mouse is over at the navbar (using :hover) or if the user's mouse is focused on one of the items in the navbar.

Although I was able to figure it the first part, I am having trouble implementing the second requirement.

Here's a code snippet to demonstrate my current implementation:

https://codepen.io/neotriz/pen/MoBMvz?editors=1100

CSS:

```<code>.nav-template {
    height: 100%;
    position: absolute;
    transition: width 0.3s linear;
    display: flex;
    overflow: hidden;
    background: black;
    width: 70px;
    &:hover{
        width: 150px;
    }

    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;

        li {
            margin: 0;
            padding: 0;
            cursor: pointer;
            &:hover {
                background-color: rgba(255, 255, 255, 0.12);
            }
            a {
                color: white;
                height: 40px;
                margin-left: 12px;
                margin-right: 35px;
                padding-bottom: 10px;
                display: flex;
                align-items: center;
                text-decoration: none;
            }
        }
    }
}
</code>```

It looks like if I apply &:focus where &:hover is, it doesn't work because it is thinking the entire navbar needs to be selected in order to expand it, as suppose to focusing on each individual items.

Is my current implementation needs some reworking?

答:
Try Some thing Like this

HTML

```<code><div tabindex="1" class="nav-template">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</div>
</code>```

LESS

```<code>.nav-template {
    height: 100%;
    position: absolute;
    display: flex;
    overflow: hidden;
    background: black;
    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
    transition: width 0.3s linear;
        li {
            margin: 0;
            padding: 0;
            cursor: pointer;
            a {
                color: white;
                height: 40px;
                margin-left: 12px;
                margin-right: 35px;
                padding-bottom: 10px;
                display: flex;
                align-items: center;
                text-decoration: none;
                width:70px;
                transition:all ease 0.5s;
        &:focus,&:hover {
                width: 100px;
        background-color: rgba(255, 255, 255, 0.12);
            }
            }
        }
    }
}
</code>```

CSS

```<code>.nav-template {
  height: 100%;
  position: absolute;
  display: flex;
  overflow: hidden;
  background: black;
}
.nav-template ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  transition: width 0.3s linear;
}
.nav-template ul li {
  margin: 0;
  padding: 0;
  cursor: pointer;
}
.nav-template ul li a {
  color: white;
  height: 40px;
  margin-left: 12px;
  margin-right: 35px;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  text-decoration: none;
  width:70px;
  transition:all ease 0.5s;
}
.nav-template ul li a:focus,
.nav-template ul li a:hover {
  width: 100px;
  background-color: rgba(255, 255, 255, 0.12);
}
</code>```

use :focus on the anchor tag increase its width, :focus works on div but the problem here is when you are focusing it is directly focused on the anchor tag but not on the div or the li or ul

add these rules for transition

```<code>.nav-template ul li a{
width:70px;
transition:all ease 0.5s;
}
</code>```

Link For reference

give this a try

hope this helps...

Title: CSS selector: applying :focus on navbar

Body:
Following with ADA-compliant, I need to make the navbar expand either when the user's mouse is over at the navbar (using :hover) or if the user's mouse is focused on one of the items in the navbar.

Although I was able to figure it the first part, I am having trouble implementing the second requirement.

Here's a code snippet to demonstrate my current implementation:

https://codepen.io/neotriz/pen/MoBMvz?editors=1100

CSS:

.nav-template {
    height: 100%;
    position: absolute;
    transition: width 0.3s linear;
    display: flex;
    overflow: hidden;
    background: black;
    width: 70px;
    &:hover{
        width: 150px;
    }

    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;

        li {
            margin: 0;
            padding: 0;
            cursor: pointer;
            &:hover {
                background-color: rgba(255, 255, 255, 0.12);
            }
            a {
                color: white;
                height: 40px;
                margin-left: 12px;
                margin-right: 35px;
                padding-bottom: 10px;
                display: flex;
                align-items: center;
                text-decoration: none;
            }
        }
    }
}

It looks like if I apply &:focus where &:hover is, it doesn't work because it is thinking the entire navbar needs to be selected in order to expand it, as suppose to focusing on each individual items.

Is my current implementation needs some reworking?

Body:
Try Some thing Like this

HTML

<div tabindex="1" class="nav-template">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</div>

LESS

.nav-template {
    height: 100%;
    position: absolute;
    display: flex;
    overflow: hidden;
    background: black;
    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
    transition: width 0.3s linear;
        li {
            margin: 0;
            padding: 0;
            cursor: pointer;
            a {
                color: white;
                height: 40px;
                margin-left: 12px;
                margin-right: 35px;
                padding-bottom: 10px;
                display: flex;
                align-items: center;
                text-decoration: none;
                width:70px;
                transition:all ease 0.5s;
        &:focus,&:hover {
                width: 100px;
        background-color: rgba(255, 255, 255, 0.12);
            }
            }
        }
    }
}

CSS

.nav-template {
  height: 100%;
  position: absolute;
  display: flex;
  overflow: hidden;
  background: black;
}
.nav-template ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  transition: width 0.3s linear;
}
.nav-template ul li {
  margin: 0;
  padding: 0;
  cursor: pointer;
}
.nav-template ul li a {
  color: white;
  height: 40px;
  margin-left: 12px;
  margin-right: 35px;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
  text-decoration: none;
  width:70px;
  transition:all ease 0.5s;
}
.nav-template ul li a:focus,
.nav-template ul li a:hover {
  width: 100px;
  background-color: rgba(255, 255, 255, 0.12);
}

use :focus on the anchor tag increase its width, :focus works on div but the problem here is when you are focusing it is directly focused on the anchor tag but not on the div or the li or ul

add these rules for transition

.nav-template ul li a{
width:70px;
transition:all ease 0.5s;
}

Link For reference

give this a try

hope this helps...


问:
Alternative library/template class for the deprecated auto_ptr in C++17
Have shared project library that has to be compiled with various compilers C++17 C++03 etc.  So just using the better unique_ptr or the less than perfect auto_ptr as appropriate is not ideal if the code is to be kept common.

Have look at the #ifdef type solution but it gets messy.
Plus making edits to well tried and tested coded is not a particular attractive idea!

Anyone know of a form, fit and function drop in replacement for auto_ptr?

答:
There are Boost.Move and Boost Smart Pointer. std::unique_ptr and std::auto_ptr may be replaced by boost::movelib::unique_ptr. std::shared_ptr and std::weak_ptr by boost::shared_ptr and boost::weak_ptr.

And, you can be more expressive with boost::scoped_ptr when there is no intent to transfer ownership.


问:
Excel, VBA, convert number to text with numberformat="@" working or not?
The basic rule to tell text from number is that text is left-aligned and number is right-aligned.

In a blank cell, I set the format to text. Then, I entered 25. This "number" was left-aligned, implying it was text. There was a green triangle on the upper-left corner of the cell with a note saying

"The number in the cell is formatted as text...".

So far so good.

In the cell right below, I entered 25. It was right-aligned, implying it was number. I then ran the code Range.NumberFormat="@" on it. It became left-aligned. However, there was no green triangle.

When I used =IF(A1="25",1,0) to check the first cell, the formula returned 1. Same test (difference address, of course) on the next cell returned 0.

It seems to me the code converted 25 to text (judging from the alignment) and at the same time not converted 25 to text (judging from the lack of a green triangle and the IF test.)

What's going on?

答:
This may not be the most efficient method, but it works:</p>

```<code>Option Explicit
Sub convertText()
    Dim testValue As Variant
    testValue = ActiveCell.Value & ""
    ActiveCell.ClearContents
    ActiveCell.NumberFormat = "@"
    ActiveCell.Value = testValue
End Sub
</code>```

Body:
This may not be the most efficient method, but it works:

Option Explicit
Sub convertText()
    Dim testValue As Variant
    testValue = ActiveCell.Value & ""
    ActiveCell.ClearContents
    ActiveCell.NumberFormat = "@"
    ActiveCell.Value = testValue
End Sub


问:
Passing Numpy arrays to C code wrapped with Cython
I have a small bit of existing C code that I want to wrap using Cython. I want to be able to set up a number of numpy arrays, and then pass those arrays as arguments to the C code whose functions take standard c arrays (1d and 2d). I'm a little stuck in terms of figuring out how to write the proper .pyx code to properly handle things.

There are a handful of functions, but a typical function in the file funcs.h looks something like:

```<code>double InnerProduct(double *A, double **coords1, double **coords2, const int len)
</code>```

I then have a .pyx file that has a corresponding line:

```<code>cdef extern from "funcs.h":
    double InnerProduct(double *A, double **coords1, double **coords2, int len)
</code>```

where I got rid of the const because cython doesn't support it. Where I'm stuck is what the wrapper code should then look like to pass a MxN numpy array to the **coords1 and **coords2 arguments.

I've struggled to find the correct documentation or tutorials for this type of problem. Any suggestions would be most appreciated.

答:
The cython interface code should be created according to the tutorial given here.

To get a C pointer to the data in a numpy array, you should use the ctypes attribute of the numpy array, which is described here.

Body:
I have a small bit of existing C code that I want to wrap using Cython. I want to be able to set up a number of numpy arrays, and then pass those arrays as arguments to the C code whose functions take standard c arrays (1d and 2d). I'm a little stuck in terms of figuring out how to write the proper .pyx code to properly handle things.

There are a handful of functions, but a typical function in the file funcs.h looks something like:

double InnerProduct(double *A, double **coords1, double **coords2, const int len)

I then have a .pyx file that has a corresponding line:

cdef extern from "funcs.h":
    double InnerProduct(double *A, double **coords1, double **coords2, int len)

where I got rid of the const because cython doesn't support it. Where I'm stuck is what the wrapper code should then look like to pass a MxN numpy array to the **coords1 and **coords2 arguments.

I've struggled to find the correct documentation or tutorials for this type of problem. Any suggestions would be most appreciated.


问:
How to change "namedtuples" into classes in Python?
Can anyone give an example?

What's the difference between using variables in classes and in namedtuples?

答:
I think OP wants to be explit about the class definition for a data structure which is currently a namedtuple.  namedtuple([...], verbose=True) is likely what you're looking for:

```<code>>>> from collections import namedtuple
>>> Pooper = namedtuple('Pooper', ('poop_length','poop_width'))
>>> Pooper(7.5, 1.5)
Pooper(poop_length=7.5, poop_width=1.5)
>>> Pooper = namedtuple('Pooper', ('poop_length','poop_width'), verbose=True)
class Pooper(tuple):
    'Pooper(poop_length, poop_width)'
    __slots__ = ()
    _fields = ('poop_length', 'poop_width')

    def __new__(_cls, poop_length, poop_width):
        'Create new instance of Pooper(poop_length, poop_width)'
        return _tuple.__new__(_cls, (poop_length, poop_width))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Pooper object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'Pooper(poop_length=%r, poop_width=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _replace(_self, **kwds):
        'Return a new Pooper object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('poop_length', 'poop_width'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    __dict__ = _property(_asdict)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        pass

    poop_length = _property(_itemgetter(0), doc='Alias for field number 0')

    poop_width = _property(_itemgetter(1), doc='Alias for field number 1')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I think OP wants to be explit about the class definition for a data structure which is currently a namedtuple.  namedtuple([...], verbose=True) is likely what you're looking for:

>>> from collections import namedtuple
>>> Pooper = namedtuple('Pooper', ('poop_length','poop_width'))
>>> Pooper(7.5, 1.5)
Pooper(poop_length=7.5, poop_width=1.5)
>>> Pooper = namedtuple('Pooper', ('poop_length','poop_width'), verbose=True)
class Pooper(tuple):
    'Pooper(poop_length, poop_width)'
    __slots__ = ()
    _fields = ('poop_length', 'poop_width')

    def __new__(_cls, poop_length, poop_width):
        'Create new instance of Pooper(poop_length, poop_width)'
        return _tuple.__new__(_cls, (poop_length, poop_width))

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Pooper object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'Pooper(poop_length=%r, poop_width=%r)' % self

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self))

    def _replace(_self, **kwds):
        'Return a new Pooper object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('poop_length', 'poop_width'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)

    __dict__ = _property(_asdict)

    def __getstate__(self):
        'Exclude the OrderedDict from pickling'
        pass

    poop_length = _property(_itemgetter(0), doc='Alias for field number 0')

    poop_width = _property(_itemgetter(1), doc='Alias for field number 1')


问:
Why is it an optimization to use str.chatAt(0) instead of str[0]?
In all the browsers I have tried so far (Firefox, Chrome, Edge), it has been significantly faster to do the following:

```<code>str.charAt(0)
</code>```

Than these other two methods I've found to accomplish the same thing:

```<code>str[0]
str.substring(0, 1)
</code>```

Although I can understand .substring() being significantly slower (10% of speed), isn't [] (75% of speed) with a string just a different syntax for .charAt()?

答:
Using an index and treating the string as an array used to be the prefered approach. charAt was only introduced in ES5 and before IE9 you had to use string[index]. The charAt method is the recommended and cleaner approach to use, unless you need to support older browsers.

Presumably, it's speed comes from its predictability and the browser can optimise it a lot better than it can using an index lookup. But as you'll see in benchmarks, browsers all optimise things differently.

You will see widely different numbers in different browsers. In Chrome charAt is faster, but in Microsoft Edge and Internet Explorer it's considerably slower and [index] wins out (especially in IE11). Check out this JSPerf test and run it in different browsers.

Unless you're dealing with hundreds of millions of strings, you're not going to notice any slowdown using either-all. In Chrome the difference in speed is a fraction of a percentage especially.

Body:
In all the browsers I have tried so far (Firefox, Chrome, Edge), it has been significantly faster to do the following:

str.charAt(0)

Than these other two methods I've found to accomplish the same thing:

str[0]
str.substring(0, 1)

Although I can understand .substring() being significantly slower (10% of speed), isn't [] (75% of speed) with a string just a different syntax for .charAt()?


问:
scope variable - Error while assigning value to variable
How to access a variable from within callback of a function. I'll show the example to be more direct in the question

```<code>export class FormComponent {

  public pedidoSoft:PedidoSoft = new PedidoSoft();

  getBrandCard(){

       PagSeguroDirectPayment.getBrand({

            cardBin: this.pedidoSoft.numCard,
            success: function(response) {

                    this.pedidoSoft.bandCard = response.brand.name;

            },
            error: function(response) { },
            complete: function(response) { }
       });

   }
</code>```

I'm getting the following error. This error is when this.pedidoSoft.bandCard receives the value of response.brand.name

答:
Don't use function in TypeScript. Replace those with ()=>{} statements instead.

```<code>        success: (response) => {
                this.pedidoSoft.bandCard = response.brand.name;
        },
        error: (response) => { },
        complete: (response) => { }
</code>```

When you use function() {} the this is not persistent where as ()=>{} keeps the this reference.

Your alternative is to use bind(this) on the functions.

Body:
How to access a variable from within callback of a function. I'll show the example to be more direct in the question

export class FormComponent {

  public pedidoSoft:PedidoSoft = new PedidoSoft();

  getBrandCard(){

       PagSeguroDirectPayment.getBrand({

            cardBin: this.pedidoSoft.numCard,
            success: function(response) {

                    this.pedidoSoft.bandCard = response.brand.name;

            },
            error: function(response) { },
            complete: function(response) { }
       });

   }

I'm getting the following error. This error is when this.pedidoSoft.bandCard receives the value of response.brand.name

Body:
Don't use function in TypeScript. Replace those with ()=>{} statements instead.

        success: (response) => {
                this.pedidoSoft.bandCard = response.brand.name;
        },
        error: (response) => { },
        complete: (response) => { }

When you use function() {} the this is not persistent where as ()=>{} keeps the this reference.

Your alternative is to use bind(this) on the functions.


问:
Using audio_play_sound() in a if statement GameMaker
I am trying to use the command:

```<code>audio_play_sound()
</code>```

I am trying to insert it into this piece of code, so that when the player jumps, a sound plays.

```<code>if (key_jump) && (jumps > 0)
{
     jumps -=1;
     vsp = -jumpspeed;
}
</code>```

Code that causes problem:

```<code>if (key_jump) && (jumps > 0)
{
     jumps -=1;
     vsp = -jumpspeed;
     audio_play_sound(snd_jump)
}
</code>```

Simply inserting the line into the if statement does not work, and gives the error WRONG NUMBER OF ARGUMENTS IN FUNCTION. This is rather confusing, perhaps I am using the wrong command? Thanks in advance

答: As the person above states your answer is audio_play_sound(snd_jump, 1, false).

Body:
I am trying to use the command:

audio_play_sound()

I am trying to insert it into this piece of code, so that when the player jumps, a sound plays.

if (key_jump) && (jumps > 0)
{
     jumps -=1;
     vsp = -jumpspeed;
}

Code that causes problem:

if (key_jump) && (jumps > 0)
{
     jumps -=1;
     vsp = -jumpspeed;
     audio_play_sound(snd_jump)
}

Simply inserting the line into the if statement does not work, and gives the error WRONG NUMBER OF ARGUMENTS IN FUNCTION. This is rather confusing, perhaps I am using the wrong command? Thanks in advance


问:
How to test what is using page loading resources
I use Google Web Development Tools and Firebug whilst developing WordPress themes to make sure there are no errors in the page and to check on the resources that the pages are using.

Recently using my own XAMPP, I have noticed that when I click a link in my WordPress Dashboard it takes a few seconds before the next page will load.

If there any way using Chrome Toils and Firebug that I can test the page loading progress to see where the page is "hanging" when loading.

Thanks.

答:
Give this tool a shot.

tools.pingdom.com

I find it very useful.


问:
Independent child object with references from multiples parents in EF
I'm having quite the issue right now while trying to learn Entity Framework.
Let's say I have this entity:

public class BuildingGroup {
    public int ID { get; set; }
    public string NameOfManager { get; set; }

    public virtual ICollection<Building> Buildings { get; set; }
}
```

<p>And also this entity.</p>

<pre class="lang-cs prettyprint-override"><code>public class Architect {
    public int ID { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Building> BuildingsBeingWorkedOn { get; set; }
}
</code>```

These two entities are completely unrelated. Here's the Building entity:

public class Building {
    public int ID { get; set; }
    public string Address { get; set; }
}
```

<p>My problem happens when I try to add a building to, say a BuildingGroup. In my domain model, I can modify the equivalent collection of buildings, by adding, modifying or removing buildings. However, when I try to update <code>BuildingGroup</code> through a repository, the buildings will not be updated. </p>

<pre class="lang-cs prettyprint-override"><code>public void Update(BuildingGroup buildingGroup) {
    var buildingGroupEntity = _context.BuildingGroups.Single(b => b.ID == buildingGroup.ID);

    // This will not map the Building collection
    context.Entry(buildingGroupEntity).CurrentValues.SetValues(buildingGroup);

    // My attempt at mapping the buildings
    buildingGroupEntity.Buildings.Clear();
    buildingGroup.Buildings.ToList().ForEach(b => buildingGroupEntity.Buildings.Add(_context.Buildings.Single(x => x.ID == b.ID)));

    _context.Entry(buildingGroupEntity).State = EntityState.Modified;
}
</code>```

This fails if the building were not saved in the database prior to the call to Update(), which is normal since buildings can live independently. It must also be done for every child collection of BuildingGroup (if there were more), and for child collections of these children, well...

I have noticed other people use a foreign key constraint in the child object (here, Building), but I can't really do that since many unrelated entities can point to a building: I'd have a lot of navigation properties.

Is there a graceful way to manage referencing objects that can also live independently from those who hold references to them?

答:
If all the entities have to exist independently, yet have relationships with each other, it's better to use many-to-many relationship.

Change your model classes as follows, the Building should contain a couple of collections for architects and groups.

```<code>public class BuildingGroup
{
    public int ID { get; set; }
    public string NameOfManager { get; set; }

    public virtual ICollection<Building> Buildings { get; set; }
}

public class Architect
{
    public int ID { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Building> BuildingsBeingWorkedOn { get; set; }
}

public class Building
{
    public int ID { get; set; }
    public string Address { get; set; }

    public virtual ICollection<Architect> Architects { get; set; }
    public virtual ICollection<BuildingGroup> BuildingGroups { get; set; }
}
</code>```

If you use entity type configuration, you could define the relationship as follows:

```<code>public class MyDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Building>().HasMany(it => it.Architects).WithMany(it => it.BuildingsBeingWorkedOn);
        modelBuilder.Entity<Building>().HasMany(it => it.BuildingGroups).WithMany(it => it.Buildings);

        base.OnModelCreating(modelBuilder);
    }
}
</code>```

Body:
I'm having quite the issue right now while trying to learn Entity Framework.
Let's say I have this entity:

public class BuildingGroup {
    public int ID { get; set; }
    public string NameOfManager { get; set; }

    public virtual ICollection<Building> Buildings { get; set; }
}

And also this entity.

public class Architect {
    public int ID { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Building> BuildingsBeingWorkedOn { get; set; }
}

These two entities are completely unrelated. Here's the Building entity:

public class Building {
    public int ID { get; set; }
    public string Address { get; set; }
}

My problem happens when I try to add a building to, say a BuildingGroup. In my domain model, I can modify the equivalent collection of buildings, by adding, modifying or removing buildings. However, when I try to update BuildingGroup through a repository, the buildings will not be updated.

public void Update(BuildingGroup buildingGroup) {
    var buildingGroupEntity = _context.BuildingGroups.Single(b => b.ID == buildingGroup.ID);

    // This will not map the Building collection
    context.Entry(buildingGroupEntity).CurrentValues.SetValues(buildingGroup);

    // My attempt at mapping the buildings
    buildingGroupEntity.Buildings.Clear();
    buildingGroup.Buildings.ToList().ForEach(b => buildingGroupEntity.Buildings.Add(_context.Buildings.Single(x => x.ID == b.ID)));

    _context.Entry(buildingGroupEntity).State = EntityState.Modified;
}

This fails if the building were not saved in the database prior to the call to Update(), which is normal since buildings can live independently. It must also be done for every child collection of BuildingGroup (if there were more), and for child collections of these children, well...

I have noticed other people use a foreign key constraint in the child object (here, Building), but I can't really do that since many unrelated entities can point to a building: I'd have a lot of navigation properties.

Is there a graceful way to manage referencing objects that can also live independently from those who hold references to them?

Body:
If all the entities have to exist independently, yet have relationships with each other, it's better to use many-to-many relationship.

Change your model classes as follows, the Building should contain a couple of collections for architects and groups.

public class BuildingGroup
{
    public int ID { get; set; }
    public string NameOfManager { get; set; }

    public virtual ICollection<Building> Buildings { get; set; }
}

public class Architect
{
    public int ID { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Building> BuildingsBeingWorkedOn { get; set; }
}

public class Building
{
    public int ID { get; set; }
    public string Address { get; set; }

    public virtual ICollection<Architect> Architects { get; set; }
    public virtual ICollection<BuildingGroup> BuildingGroups { get; set; }
}

If you use entity type configuration, you could define the relationship as follows:

public class MyDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Building>().HasMany(it => it.Architects).WithMany(it => it.BuildingsBeingWorkedOn);
        modelBuilder.Entity<Building>().HasMany(it => it.BuildingGroups).WithMany(it => it.Buildings);

        base.OnModelCreating(modelBuilder);
    }
}


问:
dojo dstore insert row
Can anyone assist me in inserting a row into a DGRID? The way I am doing it now is cloning a row, add it to the collection with the use of directives and then try to apply it to the grid. Below is the code I am using but the new row ends up getting added to the bottom instead of being inserted.</p>

```<code>// Clone a row

theTable = tmxdijit.registry.byId(tableName);

firstRow = theTable.collection.data[theTable.collection.data.length-1];

firstRowDom = theTable.row(firstRow.id);

var cloneRow = json.stringify(firstRow);

cloneRow = json.parse(cloneRow);

// Get the row I want to add before

var theSelected = Object.keys(theTable.selection)[0];

if(theSelected.length > 0) {

    var theRowID = theSelected[0];

}

theTable.collection.add(cloneRow, {beforeId: theRowID});

theTable.renderArray([cloneRow]);
</code>```

答:
There are two general ways to handle data insertion. One is to manually add data to an array, ensure it's properly sorted, and then tell the grid to render the array. A better way is to use an OnDemandGrid with a trackable store.

For dgrid/dstore to support simple dynamic insertion of rows, make sure the store is trackable, and that data items have some unique id property:

```<code>var StoreClass = Memory.createSubclass(Trackable);
var store = new StoreClass({ data: whatever });
var grid = new OnDemandGrid({
    columns: { /* columns */ },
    collection: store
});
</code>```

By default dstore assumes the id property is "id", but you can specify something else:

```<code>var store = new StoreClass({ idProperty: "name", data: whatever });
</code>```

If you want the data to be sorted, a simple solution is to set a sort on the grid (the grid will sort rows in ascending order using the given property name):

```<code>grid.set('sort', 'name');
</code>```

To add or remove data, use the store methods put and remove.

```<code>var collection = grid.get('collection');
collection.put(/* a new data item */);
collection.remove(/* a data item id */);
</code>```

The grid will be notified of the store update and will insert or remove the rows.

The dgrid Using Grids and Stores tutorial has more information and examples.

Title: dojo dstore insert row

Body:
Can anyone assist me in inserting a row into a DGRID? The way I am doing it now is cloning a row, add it to the collection with the use of directives and then try to apply it to the grid. Below is the code I am using but the new row ends up getting added to the bottom instead of being inserted.

// Clone a row

theTable = tmxdijit.registry.byId(tableName);

firstRow = theTable.collection.data[theTable.collection.data.length-1];

firstRowDom = theTable.row(firstRow.id);

var cloneRow = json.stringify(firstRow);

cloneRow = json.parse(cloneRow);

// Get the row I want to add before

var theSelected = Object.keys(theTable.selection)[0];

if(theSelected.length > 0) {

    var theRowID = theSelected[0];

}

theTable.collection.add(cloneRow, {beforeId: theRowID});

theTable.renderArray([cloneRow]);

Body:
There are two general ways to handle data insertion. One is to manually add data to an array, ensure it's properly sorted, and then tell the grid to render the array. A better way is to use an OnDemandGrid with a trackable store.

For dgrid/dstore to support simple dynamic insertion of rows, make sure the store is trackable, and that data items have some unique id property:

var StoreClass = Memory.createSubclass(Trackable);
var store = new StoreClass({ data: whatever });
var grid = new OnDemandGrid({
    columns: { /* columns */ },
    collection: store
});

By default dstore assumes the id property is "id", but you can specify something else:

var store = new StoreClass({ idProperty: "name", data: whatever });

If you want the data to be sorted, a simple solution is to set a sort on the grid (the grid will sort rows in ascending order using the given property name):

grid.set('sort', 'name');

To add or remove data, use the store methods put and remove.

var collection = grid.get('collection');
collection.put(/* a new data item */);
collection.remove(/* a data item id */);

The grid will be notified of the store update and will insert or remove the rows.

The dgrid Using Grids and Stores tutorial has more information and examples.


问:
Vertical cut off of text in label with letters such as p and g
I have a label in a stack view that displays a variety of different text however when it displays p and g, the bottoms are cut off as you can see here.

Is there any way to prevent this?

Update: I need the size of my label to stay the same and rather the font size of the label to change.

答:
To make sure your label is always big enough for the content inside, you need to call sizeToFit() every time after you set the text.

Here is the sample code

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    label.text = "gpb"
    label.backgroundColor = .red
    label.sizeToFit()

    Timer.scheduledTimer(timeInterval: 1, target: self,
                         selector: #selector(self.timerDidFire(timer:)), userInfo: nil, repeats: true)

}

func timerDidFire(timer: Timer) {
    size += 5
    label.font = label.font.withSize(CGFloat(size))
    label.sizeToFit()
}
</code>```

And it looks like

Body:
To make sure your label is always big enough for the content inside, you need to call sizeToFit() every time after you set the text.

Here is the sample code

override func viewDidLoad() {
    super.viewDidLoad()

    label.text = "gpb"
    label.backgroundColor = .red
    label.sizeToFit()

    Timer.scheduledTimer(timeInterval: 1, target: self,
                         selector: #selector(self.timerDidFire(timer:)), userInfo: nil, repeats: true)

}

func timerDidFire(timer: Timer) {
    size += 5
    label.font = label.font.withSize(CGFloat(size))
    label.sizeToFit()
}

And it looks like


问:
Data coming back as undefined in react
I'm trying to pass data down to a component with react router. I've tested that the end point works correctly, so it's not a server issue.

This is my function that is supposed to grab the page data based on the ID param:

```<code>    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }
</code>```

And my React Route:

```<code>    <Route path="/admin/edit-page/:id" render={ (props) => (
      <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
    )} />
</code>```

But page is coming back undefined when I goto

localhost:3000/admin/edit-page/1

If I console.log(response.data) inside the setPage function, I can see the correct data in the console. This is so weird.

Am I not supposed to return response.data ??

This is the whole App.js container file:

```<code>import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
    this.getPages = this.getPages.bind(this)
    this.setPage = this.setPage.bind(this)

  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      this.getPages();
      //TODO: Create my own history object as props, then use router to push route.
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }

  setPage(id) {
    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>
        <div className="Router">
          <div className="Navbar">
            <Header />
          </div>
          <div className="Wrapper">
            <Route exact path="/" render={ (props) => (
              <Dashboard {...props} pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ (props) => (
              <AddEditPage {...props} createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ (props) => (
              <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
            )} />
          </div>
        </div>
      </Router>

    );
  }
}

export default App;
</code>```

答:
Looks like you're calling a function, not passing a reference to it:

```<code> page={this.setPage(props.match.params.id)}
</code>```

That's almost definitely not what you want to do.

Title: Data coming back as undefined in react

Body:
I'm trying to pass data down to a component with react router. I've tested that the end point works correctly, so it's not a server issue.

This is my function that is supposed to grab the page data based on the ID param:

    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

And my React Route:

    <Route path="/admin/edit-page/:id" render={ (props) => (
      <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
    )} />

But page is coming back undefined when I goto

localhost:3000/admin/edit-page/1

If I console.log(response.data) inside the setPage function, I can see the correct data in the console. This is so weird.

Am I not supposed to return response.data ??

This is the whole App.js container file:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import axios from 'axios'

import Header from '../components/Header'

import Dashboard from './Dashboard'
import AddEditPage from './AddEditPage'

const instance = axios.create({baseURL: 'http://localhost:1337'})

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      "pages": []
    }
    this.createPage = this.createPage.bind(this)
    this.getPages = this.getPages.bind(this)
    this.setPage = this.setPage.bind(this)

  }

  componentDidMount() {
    this.getPages()
  }

  getPages() {
    instance.get('/admin/listPages')
      .then(
        (response) => {
          this.setState(
            {
              "pages": response.data
            }
          )
        })
      .catch((error) => {console.log(error)})
  }

  createPage(page) {
    instance.post('/admin/createPage',page).then((response) => {
      this.getPages();
      //TODO: Create my own history object as props, then use router to push route.
      window.location.replace('/')
    }).catch((error) => {
      console.log(error)
    })
  }

  setPage(id) {
    instance.get(`/admin/page/${id}`).then((response) => {
      return response.data
    }).catch((error) => {
      console.log(error)
    })
  }

  render() {
    return (
      <Router>

            <Route exact path="/" render={ (props) => (
              <Dashboard {...props} pages={this.state.pages} />
            )} />
            <Route path="/admin/new-page" render={ (props) => (
              <AddEditPage {...props} createPage={this.createPage} />
            )} />
            <Route path="/admin/edit-page/:id" render={ (props) => (
              <AddEditPage {...props} page={this.setPage(props.match.params.id)} />
            )} />

      </Router>

    );
  }
}

export default App;

Body:
Looks like you're calling a function, not passing a reference to it:

 page={this.setPage(props.match.params.id)}

That's almost definitely not what you want to do.


问:
How can I make a Discord bot require x permissions when adding it? Using Python
Maybe this is a noob question, really easy, but I have no idea how to do it.
For sure, you've seen other Discord bots, when you add them, they require certain permissions like "Administrator", "kick lower ranked members", "Manage messages", etc.

This would be easier to server's owner to setup the bot. Instead of they have to create a role, then setup those permissions, he could just tick them.

How can I do this?

答: Use this calculator https://discordapi.com/permissions.html , tick the boxes for the permissions you would like the bot to request upon someone clicking the invite link. Once you've gotten the number, add it to the end of your invite link where it has permissions=


问:
Q: Resample bitstamp bars in pyalgotrade
I'm working with an algo on the bitstamp client that works better with 30-min bars, rather than seeing each trade as a bar.

Is there a "right" way to resample those bars into 30-min intervals on the fly?

I can do it no problem with the bitcoincharts broker, but I need the execution from the bitstampbroker, so I was hoping to do it with one.

答:
This should help:</p>

```<code>from pyalgotrade.bitstamp import barfeed
from pyalgotrade.bitstamp import broker
from pyalgotrade import strategy

class Strategy(strategy.BaseStrategy):
    def __init__(self, feed, brk):
        super(Strategy, self).__init__(feed, brk)
        self._instrument = "BTC"
        self._bid = None
        self._ask = None
        self._resampledBF = self.resampleBarFeed(60, self.onResampledBars)

        # Subscribe to order book update events to get bid/ask prices to trade.
        feed.getOrderBookUpdateEvent().subscribe(self._onOrderBookUpdate)

    def _onOrderBookUpdate(self, orderBookUpdate):
        bid = orderBookUpdate.getBidPrices()[0]
        ask = orderBookUpdate.getAskPrices()[0]

        if bid != self._bid or ask != self._ask:
            self._bid = bid
            self._ask = ask
            self.info("Order book updated. Best bid: %s. Best ask: %s" % (self._bid, self._ask))

    def onResampledBars(self, dt, bars):
        bar = bars[self._instrument]
        self.info("Resampled - Price: %s. Volume: %s." % (bar.getClose(), bar.getVolume()))

    def onBars(self, bars):
        bar = bars[self._instrument]
        self.info("Price: %s. Volume: %s." % (bar.getClose(), bar.getVolume()))

def main():
    barFeed = barfeed.LiveTradeFeed()
    brk = broker.PaperTradingBroker(1000, barFeed)
    strat = Strategy(barFeed, brk)

    strat.run()

if __name__ == "__main__":
    main()
</code>```

Body:
This should help:

from pyalgotrade.bitstamp import barfeed
from pyalgotrade.bitstamp import broker
from pyalgotrade import strategy

class Strategy(strategy.BaseStrategy):
    def __init__(self, feed, brk):
        super(Strategy, self).__init__(feed, brk)
        self._instrument = "BTC"
        self._bid = None
        self._ask = None
        self._resampledBF = self.resampleBarFeed(60, self.onResampledBars)

        # Subscribe to order book update events to get bid/ask prices to trade.
        feed.getOrderBookUpdateEvent().subscribe(self._onOrderBookUpdate)

    def _onOrderBookUpdate(self, orderBookUpdate):
        bid = orderBookUpdate.getBidPrices()[0]
        ask = orderBookUpdate.getAskPrices()[0]

        if bid != self._bid or ask != self._ask:
            self._bid = bid
            self._ask = ask
            self.info("Order book updated. Best bid: %s. Best ask: %s" % (self._bid, self._ask))

    def onResampledBars(self, dt, bars):
        bar = bars[self._instrument]
        self.info("Resampled - Price: %s. Volume: %s." % (bar.getClose(), bar.getVolume()))

    def onBars(self, bars):
        bar = bars[self._instrument]
        self.info("Price: %s. Volume: %s." % (bar.getClose(), bar.getVolume()))

def main():
    barFeed = barfeed.LiveTradeFeed()
    brk = broker.PaperTradingBroker(1000, barFeed)
    strat = Strategy(barFeed, brk)

    strat.run()

if __name__ == "__main__":
    main()


问:
set args for JDB
The command I use to execute my Java code is:

```<code>java -cp /usr/local/share/java/dbus.jar:/usr/local/share/java/unix.jar:/usr/local/share/java/debug-disable.jar:. \
-Djava.library.path=/usr/local/lib/jniCaller3 org.freedesktop.DBus" "/org/freedesktop/DBus" "org.freedesktop.DBus" "Hello"
</code>```

How can I pass the args into JDB?

```<code>~/jdbus> jdb Caller3
Initializing jdb ...
>
</code>```

Now what? With GDB I'd simply use set args.

```<code>> set args -cp /usr/local/share/java/dbus.jar:/usr/local/share/java/unix.jar:/usr/local/share/java/debug-disable.jar:. \
-Djava.library.path=/usr/local/lib/jni org.freedesktop.DBus" "/org/freedesktop/DBus" "org.freedesktop.DBus" "Hello"
</code>```

答:
You can simply pass arguments into jdb</p>

```<code>> cat Code.java
public class Code {
  public static void main(String [] arg) {
    System.out.println(arg[0]);
  }
}
> javac Code.java
> java -cp . Code Hello
Hello
> jdb -classpath . Code hello
Initializing jdb ...
> run
run Code hello
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: hello

The application exited
</code>```

Title: set args for JDB

Body:
The command I use to execute my Java code is:

java -cp /usr/local/share/java/dbus.jar:/usr/local/share/java/unix.jar:/usr/local/share/java/debug-disable.jar:. \
-Djava.library.path=/usr/local/lib/jniCaller3 org.freedesktop.DBus" "/org/freedesktop/DBus" "org.freedesktop.DBus" "Hello"

How can I pass the args into JDB?

~/jdbus> jdb Caller3
Initializing jdb ...
>

Now what? With GDB I'd simply use set args.

> set args -cp /usr/local/share/java/dbus.jar:/usr/local/share/java/unix.jar:/usr/local/share/java/debug-disable.jar:. \
-Djava.library.path=/usr/local/lib/jni org.freedesktop.DBus" "/org/freedesktop/DBus" "org.freedesktop.DBus" "Hello"

Body:
You can simply pass arguments into jdb

> cat Code.java
public class Code {
  public static void main(String [] arg) {
    System.out.println(arg[0]);
  }
}
> javac Code.java
> java -cp . Code Hello
Hello
> jdb -classpath . Code hello
Initializing jdb ...
> run
run Code hello
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: hello

The application exited


问:
Why bufferedreader.readLine() needs to equal to a temporary string while reading it?
As following code snippet shown. While reading with BufferedReader, the Buffereder.readLine() is always set to a temporary string.

```<code>String hello = "hello ";
byte[] data = hello.getBytes();
ByteArrayInputStream bai = new ByteArrayInputStream(data);

try(BufferedReader br = new BufferedReader(new InputStreamReader(bai))){
      String temp;

      while((temp=br.readLine())!=null)
         System.out.println(temp);

}catch(Exception exception){

}
</code>```

Why can't we just do

```<code>while(br.readLine()!=null)
   System.out.println(br.readLine())
</code>```

答:
If you do

```<code>while(br.readLine()!=null)
   System.out.println(br.readLine())
</code>```

you will throw away every other line.  Think about it. Each time around the loop you do readLine() and test to see if it's not null.  OK, it's not, so you go into the loop and do another readLine().  What happened to the line you read and tested to decide if you should go into the loop?

Body:
As following code snippet shown. While reading with BufferedReader, the Buffereder.readLine() is always set to a temporary string.

String hello = "hello ";
byte[] data = hello.getBytes();
ByteArrayInputStream bai = new ByteArrayInputStream(data);

try(BufferedReader br = new BufferedReader(new InputStreamReader(bai))){
      String temp;

      while((temp=br.readLine())!=null)
         System.out.println(temp);

}catch(Exception exception){

}

Why can't we just do

while(br.readLine()!=null)
   System.out.println(br.readLine())

Body:
If you do

while(br.readLine()!=null)
   System.out.println(br.readLine())

you will throw away every other line.  Think about it. Each time around the loop you do readLine() and test to see if it's not null.  OK, it's not, so you go into the loop and do another readLine().  What happened to the line you read and tested to decide if you should go into the loop?


问:
Speed up write numpy data in binary to file. ply generator
I made my own ply exporter and even though it is working, it is quite slow. I'm assuming that the problem comes from specifically looping over the elements and, based on this comment, from using struct.pack.

The challenge with exporting Nodes is that it is a 1D vector of tuples. The challenge with exporting Faces is that each line of ints is preceded by a number "3" in uchar format.

I put the entire code here since it serves as a MWE and also a reference if someone wants to use the code to export meshes in ply format.

Code:

```<code>from __future__ import division
import numpy as np
import struct
import timeit

def Timeme(funct,var,NN=10,NNN=10):
    for i in xrange(NN):
        start =timeit.default_timer()
        for t in xrange(NNN):
            funct(*var)
        end =timeit.default_timer()
        print str(i)+': '+str((end - start)/NNN*1000)

# This function is fictitious. In reality the
# Nodes array is imported from another module
def MakeNodes(Nr,Nc):
    Nodes=np.zeros(Nr*Nc,dtype=[('x', np.float32), ('y', np.float32), ('z', np.float32)])
    x = np.linspace(0, (Nc-1), Nc, dtype=np.float32)
    y = np.linspace((Nr-1),0 , Nr, dtype=np.float32)
    xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy')
    Nodes['x']=xv.flatten()
    Nodes['y']=yv.flatten()
    Nodes['z']=(1/2-((Nodes['x']/Nc-1/2)**2+ (Nodes['y']/Nr-1/2)**2))*Nr/2
    return Nodes

# Function below explained in https://stackoverflow.com/questions/44934631
def MakeFaces(Nr,Nc):
    out = np.empty((Nr-1,Nc-1,2,3),dtype=int)
    r = np.arange(Nr*Nc).reshape(Nr,Nc)
    l1=r[:-1,:-1]
    l2=r[:-1,1:]
    l3=r[1:,:-1]
    l4=r[1:,1:]
    out[:,:, 0,0] = l2
    out[:,:, 0,1] = l1
    out[:,:, 0,2] = l3
    out[:,:, 1,0] = l4
    out[:,:, 1,1] = l2
    out[:,:, 1,2] = l3
    out.shape =(-1,3)
    return out

def ExportPlyBinary(Nodes,Faces,file):
    LN=len(Nodes)
    LF=len(Faces)

    header= \
    "ply\n" \
    "format binary_little_endian 1.0\n" \
    "element vertex "+str(LN)+"\n" \
    "property float x\n" \
    "property float y\n" \
    "property float z\n" \
    "element face "+str(LF)+"\n" \
    "property list uchar int vertex_indices\n" \
    "end_header\n"

    with open(file, 'wb') as fp:
        fp.write(header)
        s = struct.Struct('<fff')
        for nd in Nodes:
            fp.write(s.pack(nd['x'],nd['y'],nd['z']))

        s = struct.Struct('<Blll')
        for fc in Faces:
            fp.write(s.pack(3,fc[0],fc[1],fc[2]))

Nr=200
Nc=200
Nodes=MakeNodes(Nr,Nc)
Faces=MakeFaces(Nr,Nc)
Timeme(ExportPlyBinary,(Nodes,Faces,"Test.ply"))
Timeme(np.savez,("Test_np.ply", Nodes,Faces))
</code>```

Result:

```<code>0: 366.352801235
1: 386.216017627
2: 383.307741944
3: 359.598214393
4: 363.434228045
5: 397.255473919
6: 433.967095136
7: 407.806616677
8: 393.701390596
9: 379.542319143
0: 15.5258007875
1: 13.2543344563
2: 12.8754439597
3: 24.2303215372
4: 15.9684973291
5: 14.2023306048
6: 13.7465456437
7: 13.6964054484
8: 21.27484093
9: 13.2139143373
</code>```

答:
Why not use what is available?

For example trimesh?
https://pypi.python.org/pypi/trimesh

Even when you wan't only a small part of the package you can copy and adjust this part from their source code. (with mentioning the authors of course)

Body:
I made my own ply exporter and even though it is working, it is quite slow. I'm assuming that the problem comes from specifically looping over the elements and, based on this comment, from using struct.pack.

The challenge with exporting Nodes is that it is a 1D vector of tuples. The challenge with exporting Faces is that each line of ints is preceded by a number "3" in uchar format.

I put the entire code here since it serves as a MWE and also a reference if someone wants to use the code to export meshes in ply format.

Code:

from __future__ import division
import numpy as np
import struct
import timeit

def Timeme(funct,var,NN=10,NNN=10):
    for i in xrange(NN):
        start =timeit.default_timer()
        for t in xrange(NNN):
            funct(*var)
        end =timeit.default_timer()
        print str(i)+': '+str((end - start)/NNN*1000)

# This function is fictitious. In reality the
# Nodes array is imported from another module
def MakeNodes(Nr,Nc):
    Nodes=np.zeros(Nr*Nc,dtype=[('x', np.float32), ('y', np.float32), ('z', np.float32)])
    x = np.linspace(0, (Nc-1), Nc, dtype=np.float32)
    y = np.linspace((Nr-1),0 , Nr, dtype=np.float32)
    xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy')
    Nodes['x']=xv.flatten()
    Nodes['y']=yv.flatten()
    Nodes['z']=(1/2-((Nodes['x']/Nc-1/2)**2+ (Nodes['y']/Nr-1/2)**2))*Nr/2
    return Nodes

# Function below explained in https://stackoverflow.com/questions/44934631
def MakeFaces(Nr,Nc):
    out = np.empty((Nr-1,Nc-1,2,3),dtype=int)
    r = np.arange(Nr*Nc).reshape(Nr,Nc)
    l1=r[:-1,:-1]
    l2=r[:-1,1:]
    l3=r[1:,:-1]
    l4=r[1:,1:]
    out[:,:, 0,0] = l2
    out[:,:, 0,1] = l1
    out[:,:, 0,2] = l3
    out[:,:, 1,0] = l4
    out[:,:, 1,1] = l2
    out[:,:, 1,2] = l3
    out.shape =(-1,3)
    return out

def ExportPlyBinary(Nodes,Faces,file):
    LN=len(Nodes)
    LF=len(Faces)

    header= \
    "ply\n" \
    "format binary_little_endian 1.0\n" \
    "element vertex "+str(LN)+"\n" \
    "property float x\n" \
    "property float y\n" \
    "property float z\n" \
    "element face "+str(LF)+"\n" \
    "property list uchar int vertex_indices\n" \
    "end_header\n"

    with open(file, 'wb') as fp:
        fp.write(header)
        s = struct.Struct('<fff')
        for nd in Nodes:
            fp.write(s.pack(nd['x'],nd['y'],nd['z']))

        s = struct.Struct('<Blll')
        for fc in Faces:
            fp.write(s.pack(3,fc[0],fc[1],fc[2]))

Nr=200
Nc=200
Nodes=MakeNodes(Nr,Nc)
Faces=MakeFaces(Nr,Nc)
Timeme(ExportPlyBinary,(Nodes,Faces,"Test.ply"))
Timeme(np.savez,("Test_np.ply", Nodes,Faces))

Result:

0: 366.352801235
1: 386.216017627
2: 383.307741944
3: 359.598214393
4: 363.434228045
5: 397.255473919
6: 433.967095136
7: 407.806616677
8: 393.701390596
9: 379.542319143
0: 15.5258007875
1: 13.2543344563
2: 12.8754439597
3: 24.2303215372
4: 15.9684973291
5: 14.2023306048
6: 13.7465456437
7: 13.6964054484
8: 21.27484093
9: 13.2139143373


问:
I want to set a variable 's value from another php file
So i have dashboard.php

```<code>$value1;
$value1 = 1;
</code>```

and file.php

```<code>$value;
echo value;
</code>```

So i want to print "1" on the file file.php. How can i tell file.php to get the variable 's value from dashboard.php

答: simply use inlcude/require or use spl_autoload_register. if you want to get the value from frontend, maybe you will use session,$_GET or $_POST.

Body:
So i have dashboard.php

$value1;
$value1 = 1;

and file.php

$value;
echo value;

So i want to print "1" on the file file.php. How can i tell file.php to get the variable 's value from dashboard.php