问:
ACTION_TIME_CHANGED or ACTION_DATE_CHANGED, can't make them work
So I am in the process of trying to get a few intents to work for me,
and am having problems on 2 specific intents.  I searched these groups
and the webs and can 't seem to find any more information than what
the documentation gives me.
It doesn't seem to matter if I declare the use of these intent in the
manifest, or if I try to register a receiver in code, my receiver
never receives the actions for ACTION_TIME_CHANGED or
ACTION_DATE_CHANGED.
As far as I can tell I should be receiving these actions in my
broadcast receiver whenever the user explicitly sets the time/date by
going to "Settings" --> "Date & Time" and then modifying the time or
date
Am I mis-interpreting what these actions are for?
Are there any permissions that I need to declare in order to receive
these actions?
Does anybody worked with this actions ?

Is there some useful example where this actions are used, I could not find anything useful, there is plenty of examples of format change but not on actual time_date change...

Thanks in advance

答:
An alternative approach which I used to take an action when the date is changed.

Actually, the Intent.ACTION_DATE_CHANGED only works with the date of an advanced date and not with a previous date when you change the date on the phone manually. Also, when you set time to 11:59 and wait for it to become 00:00 to give you the broadcast event of the date change, it doesn't give you the trigger.

So, I ended up making my own logic of storing a date in shared pref and then checking if the current date is after or before previously stored date (with some date processing logic) and updating my data based on that.

```<code>  private void takesomeActionIfDateIsChanged() {
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

        long currentDateTimeInMillis = System.currentTimeMillis();
        Date currentDateWithMillis = new Date(currentDateTimeInMillis);

        String formattedCurrentDateWithOnlyDMYStr = dateFormat.format(currentDateWithMillis);
        Log.d(TAG, "formattedCurrentDate With Only DateMonthAndYear String : " + formattedCurrentDateWithOnlyDMYStr);
        Date formattedCurrentDate = dateFormat.parse(formattedCurrentDateWithOnlyDMYStr);

        String storedDateStr = mSpManager.getStoredDate(SPManager.STORED_DATE);
        Log.d(TAG, "storedDateStr : " + storedDateStr);
        Date storedDateOnlyWithDateMonthAndYear = dateFormat.parse(storedDateStr);

        if (formattedCurrentDate.after(storedDateOnlyWithDateMonthAndYear)) {
            Log.d(TAG, "The current date is after stored date");
            mSpManager.putNewDate(SPManager.STORED_DATE, formattedCurrentDateWithOnlyDMYStr);
            mCounter = 0;
        } else if (formattedCurrentDate.before(storedDateOnlyWithDateMonthAndYear)) {
            Log.d(TAG, "The current date is before stored date");
            mSpManager.putNewDate(SPManager.STORED_DATE, formattedCurrentDateWithOnlyDMYStr);
            mCounter = 0;
        } else {
            Log.d(TAG, "The current date is same as stored date");
        }
    } catch (Exception e) {
        Log.e(TAG, "exception : ", e);
    }
}
</code>```

Body:
An alternative approach which I used to take an action when the date is changed.

Actually, the Intent.ACTION_DATE_CHANGED only works with the date of an advanced date and not with a previous date when you change the date on the phone manually. Also, when you set time to 11:59 and wait for it to become 00:00 to give you the broadcast event of the date change, it doesn't give you the trigger.

So, I ended up making my own logic of storing a date in shared pref and then checking if the current date is after or before previously stored date (with some date processing logic) and updating my data based on that.

  private void takesomeActionIfDateIsChanged() {
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

        long currentDateTimeInMillis = System.currentTimeMillis();
        Date currentDateWithMillis = new Date(currentDateTimeInMillis);

        String formattedCurrentDateWithOnlyDMYStr = dateFormat.format(currentDateWithMillis);
        Log.d(TAG, "formattedCurrentDate With Only DateMonthAndYear String : " + formattedCurrentDateWithOnlyDMYStr);
        Date formattedCurrentDate = dateFormat.parse(formattedCurrentDateWithOnlyDMYStr);

        String storedDateStr = mSpManager.getStoredDate(SPManager.STORED_DATE);
        Log.d(TAG, "storedDateStr : " + storedDateStr);
        Date storedDateOnlyWithDateMonthAndYear = dateFormat.parse(storedDateStr);

        if (formattedCurrentDate.after(storedDateOnlyWithDateMonthAndYear)) {
            Log.d(TAG, "The current date is after stored date");
            mSpManager.putNewDate(SPManager.STORED_DATE, formattedCurrentDateWithOnlyDMYStr);
            mCounter = 0;
        } else if (formattedCurrentDate.before(storedDateOnlyWithDateMonthAndYear)) {
            Log.d(TAG, "The current date is before stored date");
            mSpManager.putNewDate(SPManager.STORED_DATE, formattedCurrentDateWithOnlyDMYStr);
            mCounter = 0;
        } else {
            Log.d(TAG, "The current date is same as stored date");
        }
    } catch (Exception e) {
        Log.e(TAG, "exception : ", e);
    }
}


来源: stackexchange

问:
Unit Testing Express Controllers
I am having trouble unit testing with Express on a number of fronts, seems to be a lack of documentation and general info online about it.

So far I have found out I can test my routes with a library called supertest (https://github.com/visionmedia/superagent), but what if I have broken my routes and controllers up, how can I go about testing my controllers independently of their routes.

here is my test:

```<code>describe("Products Controller", function() {
    it("should add a new product to the mongo database", function(next) {
        var ProductController = require('../../controllers/products');
        var Product = require('../../models/product.js');

        var req = {
            params: {
                name: 'Coolest Product Ever',
                description: 'A very nice product'
            }
        };

        ProductController.create(req, res);

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

req is easy enough to mockup. res not so much, I tried grabbing express.response, hoping I could just inject it but this hasn't worked. Is there a way to simulate the res.send object? Or am I going the wrong way about this?

答:
When you are testing your routes, you don't actually use the inbuilt functions. Say for example, ProductController.create(req, res);

What you basically need to do is, run the server on a port and send a request for each url. As you mentioned supergent, you can follow this code.

```<code>describe("Products Controller", function() {
    it("should add a new product to the mongo database", function(next) {
        const request = require('superagent');
        request.post('http://localhost/yourURL/products')
            .query({ name: 'Coolest Product Ever', description: 'A very nice product' })
            .set('Accept', 'application/json')
            .end(function(err, res){
                if (err || !res.ok) {
                    alert('Oh no! error');
                } else {
                    alert('yay got ' + JSON.stringify(res.body));
                }
       });
    });
});
</code>```

You can refer to superagent request examples here.

ContentLicense: CC BY-SA 3.0

Title: Unit Testing Express Controllers

Body:
I am having trouble unit testing with Express on a number of fronts, seems to be a lack of documentation and general info online about it.

So far I have found out I can test my routes with a library called supertest (https://github.com/visionmedia/superagent), but what if I have broken my routes and controllers up, how can I go about testing my controllers independently of their routes.

here is my test:

describe("Products Controller", function() {
    it("should add a new product to the mongo database", function(next) {
        var ProductController = require('../../controllers/products');
        var Product = require('../../models/product.js');

        var req = {
            params: {
                name: 'Coolest Product Ever',
                description: 'A very nice product'
            }
        };

        ProductController.create(req, res);

    });
});

req is easy enough to mockup. res not so much, I tried grabbing express.response, hoping I could just inject it but this hasn't worked. Is there a way to simulate the res.send object? Or am I going the wrong way about this?

Body:
When you are testing your routes, you don't actually use the inbuilt functions. Say for example, ProductController.create(req, res);

What you basically need to do is, run the server on a port and send a request for each url. As you mentioned supergent, you can follow this code.

describe("Products Controller", function() {
    it("should add a new product to the mongo database", function(next) {
        const request = require('superagent');
        request.post('http://localhost/yourURL/products')
            .query({ name: 'Coolest Product Ever', description: 'A very nice product' })
            .set('Accept', 'application/json')
            .end(function(err, res){
                if (err || !res.ok) {
                    alert('Oh no! error');
                } else {
                    alert('yay got ' + JSON.stringify(res.body));
                }
       });
    });
});

You can refer to superagent request examples here.


问:
how to write a function in haskell which inserts space after every character of String
i want to implemet a method in haskeel which should add space after every char of string passed to that method but not after the last char of the string
 for example</p>

```<code>Main> insertSpace "This is world"
"T h i s  i s  w o r l d"
</code>```

答:
You could write this by hand through explicit recursion.

```<code>insertSpace :: String -> String
insertSpace []     = []
insertSpace (x:[]) = x  -- you need this to keep from adding a space at the end
insertSpace (x:xs) = x:' ':(insertSpace xs)
</code>```

but there is a stdlib function for this in Data.List -- intersperse.

```<code>import Data.List (intersperse)

insertSpace :: String -> String
insertSpace = intersperse ' '
</code>```

This is the first result when you search Hoogle for Char -> String -> String.

Body:
i want to implemet a method in haskeel which should add space after every char of string passed to that method but not after the last char of the string
 for example

Main> insertSpace "This is world"
"T h i s  i s  w o r l d"

Body:
You could write this by hand through explicit recursion.

insertSpace :: String -> String
insertSpace []     = []
insertSpace (x:[]) = x  -- you need this to keep from adding a space at the end
insertSpace (x:xs) = x:' ':(insertSpace xs)

but there is a stdlib function for this in Data.List -- intersperse.

import Data.List (intersperse)

insertSpace :: String -> String
insertSpace = intersperse ' '

This is the first result when you search Hoogle for Char -> String -> String.


问:
how to launch jenkins with previous jobs
I shutdown jenkins for some purpose. Wonted to launch the jenkins from previous workspace. is there a way to restore the same old jobs?
I am starting jenkins like

java -jar jenkins.war --httpPort=8083 &

But is there a way to provide workspace from commandline?

答: Workspace is a specific term related to jobs in Jenkins. I think you are looking for JENKINS_HOME.  Set the environment variable to the path to the directory that has all your jenkins config and jobs before you start Jenkins. </p>


问:
Difference between returning a value and returning Promise.resolve() from a function
I have problem in understanding that what happens when we simply return a value or when we return Promise.resolve() from a function. Specifically: I am trying to understand how promises chaining works. I am chaining methods and verifying whether the value reaches in the method which is last call to then. I just want to understand the difference between returning promises to then, returning Promise.resolve() to then, and returning just a value to then.

答:
When you return Promise.resolve(), you wrap your result into a Promise, on which you can call then and make chain of then. This is preferable for a single type returns.

function resolve() {
   return Promise.resolve(15);
}

resolve().then(value => console.log(value));```
</div>
</div>
</p>

<p>If you have a logic which depends on a call to the server and also you can have that result in the <code>cache</code>, you can have a function which in all cases returns you a Promise, so you can add <code>then</code> for the result of the Promise. Look at this pseudo-code. </p>

<p>I want my function in all cases return a Promise. So here if I have cached the <code>userId</code> I can just wrap the result into the Promise with <code>Promise.resolve</code></p>

```function getUserData() {
   if(cache.hasUserId) {
      return Promise.resolve(cache.hasUserId); // Is used to let the `then` functions to be called
   } else {
      return myAjaxCall();
   }
}

getUserData().then(userId => /* */);
```

<p>Base on comment. Wrap into the <code>Promise.resolve()</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function add1(data) {
  return new Promise(function (resolve, reject) {
               resolve(data + 1);
         });
}

function add2(data) {
   return Promise.resolve(data + 2);
}

function printdata(data) {
   console.log(data);
}</code>```

Body:
When you return Promise.resolve(), you wrap your result into a Promise, on which you can call then and make chain of then. This is preferable for a single type returns.

function resolve() {
   return Promise.resolve(15);
}

resolve().then(value => console.log(value));

If you have a logic which depends on a call to the server and also you can have that result in the cache, you can have a function which in all cases returns you a Promise, so you can add then for the result of the Promise. Look at this pseudo-code.

I want my function in all cases return a Promise. So here if I have cached the userId I can just wrap the result into the Promise with Promise.resolve

function getUserData() {
   if(cache.hasUserId) {
      return Promise.resolve(cache.hasUserId); // Is used to let the `then` functions to be called
   } else {
      return myAjaxCall();
   }
}

getUserData().then(userId => /* */);

Base on comment. Wrap into the Promise.resolve()

function add1(data) {
  return new Promise(function (resolve, reject) {
               resolve(data + 1);
         });
}

function add2(data) {
   return Promise.resolve(data + 2);
}

function printdata(data) {
   console.log(data);
}


问:
Convert len() to a string value within a string concatenation expression
How do I convert the len() value to be a string to successfully print the a string expression?

```<code>vacation = ['Rick', 'Paris', 'Tom', 'James']

print("I live with " + len(vacation) + " people")
</code>```

I got the error

```<code>Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
   print("I live with " + len(vacation) + " people")
TypeError: must be str, not int
</code>```

答:
For tasks like these, the use of formatting strings is
far more convenient that joining small pieces together with +

```<code>vacation = ['Rick', 'Paris', 'Tom', 'James']
print("I live with %d people" % len(vacation))
</code>```

Body:
How do I convert the len() value to be a string to successfully print the a string expression?

vacation = ['Rick', 'Paris', 'Tom', 'James']

print("I live with " + len(vacation) + " people")

I got the error

Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
   print("I live with " + len(vacation) + " people")
TypeError: must be str, not int

Body:
For tasks like these, the use of formatting strings is
far more convenient that joining small pieces together with +

vacation = ['Rick', 'Paris', 'Tom', 'James']
print("I live with %d people" % len(vacation))


问:
Write to a file Xcode MacOS
I'm unable to run this piece of code which writes the pid to a file.

```<code>NSString *text = [NSString stringWithFormat:@"%d\n", getpid()];
NSError *error = nil;

if (![text writeToFile:@"/tmp/Frontend.pid" atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"Cannot write PID file %@: %@", @"/tmp/Frontend.pid", error);
    return NO;
}
</code>```

This is the error I get.

2017-11-13 20:19:18.742171+0530 TestThread[7648:273326] Cannot write PID file /tmp/Frontend.pid: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Frontend.pid” in the folder “tmp”." UserInfo={NSFilePath=/tmp/Frontend.pid, NSUnderlyingError=0x6040000432a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I've changed the permission for the directory to 777 and it still doesn't have enough permissions. Please help.

答: Well, I finally fixed it. Here is the default configuration of a new project in xcode which ruined the whole file io thing. I turned off these 2 knobs in the entitlements file and was good to go.

Title: Write to a file Xcode MacOS

Body:
I'm unable to run this piece of code which writes the pid to a file.

NSString *text = [NSString stringWithFormat:@"%d\n", getpid()];
NSError *error = nil;

if (![text writeToFile:@"/tmp/Frontend.pid" atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"Cannot write PID file %@: %@", @"/tmp/Frontend.pid", error);
    return NO;
}

This is the error I get.

2017-11-13 20:19:18.742171+0530 TestThread[7648:273326] Cannot write PID file /tmp/Frontend.pid: Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “Frontend.pid” in the folder “tmp”." UserInfo={NSFilePath=/tmp/Frontend.pid, NSUnderlyingError=0x6040000432a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I've changed the permission for the directory to 777 and it still doesn't have enough permissions. Please help.


答:
You can do it like this:

```<code>print("I live with %s people" % len(vacation))
</code>```

or

```<code>print('I live with {} people'.format(len(vacation)))
</code>```

%s and {} are placeholders for the argument passed.

Title: Convert len() to a string value within a string concatenation expression

Body:
You can do it like this:

print("I live with %s people" % len(vacation))

or

print('I live with {} people'.format(len(vacation)))

%s and {} are placeholders for the argument passed.


问:
Intent couldnt be initialized even after multiple tries
I have created this small program but i cant seem to make it run. It gives an error saying that intent hasnt been initialized. What should i do?

```<code>Spinner mySpinner1 = (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter<String> myAdapter1 = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.which));
    myAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner1.setAdapter(myAdapter1);

    mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0,
                                   View view,
                                   int position,
                                   long id) {
           Intent intent = new Intent(MainActivity.this, intent.class);
            switch (position) {
                case 1:
                    intent = new Intent(MainActivity.this, MainActivity2.class);
                    break;
            }
            startActivity(intent);
        }
</code>```

EDIT 1 : Added few more lines of code to make the whole situation clearer

答:
```<code>Intent intent = new Intent(MainActivity.this, intent.class);
</code>```

You are passing wrong argument in 2nd. Please pass proper Activity class where you want to redirect your user.

```<code>           Intent intent; //Initialize it later as per your switch  case condition.
            switch (position) {
                case 1: //Initialize as per your condition
                    intent = new Intent(MainActivity.this, MainActivity2.class);
                    break;
            }
if(intent!=null) //Check here if its not null. Else it will crash your app.
            startActivity(intent);
</code>```

You can also do like this.

Body:
I have created this small program but i cant seem to make it run. It gives an error saying that intent hasnt been initialized. What should i do?

Spinner mySpinner1 = (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter<String> myAdapter1 = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.which));
    myAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner1.setAdapter(myAdapter1);

    mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0,
                                   View view,
                                   int position,
                                   long id) {
           Intent intent = new Intent(MainActivity.this, intent.class);
            switch (position) {
                case 1:
                    intent = new Intent(MainActivity.this, MainActivity2.class);
                    break;
            }
            startActivity(intent);
        }

EDIT 1 : Added few more lines of code to make the whole situation clearer

Body:
Intent intent = new Intent(MainActivity.this, intent.class);

You are passing wrong argument in 2nd. Please pass proper Activity class where you want to redirect your user.

           Intent intent; //Initialize it later as per your switch  case condition.
            switch (position) {
                case 1: //Initialize as per your condition
                    intent = new Intent(MainActivity.this, MainActivity2.class);
                    break;
            }
if(intent!=null) //Check here if its not null. Else it will crash your app.
            startActivity(intent);

You can also do like this.


问:
pointers in C++ (need overview)
```<code>int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
</code>```

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

答:
Answer 1: p1 still points to firstValue, but the value of firstValue is now changed to 10
Answer 2: in line 2, secondValue is assigned the value of firstValue.
Answer 3: line 3 is assigning the pointer of secondValue to the p1, so any changes in *p1 will reflect in the changed value of secondValue.

Hope this helps.

Title: pointers in C++ (need overview)

Body:
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.


问:
Angular 4 routes with submodules
I'm trying to use Core UI Angular seed.

here're my routing files:
app/app.routing.js

```<code>import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

// Import Containers
import {
    FullLayoutComponent,
    SimpleLayoutComponent
} from './containers';

export const routes:Routes = [
    {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full',
    },
    {
        path: '',
        component: FullLayoutComponent,
        data: {
            title: 'Home'
        },
        children: [
            {
                path: 'dashboard',
                loadChildren: './views/dashboard/dashboard.module#DashboardModule'
            },
            {
                path: 'clients',
                loadChildren: './views/clients/clients.module#ClientsModule'
            },
        ]
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {
}
</code>```

app/views/clients/clients.routing.ts

```<code>import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {ClientsComponent} from './clients.component';

const routes:Routes = [
    {
        path: '',
        component: ClientsComponent,
        data: {
            title: 'Clients'
        },
        children: [
            {
                path: 'organizations',
                loadChildren: './organizations/organizations.module#OrganizationsModule'
            },
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class ClientsRoutingModule {
}
</code>```

app\views\clients\organizations\organizations.routing.ts

```<code>import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {IndexComponent} from './index.component';
import {CreateComponent} from './create.component';

const routes:Routes = [
    {
        path: '',
        component: IndexComponent,
        data: {
            title: 'Organizations'
        },
        children: [
            {
                path: 'create',
                component: CreateComponent,
                data: {
                    title: 'Add organization'
                }
            }
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class OrganizationsRoutingModule {
}
</code>```

So, while navigating:

http://localhost:4200/#/dashboard - and renders dashboard
http://localhost:4200/#/clients/organizations - renders clients IndexComponent

but

http://localhost:4200/#/clients/organizations - also renders clients IndexComponent
http://localhost:4200/#/clients/organizations/create - also renders clients IndexComponent

Breadcrumbs render in correct way.

ClientsModule

```<code>import {NgModule} from '@angular/core';

import {ClientsComponent} from './clients.component';
import {ClientsRoutingModule} from './clients.routing';

@NgModule({
    imports: [
        ClientsRoutingModule,
    ],
    declarations: [
        ClientsComponent,
    ]
})
export class ClientsModule {
}
</code>```

OrganizationsModule

```<code>import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';

import {OrganizationsRoutingModule} from './organizations.routing';

import {ListComponent} from './components/list.component';

import {IndexComponent} from './index.component';
import {ViewComponent} from './view.component';
import {CreateComponent} from './create.component';

@NgModule({
    imports: [
        CommonModule,
        OrganizationsRoutingModule,
    ],
    declarations: [
        ListComponent,
        IndexComponent,
        CreateComponent,
        ViewComponent
    ]
})
export class OrganizationsModule {
}
</code>```

答:
Here're routes worked good to me:

clients:

```<code>import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {ClientsComponent} from './clients.component';

const routes:Routes = [
    {path: '', component: ClientsComponent, data: {title: 'Clients'}},
    {
        path: '',
        data: {
            title: 'Clients'
        },
        children: [
            {
                path: 'organizations',
                loadChildren: './organizations/organizations.module#OrganizationsModule'
            },
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class ClientsRoutingModule {
}
</code>```

organizations

```<code>import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {IndexComponent} from './index.component';
import {CreateComponent} from './create.component';

const routes:Routes = [
    { path: '', component: IndexComponent, data: { title: 'Organizations list' }},
    {
        path: '',
        data: {
            title: 'Organizations'
        },
        children: [
            { path: 'create', component: CreateComponent, data: { title: 'Add organization' }},
            //{ path: ':id', component: ViewComponent } //if you want to show detail view by id
        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class OrganizationsRoutingModule {
}
</code>```

Title: Angular 4 routes with submodules

Body:
I'm trying to use Core UI Angular seed.

here're my routing files:
app/app.routing.js

import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

// Import Containers
import {
    FullLayoutComponent,
    SimpleLayoutComponent
} from './containers';

export const routes:Routes = [
    {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full',
    },
    {
        path: '',
        component: FullLayoutComponent,
        data: {
            title: 'Home'
        },
        children: [
            {
                path: 'dashboard',
                loadChildren: './views/dashboard/dashboard.module#DashboardModule'
            },
            {
                path: 'clients',
                loadChildren: './views/clients/clients.module#ClientsModule'
            },
        ]
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {
}

app/views/clients/clients.routing.ts

import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {ClientsComponent} from './clients.component';

const routes:Routes = [
    {
        path: '',
        component: ClientsComponent,
        data: {
            title: 'Clients'
        },
        children: [
            {
                path: 'organizations',
                loadChildren: './organizations/organizations.module#OrganizationsModule'
            },
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class ClientsRoutingModule {
}

app\views\clients\organizations\organizations.routing.ts

import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {IndexComponent} from './index.component';
import {CreateComponent} from './create.component';

const routes:Routes = [
    {
        path: '',
        component: IndexComponent,
        data: {
            title: 'Organizations'
        },
        children: [
            {
                path: 'create',
                component: CreateComponent,
                data: {
                    title: 'Add organization'
                }
            }
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class OrganizationsRoutingModule {
}

So, while navigating:

http://localhost:4200/#/dashboard - and renders dashboard
http://localhost:4200/#/clients/organizations - renders clients IndexComponent

but

http://localhost:4200/#/clients/organizations - also renders clients IndexComponent
http://localhost:4200/#/clients/organizations/create - also renders clients IndexComponent

Breadcrumbs render in correct way.

ClientsModule

import {NgModule} from '@angular/core';

import {ClientsComponent} from './clients.component';
import {ClientsRoutingModule} from './clients.routing';

@NgModule({
    imports: [
        ClientsRoutingModule,
    ],
    declarations: [
        ClientsComponent,
    ]
})
export class ClientsModule {
}

OrganizationsModule

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';

import {OrganizationsRoutingModule} from './organizations.routing';

import {ListComponent} from './components/list.component';

import {IndexComponent} from './index.component';
import {ViewComponent} from './view.component';
import {CreateComponent} from './create.component';

@NgModule({
    imports: [
        CommonModule,
        OrganizationsRoutingModule,
    ],
    declarations: [
        ListComponent,
        IndexComponent,
        CreateComponent,
        ViewComponent
    ]
})
export class OrganizationsModule {
}

Body:
Here're routes worked good to me:

clients:

import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {ClientsComponent} from './clients.component';

const routes:Routes = [
    {path: '', component: ClientsComponent, data: {title: 'Clients'}},
    {
        path: '',
        data: {
            title: 'Clients'
        },
        children: [
            {
                path: 'organizations',
                loadChildren: './organizations/organizations.module#OrganizationsModule'
            },
        ]
    },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class ClientsRoutingModule {
}

organizations

import {NgModule} from '@angular/core';
import {
    Routes,
    RouterModule
} from '@angular/router';

import {IndexComponent} from './index.component';
import {CreateComponent} from './create.component';

const routes:Routes = [
    { path: '', component: IndexComponent, data: { title: 'Organizations list' }},
    {
        path: '',
        data: {
            title: 'Organizations'
        },
        children: [
            { path: 'create', component: CreateComponent, data: { title: 'Add organization' }},
            //{ path: ':id', component: ViewComponent } //if you want to show detail view by id
        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class OrganizationsRoutingModule {
}


答:
use str function to convert int to string:</p>

```<code>print("I live with " + str(len(vacation)) + " people")
</code>```

Body:
use str function to convert int to string:

print("I live with " + str(len(vacation)) + " people")


问:
SqlDependency doesn't fire on row insertion (or update, or delete)
After bashing my head against a wall for the next few hours I've slowly started to realise where my problem lays, so let me give you a recap: I'm trying to change a website's string when a row gets inserted into a database, but for some reason the trigger I've made that tells me when there's been a change into the database doesn't fire at all when an insertion, udpate or whatever happens. The table's Service Broker is on.

This is the involved code:

```<code>namespace WebApplication.SignalR_Data
{
    public class NotificationRepository
    {
        public NotificationInfo GetData()
        {
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReservationDbContext"].ConnectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(@"SELECT COUNT(*) FROM dbo.Reservations", connection))
                {
                    command.Notification = null;

                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == System.Data.ConnectionState.Closed)
                        connection.Open();

                    return new NotificationInfo { RowCount = (int)command.ExecuteScalar(), Date = DateTime.Now };

                }
            }
        }

// This is the method that handles the trigger.
        public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                NotificationHub.Show();
            }
        }
    }
}
</code>```

I suppose that it's not working because of mistakes I've made, but sadly I haven't been able to spot them yet.

Through NotificationHub.Show(); a message is broadcasted to all clients of the website with the updated rowcount and date, but that message is never sent because the trigger doesn't fire. Any ideas?

Thank you in advance!

答:
You need to register method GetData() again for continue receive event.
Like this:</p>

```<code>public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                NotificationHub.Show();
            }
            GetData();
        }
</code>```

Body:
After bashing my head against a wall for the next few hours I've slowly started to realise where my problem lays, so let me give you a recap: I'm trying to change a website's string when a row gets inserted into a database, but for some reason the trigger I've made that tells me when there's been a change into the database doesn't fire at all when an insertion, udpate or whatever happens. The table's Service Broker is on.

This is the involved code:

namespace WebApplication.SignalR_Data
{
    public class NotificationRepository
    {
        public NotificationInfo GetData()
        {
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReservationDbContext"].ConnectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand(@"SELECT COUNT(*) FROM dbo.Reservations", connection))
                {
                    command.Notification = null;

                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    if (connection.State == System.Data.ConnectionState.Closed)
                        connection.Open();

                    return new NotificationInfo { RowCount = (int)command.ExecuteScalar(), Date = DateTime.Now };

                }
            }
        }

// This is the method that handles the trigger.
        public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                NotificationHub.Show();
            }
        }
    }
}

I suppose that it's not working because of mistakes I've made, but sadly I haven't been able to spot them yet.

Through NotificationHub.Show(); a message is broadcasted to all clients of the website with the updated rowcount and date, but that message is never sent because the trigger doesn't fire. Any ideas?

Thank you in advance!

Body:
You need to register method GetData() again for continue receive event.
Like this:

public void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            if (e.Type == SqlNotificationType.Change)
            {
                NotificationHub.Show();
            }
            GetData();
        }


问:
How to convert date to unix format
How to convert below date to unix format using python ?

I have checked for date month and year format but it is not working

Date: "10 Nov 2017"

Please help.

答:
As per the doc

You can use %b for Locale’s abbreviated month name.

Try this:

```<code>import time
import datetime
s = "10 Nov 2017"
time.mktime(datetime.datetime.strptime(s, "%d %b %Y").timetuple())
</code>```

Title: How to convert date to unix format

Body:
As per the doc

You can use %b for Locale’s abbreviated month name.

Try this:

import time
import datetime
s = "10 Nov 2017"
time.mktime(datetime.datetime.strptime(s, "%d %b %Y").timetuple())


问:
How to make enum accessible from other classes in XNA when enum is defined in main game class?
So I have my main game class and have created an enum for game state.
How do I make this enum accessible to other classes? I know you have to make it public but I cant seem to make it accessible to other classes.
What I'm trying to do is have a bunch of different classes to be able to check the current game state via enum and do different things depending on the current game state.</p>

答:
depending on what namespace it's in, you might have to place the following line (or one similar) at the top of any .cs file that you want to have access to it:

```<code>using MyGame.ThisIsMyNameSpace;
</code>```

That exposes the enum so that you can reference it without having to fully qualify it

or, if what you mean is that you need a way to access the current game's state, then you need to have a reference to something. One thing that many people do is make a public property on the Game class, and then pass around a reference to that instance. Other people just make a singleton or static class to hold that globally available space. It all depends on your code style and the size of your game

ContentLicense: CC BY-SA 2.5

Body:
depending on what namespace it's in, you might have to place the following line (or one similar) at the top of any .cs file that you want to have access to it:

using MyGame.ThisIsMyNameSpace;

That exposes the enum so that you can reference it without having to fully qualify it

or, if what you mean is that you need a way to access the current game's state, then you need to have a reference to something. One thing that many people do is make a public property on the Game class, and then pass around a reference to that instance. Other people just make a singleton or static class to hold that globally available space. It all depends on your code style and the size of your game


问:
Pyspark udf high memory utilization
I'm using a UDF written in python in order to change the base of a number.

So I read a parquet file and write to a parquet file and applying the UDF.
Here is the line I run:

```<code>input_df.withColumn("origin_base", convert_2_dest_base(input_df.origin_base)).write.mode('overwrite').parquet(destination_path)
</code>```

This conversion makes spark to utilize a lot of memory and I get this kind of warnings:

17/06/18 08:05:39 WARN TaskSetManager: Lost task 40.0 in stage 4.0 (TID 183, ip-10-100-5-196.ec2.internal, executor 19): ExecutorLostFailure (executor 19 exited caused by one of the running tasks) Reason: Container killed by YARN for exceeding memory limits. 4.4 GB of 4.4 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.

and in the end it fails.

Does UDF is not the right approach? Why is it consuming so much memory?

答:
For pyspark, data is processed in Python and cached / shuffled in the JVM. If you are using built in Python API, there would not be much difference in terms of performance to scala. See python vs scala performance

When you use udf, since your local defined function does not registered in native JVM structure and so can't be implemented by simple java API call, it has to be serialize/deserialize to Python worker. Then data will be processed in Python worker and serialize/deserialize back to JVM.

The Python worker now need to process the serialized data in the off-heap memory, it consumes huge off-heap memory and so it often leads to memoryOverhead.

Performance wise, serialization is slow and it is often the key for performance tuning.

Title: Pyspark udf high memory utilization

Body:
I'm using a UDF written in python in order to change the base of a number.

So I read a parquet file and write to a parquet file and applying the UDF.
Here is the line I run:

input_df.withColumn("origin_base", convert_2_dest_base(input_df.origin_base)).write.mode('overwrite').parquet(destination_path)

This conversion makes spark to utilize a lot of memory and I get this kind of warnings:

17/06/18 08:05:39 WARN TaskSetManager: Lost task 40.0 in stage 4.0 (TID 183, ip-10-100-5-196.ec2.internal, executor 19): ExecutorLostFailure (executor 19 exited caused by one of the running tasks) Reason: Container killed by YARN for exceeding memory limits. 4.4 GB of 4.4 GB physical memory used. Consider boosting spark.yarn.executor.memoryOverhead.

and in the end it fails.

Does UDF is not the right approach? Why is it consuming so much memory?


问:
how to set soap header using php for my xml content
```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xxxxx="xxxxx" xmlns:tem="http://tempuri.org/">
   <soapenv:Header>
      <Auth>
         <!--Optional:-->
         <xxxxx:id></xxxxx:id>
         <!--Optional:-->
         <xxxxx:Login></xxxxx:Login>
         <!--Optional:-->
         <xxxxx:pass></xxxxx:pass>
      </Auth>
   </soapenv:Header>
   <soapenv:Body>
      <tem:test>
         <!--Optional:-->
         <tem:test>test</tem:test>
      </tem:test>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

php

```<code><?php

try {
    $client = new SoapClient(self::$url, array());
    $header = new SoapHeader("xxxxx", "Auth", $header_data, false);

    $client->__setSoapHeaders([$header]);

    $result = $client->ProcessarIntegracao($header, $test);
}
catch (Exception $e) {
    return 'soap error: ' . $e->getMessage();
}
</code>```

I tried lots of methods to send request, but it always return

soap header not found

答:
```<code>okay I fixed this thaks for your help, here is my code

<?php
error_reporting(-1);
ini_set('error_reporting', E_ALL);
ini_set("soap.wsdl_cache_enabled", "0");
ini_set('display_errors', 1);

class XSoapClient extends SoapClient
{
    public function __doRequest($request, $location, $action, $version, $one_way = null)
    {
        $request = preg_replace('/ns2:xxxxx/','xxxxx',$request, -1);
        return parent::__doRequest($request, $location, $action, $version, $one_way);
    }
}

//phpinfo();die();
$url = 'xxxxx';
$data = array(
               'test' => 'test'
            );

    $client = new XSoapClient($url, array(
     "trace" => 1,
     "classmap" => array(
          'xxxxx' => 'xxxxx'
     )
    ));

    $ns = "xxxxx";

$auth = "<your header xml><ns2:id>xx</ns2:id><xxx:Login>xxxx</xxx:Login><xxx:pass>xxx</xxx:pass></your header xml>";
$auth_block = new SoapVar( $auth, XSD_ANYXML, NULL, NULL, NULL, NULL );

class ServiceHeader{}
$serviceHeader = new ServiceHeader();
$serviceHeader->id = xxx;
$serviceHeader->Login = "xxxx";
$serviceHeader->pass = "xxxx";

$header = new SoapHeader($ns, "xxxx", $serviceHeader);
//$header = new SoapHeader( $ns, 'Header', $auth_block );
    $client->__setSoapHeaders($header);
try{
    $result =  $client->ProcessarIntegracao($data);
} catch (exception $ex){

echo "```";

print_r($client);
//echo "```";
print_r($header);
print_r($client->__getLastRequest());

echo "```";

}
</code>```

Body:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xxxxx="xxxxx" xmlns:tem="http://tempuri.org/">
   <soapenv:Header>
      <Auth>

         <xxxxx:id></xxxxx:id>

         <xxxxx:Login></xxxxx:Login>

         <xxxxx:pass></xxxxx:pass>
      </Auth>
   </soapenv:Header>
   <soapenv:Body>
      <tem:test>

         <tem:test>test</tem:test>
      </tem:test>
   </soapenv:Body>
</soapenv:Envelope>

php

<?php

try {
    $client = new SoapClient(self::$url, array());
    $header = new SoapHeader("xxxxx", "Auth", $header_data, false);

    $client->__setSoapHeaders([$header]);

    $result = $client->ProcessarIntegracao($header, $test);
}
catch (Exception $e) {
    return 'soap error: ' . $e->getMessage();
}

I tried lots of methods to send request, but it always return

soap header not found

Body:
okay I fixed this thaks for your help, here is my code

<?php
error_reporting(-1);
ini_set('error_reporting', E_ALL);
ini_set("soap.wsdl_cache_enabled", "0");
ini_set('display_errors', 1);

class XSoapClient extends SoapClient
{
    public function __doRequest($request, $location, $action, $version, $one_way = null)
    {
        $request = preg_replace('/ns2:xxxxx/','xxxxx',$request, -1);
        return parent::__doRequest($request, $location, $action, $version, $one_way);
    }
}

//phpinfo();die();
$url = 'xxxxx';
$data = array(
               'test' => 'test'
            );

    $client = new XSoapClient($url, array(
     "trace" => 1,
     "classmap" => array(
          'xxxxx' => 'xxxxx'
     )
    ));

    $ns = "xxxxx";

$auth = "<your header xml><ns2:id>xx</ns2:id><xxx:Login>xxxx</xxx:Login><xxx:pass>xxx</xxx:pass></your header xml>";
$auth_block = new SoapVar( $auth, XSD_ANYXML, NULL, NULL, NULL, NULL );

class ServiceHeader{}
$serviceHeader = new ServiceHeader();
$serviceHeader->id = xxx;
$serviceHeader->Login = "xxxx";
$serviceHeader->pass = "xxxx";

$header = new SoapHeader($ns, "xxxx", $serviceHeader);
//$header = new SoapHeader( $ns, 'Header', $auth_block );
    $client->__setSoapHeaders($header);
try{
    $result =  $client->ProcessarIntegracao($data);
} catch (exception $ex){

echo "<pre>";

print_r($client);
//echo "</pre>";
print_r($header);
print_r($client->__getLastRequest());

echo "</pre>";

}


问:
Non-resolvable parent POM in new Spring Starter Project using corporate proxy
I just started using STS and the previous answers I have looked through does not have an answer to my question.

```<code>Project build error: Non-resolvable parent POM for learn.fullstack.ngspring:demo:0.0.1-SNAPSHOT:
Failure to transfer org.springframework.boot:spring-boot-starter-parent:pom:1.5.8.RELEASE from
https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be
reattempted until the update interval of central has elapsed or updates are forced. Original error: Could
not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:1.5.8.RELEASE from/to
central (https://repo.maven.apache.org/maven2): sun.security.validator.ValidatorException: PKIX path
building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid
certification path to requested target and 'parent.relativePath' points at no local POM
</code>```

1) I configured proxy settings under Preferences -> Network Connections, which allows me to create a Spring Starter Project

2) I am unable to run any mvn commands

3) I created a settings.xml with my own corporate credentials:

```<code><?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
     <proxies>
       <proxy>
          <active>true</active>
          <protocol>http</protocol>
          <host>XXXXXX</host>
          <port>XX</port>
          <username>XXXXXXX</username>
          <password>XXXXXXX</password>
        </proxy>
      </proxies>
    </settings>
</code>```

Unable to work after doing these two steps. My questions are:

1) Do I need to make any changes to the pom.xml file?

2) Where can I find 'local POM' or direct STS to point to the local POM?

答:
Select window option in Eclipse and go to preferences and then go to Maven and there update .setting file and change proxy username or password as of ur system.
Then Go to Project ,right click and then Select Maven and update Project</p>

Body:
I just started using STS and the previous answers I have looked through does not have an answer to my question.

Project build error: Non-resolvable parent POM for learn.fullstack.ngspring:demo:0.0.1-SNAPSHOT:
Failure to transfer org.springframework.boot:spring-boot-starter-parent:pom:1.5.8.RELEASE from
https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be
reattempted until the update interval of central has elapsed or updates are forced. Original error: Could
not transfer artifact org.springframework.boot:spring-boot-starter-parent:pom:1.5.8.RELEASE from/to
central (https://repo.maven.apache.org/maven2): sun.security.validator.ValidatorException: PKIX path
building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid
certification path to requested target and 'parent.relativePath' points at no local POM

1) I configured proxy settings under Preferences -> Network Connections, which allows me to create a Spring Starter Project

2) I am unable to run any mvn commands

3) I created a settings.xml with my own corporate credentials:

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
     <proxies>
       <proxy>
          <active>true</active>
          <protocol>http</protocol>
          <host>XXXXXX</host>
          <port>XX</port>
          <username>XXXXXXX</username>
          <password>XXXXXXX</password>
        </proxy>
      </proxies>
    </settings>

Unable to work after doing these two steps. My questions are:

1) Do I need to make any changes to the pom.xml file?

2) Where can I find 'local POM' or direct STS to point to the local POM?


问:
Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?
Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

If not, what is the alternative in MS SQL Server?

答: I use TINYINT(1)datatype in order to store boolean values in SQL Server though BIT is very effective

ContentLicense: CC BY-SA 4.0


答:
```<code>  mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0,
                                   View view,
                                   int position,
                                   long id) {
            switch (position) {
                case 1:
                  Intent intent = new Intent(MainActivity.this,MainActivity2.class);
                  startActivity(intent);
                  break;
            }
        }
</code>```

Title: Intent couldnt be initialized even after multiple tries


问:
In .NET, when do I have to reference a DLL that an external library also references?
I'm trying to understand when it's necessary for my .NET project to reference a DLL that an external library references.

A practical example: Microsoft.Bot.Builder depends on Chronic.Signed.dll

If I reference Microsoft.Bot.Builder.dll, do I always have to also add a reference to Chronic.Signed.dll in my own project, even if I'm not using it directly? Or do I only have to only under certain circumstances?

答:
Unless you're referencing specific things from those packages, you shouldn't need to. If you're missing a dependency which would cause your code to be unable to compile or run, the compiler will most likely complain about it.

Just as a simple example of when multiple DLLs need to be installed, when you're installing packages through NuGet, sometimes packages will have dependencies that will install in order to be able to run the code in the package. However, most of them will install independently of any other packages. You can test the how this works across projects by putting some references in a library project that don't exist in another project, and then trying to run the code from the main project. You shouldn't need to reference the same DLLs as the library project.


问:
C++: Undefined function error when I have defined the function
I am trying to implement a linkedlist in C++. I defined the linkedlist and node classes and the methods for the linkedlist class in the same file. Here is my linkedlist class:

```<code>template <class T>
class  LinkedList{
    public:
        Node<T> *head;
        int size;

        LinkedList();
        void push(T data);
        T pop();
        T remove(T *target, int (*compfunc)(T *, T *));
        void clear();
        int getSize();
        void printList();
};
</code>```

I define the push method:

```<code>template <class T>
void LinkedList<T>::push(T data){
    Node<T> *n = new Node<T>;
    n -> data = data;
    n->next = this->head;
    this->head = n;
    this->size++;
}
</code>```

But when I try to run the main method, I get an error saying that LinkedList::push(T data) is undefined.

Main function:

```<code>int main(){
    LinkedList<int> list;

    for (int i = 0; i < 5; ++i)
    {
        list.push(i);
    }

    list.printList();

    return 0;
}
</code>```

All other methods except push seem to work fine. The error I get is:

Undefined symbols for architecture x86_64:
    "operator new(unsigned long)", referenced from:
        LinkedList::push(int) in linkedList-1c3a85.o
  ld: symbol(s) not found for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)`

答:
This is a case of "read the error message."  Almost every C++ compiler with which I have interacted is very, very verbose.  Lots of text.  But all of the information is there.

Perhaps if we break down your error message, the problem may become more plain:

```<code>Undefined symbols for architecture x86_64: "operator new(unsigned long)",
  referenced from: LinkedList::push(int)

in linkedList-1c3a85.o ld:
  symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation)`
</code>```

The core problem is an 'undefined symbol'.  What symbol?  The operator new(unsigned long).  Wait ... where is that used?  Inside of LinkedList::push(int).

Okay, looking inside of LinkedList::push(int), there's Node<T> *n = new Node<T>;.  So, the compiler does not like that line, and apparently cannot autogenerate a constructor function for you.

To wit, the issue is not that LinkedList::push(int) is not defined -- it very clearly is.  It's that the definition of how to create a new Node is missing.

Body:
I am trying to implement a linkedlist in C++. I defined the linkedlist and node classes and the methods for the linkedlist class in the same file. Here is my linkedlist class:

template <class T>
class  LinkedList{
    public:
        Node<T> *head;
        int size;

        LinkedList();
        void push(T data);
        T pop();
        T remove(T *target, int (*compfunc)(T *, T *));
        void clear();
        int getSize();
        void printList();
};

I define the push method:

template <class T>
void LinkedList<T>::push(T data){
    Node<T> *n = new Node<T>;
    n -> data = data;
    n->next = this->head;
    this->head = n;
    this->size++;
}

But when I try to run the main method, I get an error saying that LinkedList::push(T data) is undefined.

Main function:

int main(){
    LinkedList<int> list;

    for (int i = 0; i < 5; ++i)
    {
        list.push(i);
    }

    list.printList();

    return 0;
}

All other methods except push seem to work fine. The error I get is:

Undefined symbols for architecture x86_64:
    "operator new(unsigned long)", referenced from:
        LinkedList::push(int) in linkedList-1c3a85.o
  ld: symbol(s) not found for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)`

Body:
This is a case of "read the error message."  Almost every C++ compiler with which I have interacted is very, very verbose.  Lots of text.  But all of the information is there.

Perhaps if we break down your error message, the problem may become more plain:

Undefined symbols for architecture x86_64: "operator new(unsigned long)",
  referenced from: LinkedList::push(int)

in linkedList-1c3a85.o ld:
  symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation)`

The core problem is an 'undefined symbol'.  What symbol?  The operator new(unsigned long).  Wait ... where is that used?  Inside of LinkedList::push(int).

Okay, looking inside of LinkedList::push(int), there's Node<T> *n = new Node<T>;.  So, the compiler does not like that line, and apparently cannot autogenerate a constructor function for you.

To wit, the issue is not that LinkedList::push(int) is not defined -- it very clearly is.  It's that the definition of how to create a new Node is missing.


问:
Slow CSV row parsing and splitting
I'm trying to parse a csv of over 100,000 lines and the performance problems don't even let me get to the end of the file before hitting "Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded"

Is there something wrong, or any way I can improve?

```<code>public static List<String[]> readCSV(String filePath) throws IOException{
    List<String[]> csvLine= new ArrayList<String[]>();
    CSVReader reader = new CSVReader(new FileReader(filePath), '\n');
    String[] row;

    while((row = reader.readNext()) != null){
        csvLine.add(removeWhiteSpace(row[0].toString().split(",")));
    }

    reader.close();
    return csvLine;
}

private static String[] removeWhiteSpace(String[] split) {
    for(int index =0; index < split.length;index++){
        split[index] = split[index].trim();
    }
    return split;
}
</code>```

答:
First you are running out of memory because all rows are being added to a list.

Second you are using String.split() which is extremely slow.

Third never try processing CSV by writing your own parsing code as there are many edge cases around this format (need to handle escape of delimiter, quotes, etc).

The solution is to use a library for that, such as univocity-parsers. You should be able to read 1 million rows in less than a second.

To parse, just do this:

```<code>public static IterableResult<String[], ParsingContext> readCSV(String filePath) {
    File file = new File(filePath);

    //configure the parser here. By default all values are trimmed
    CsvParserSettings parserSettings = new CsvParserSettings();

    //create the parser
    CsvParser parser = new CsvParser(parserSettings);

    //create an iterable over rows. This will not load everything into memory.
    IterableResult<String[], ParsingContext> rows = parser.iterate(file);

    return rows;
}
</code>```

Now you can use your method like this:

```<code>public static void main(String... args) {
    IterableResult<String[], ParsingContext> rows = readCSV("c:/path/to/input.csv");

    try {
        for (String[] row : rows) {
            //process the rows however you want
        }
    } finally {
        //the parser closes itself but in case any errors processing the rows (outside of the control of the iterator), close the parser.
        rows.getContext().stop();
    }
}
</code>```

This is just an example of how you can use the parser, but there are many different ways to use it.

Now for writing, you can do this:

```<code>public static void main(String... args) {
    //this is your output file
    File output = new File("c:/path/to/output.csv");

    //configure the writer if you need to
    CsvWriterSettings settings = new CsvWriterSettings();

    //create the writer. Here we write to a file
    CsvWriter writer = new CsvWriter(output, settings);

    //get the row iterator
    IterableResult<String[], ParsingContext> rows = readCSV("c:/temp");

    try {
        //do whatever you need to the rows here
        for (String[] row : rows) {
            //then write it each one to the output.
            writer.writeRow(row);
        }
    } finally {
        //cleanup
        rows.getContext().stop();
        writer.close();
    }
}
</code>```

If all you want is to read the data, modify it and write it back to another file, you can just do this:

```<code>public static void main(String... args) throws IOException {
    CsvParserSettings parserSettings = new CsvParserSettings();
    parserSettings.setProcessor(new AbstractRowProcessor() {
        @Override
        public void rowProcessed(String[] row, ParsingContext context) {
            //modify the row data here.
        }
    });

    CsvWriterSettings writerSettings = new CsvWriterSettings();
    CsvRoutines routines = new CsvRoutines(parserSettings, writerSettings);

    FileReader input = new FileReader("c:/path/to/input.csv");
    FileWriter output = new FileWriter("c:/path/to/output.csv");

    routines.parseAndWrite(input, output);
}
</code>```

Hope this helps.

Disclaimer: I'm the author of this libary. It's open source and free (Apache 2.0 license).

Title: Slow CSV row parsing and splitting

Body:
I'm trying to parse a csv of over 100,000 lines and the performance problems don't even let me get to the end of the file before hitting "Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded"

Is there something wrong, or any way I can improve?

public static List<String[]> readCSV(String filePath) throws IOException{
    List<String[]> csvLine= new ArrayList<String[]>();
    CSVReader reader = new CSVReader(new FileReader(filePath), '\n');
    String[] row;

    while((row = reader.readNext()) != null){
        csvLine.add(removeWhiteSpace(row[0].toString().split(",")));
    }

    reader.close();
    return csvLine;
}

private static String[] removeWhiteSpace(String[] split) {
    for(int index =0; index < split.length;index++){
        split[index] = split[index].trim();
    }
    return split;
}

Body:
First you are running out of memory because all rows are being added to a list.

Second you are using String.split() which is extremely slow.

Third never try processing CSV by writing your own parsing code as there are many edge cases around this format (need to handle escape of delimiter, quotes, etc).

The solution is to use a library for that, such as univocity-parsers. You should be able to read 1 million rows in less than a second.

To parse, just do this:

public static IterableResult<String[], ParsingContext> readCSV(String filePath) {
    File file = new File(filePath);

    //configure the parser here. By default all values are trimmed
    CsvParserSettings parserSettings = new CsvParserSettings();

    //create the parser
    CsvParser parser = new CsvParser(parserSettings);

    //create an iterable over rows. This will not load everything into memory.
    IterableResult<String[], ParsingContext> rows = parser.iterate(file);

    return rows;
}

Now you can use your method like this:

public static void main(String... args) {
    IterableResult<String[], ParsingContext> rows = readCSV("c:/path/to/input.csv");

    try {
        for (String[] row : rows) {
            //process the rows however you want
        }
    } finally {
        //the parser closes itself but in case any errors processing the rows (outside of the control of the iterator), close the parser.
        rows.getContext().stop();
    }
}

This is just an example of how you can use the parser, but there are many different ways to use it.

Now for writing, you can do this:

public static void main(String... args) {
    //this is your output file
    File output = new File("c:/path/to/output.csv");

    //configure the writer if you need to
    CsvWriterSettings settings = new CsvWriterSettings();

    //create the writer. Here we write to a file
    CsvWriter writer = new CsvWriter(output, settings);

    //get the row iterator
    IterableResult<String[], ParsingContext> rows = readCSV("c:/temp");

    try {
        //do whatever you need to the rows here
        for (String[] row : rows) {
            //then write it each one to the output.
            writer.writeRow(row);
        }
    } finally {
        //cleanup
        rows.getContext().stop();
        writer.close();
    }
}

If all you want is to read the data, modify it and write it back to another file, you can just do this:

public static void main(String... args) throws IOException {
    CsvParserSettings parserSettings = new CsvParserSettings();
    parserSettings.setProcessor(new AbstractRowProcessor() {
        @Override
        public void rowProcessed(String[] row, ParsingContext context) {
            //modify the row data here.
        }
    });

    CsvWriterSettings writerSettings = new CsvWriterSettings();
    CsvRoutines routines = new CsvRoutines(parserSettings, writerSettings);

    FileReader input = new FileReader("c:/path/to/input.csv");
    FileWriter output = new FileWriter("c:/path/to/output.csv");

    routines.parseAndWrite(input, output);
}

Hope this helps.

Disclaimer: I'm the author of this libary. It's open source and free (Apache 2.0 license).


答:
Use str function.

vacation = ['Rick', 'Paris', 'Tom', 'James']

print("I live with " + str(len(vacation)) + " people")

Body:
How do I convert the len() value to be a string to successfully print the a string expression?

vacation = ['Rick', 'Paris', 'Tom', 'James']

print("I live with " + len(vacation) + " people")

I got the error

Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
   print("I live with " + len(vacation) + " people")
TypeError: must be str, not int


问:
Avoid DIV inside SPAN - Best Practice
DIV is a block level element and must not be nested within a SPAN. But many themes hijack this best practice. What CSS, should be applied in order to bypass these errors?</p>

```<code><span class="fields col-lg-6">
    <div class="field">
        <label>Otp<span style="color: red;"> *</span></label>
        @Html.TextDoxFor(m => m.Otp)
    </div>
</span>
</code>```

答:
There is no CSS to bypass the error caused by the HTML construction. You have to do it manually in the code.

But in your case it's optional, it's up to you what you want.

1# If you want to avoid the block style of the
 you can use this CSS:

```<code>span>div{display:inline;}
</code>```

or to apply to all child's inside the span

```<code>span div{display:inline;}
</code>```

2# If you want to avoid the inline style of the  you can use this CSS:

```<code>span.fields{display:block;}
</code>```

or to nest, all the child's properly

```<code>span.fields{display:inline-block;}
</code>```

Hope this was helpful for you.

Title: Avoid DIV inside SPAN - Best Practice

Body:
DIV is a block level element and must not be nested within a SPAN. But many themes hijack this best practice. What CSS, should be applied in order to bypass these errors?

        Otp *
        @Html.TextDoxFor(m => m.Otp)

Body:
There is no CSS to bypass the error caused by the HTML construction. You have to do it manually in the code.

But in your case it's optional, it's up to you what you want.

1# If you want to avoid the block style of the <div> you can use this CSS:

span>div{display:inline;}

or to apply to all child's inside the span

span div{display:inline;}

2# If you want to avoid the inline style of the <span> you can use this CSS:

span.fields{display:block;}

or to nest, all the child's properly

span.fields{display:inline-block;}

Hope this was helpful for you.


问:
SVN pre-commit hook to restrict file extensions from getting commited
Using the following code in the Collabnet SVN's pre commit script to restrict the specific file extensions to get committed, but it is committing all the files. Could you please tell where I'm going wrong.</p>

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

REPOS="$1"
TXN="$2"

SVNLOOK=/home/csvn/csvn/bin/svnlook

LOGMSG=`$SVNLOOK log -t "$TXN" "$REPOS" | grep "[a-zA-Z0-9]" | wc -c`

if [ "$LOGMSG" -lt 10 ];
then
  echo -e "\n===========================================================" 1>&2
  echo -e "|| COMMENTS ARE MADE MANDATORY.PLEASE ENTER RELEVANT COMMENT & COMMIT AGAIN Sanjeev sas||" 1>&2
  echo -e "===========================================================" 1>&2
  exit 1
fi

$SVNLOOK changed -t $TXN $REPOS | awk '
BEGIN {
FILTER=".(sh|xls|xlsx|pdf|jpg|JPG|gif|GIF|png|PNG|doc|DOC|docx|DOCX|mpg|swf|avi|mp3|mp4|zip|rar|gz|csv|o|obj|tar|gz|JPEG|jpeg|WMV|wmv|DAT|dat|3GP|3gp|MPEG|mpeg|VOD|vod|ear|jar|war|exe|ppt|PPT|PPTX|pptx|7z|iso|ISO|EAR|WAR|JAR|msg|MSG|rtf|RTF|xlsm|XLSM|vsd|VSD|dot|DOT|camrec|ECF|ecf|mff|MFF|class|CLASS)$"
}
{
 for (i = 1; i < 2; i++) $i = ""; sub(/^ */, "");
 if(match(tolower($1),FILTER))
 {
     print "File" $1 "is not allowed file type to commit"
     exit 1
 }
}'

exit 0
</code>```

答:
Solution for Windows pre-commit.bat</p>

```<code>@ECHO OFF

set REPOS=%1
set TXN=%2
set SVNLOOK="path\to\svnlook.exe"

set FORMATS=*.ext1, *.ext2, *.ext3
:CHECK1
%SVNLOOK% changed -t %TXN% %REPOS% | findstr /R /I ".ext1$"
if %ERRORLEVEL% EQU 1 goto CHECK2
echo Your commit has been blocked because you are trying to commit a restricted file. Restricted formats %FORMATS% >&2
exit /b 1

:CHECK2
%SVNLOOK% changed -t %TXN% %REPOS% | findstr /R /I ".ext2$"
if %ERRORLEVEL% EQU 1 goto CHECK3
echo Your commit has been blocked because you are trying to commit a restricted file. Restricted formats %FORMATS% >&2
exit /b 1

:CHECK3
%SVNLOOK% changed -t %TXN% %REPOS% | findstr /R /I ".ext3$"
if %ERRORLEVEL% EQU 1 goto OK
echo Your commit has been blocked because you are trying to commit a restricted file. Restricted formats %FORMATS% >&2
exit /b 1

:OK
exit /b 0
</code>```

Body:
Using the following code in the Collabnet SVN's pre commit script to restrict the specific file extensions to get committed, but it is committing all the files. Could you please tell where I'm going wrong.

#!/bin/sh

REPOS="$1"
TXN="$2"

SVNLOOK=/home/csvn/csvn/bin/svnlook

LOGMSG=`$SVNLOOK log -t "$TXN" "$REPOS" | grep "[a-zA-Z0-9]" | wc -c`

if [ "$LOGMSG" -lt 10 ];
then
  echo -e "\n===========================================================" 1>&2
  echo -e "|| COMMENTS ARE MADE MANDATORY.PLEASE ENTER RELEVANT COMMENT & COMMIT AGAIN Sanjeev sas||" 1>&2
  echo -e "===========================================================" 1>&2
  exit 1
fi

$SVNLOOK changed -t $TXN $REPOS | awk '
BEGIN {
FILTER=".(sh|xls|xlsx|pdf|jpg|JPG|gif|GIF|png|PNG|doc|DOC|docx|DOCX|mpg|swf|avi|mp3|mp4|zip|rar|gz|csv|o|obj|tar|gz|JPEG|jpeg|WMV|wmv|DAT|dat|3GP|3gp|MPEG|mpeg|VOD|vod|ear|jar|war|exe|ppt|PPT|PPTX|pptx|7z|iso|ISO|EAR|WAR|JAR|msg|MSG|rtf|RTF|xlsm|XLSM|vsd|VSD|dot|DOT|camrec|ECF|ecf|mff|MFF|class|CLASS)$"
}
{
 for (i = 1; i < 2; i++) $i = ""; sub(/^ */, "");
 if(match(tolower($1),FILTER))
 {
     print "File" $1 "is not allowed file type to commit"
     exit 1
 }
}'

exit 0

Body:
Solution for Windows pre-commit.bat

@ECHO OFF

set REPOS=%1
set TXN=%2
set SVNLOOK="path\to\svnlook.exe"

set FORMATS=*.ext1, *.ext2, *.ext3
:CHECK1
%SVNLOOK% changed -t %TXN% %REPOS% | findstr /R /I ".ext1$"
if %ERRORLEVEL% EQU 1 goto CHECK2
echo Your commit has been blocked because you are trying to commit a restricted file. Restricted formats %FORMATS% >&2
exit /b 1

:CHECK2
%SVNLOOK% changed -t %TXN% %REPOS% | findstr /R /I ".ext2$"
if %ERRORLEVEL% EQU 1 goto CHECK3
echo Your commit has been blocked because you are trying to commit a restricted file. Restricted formats %FORMATS% >&2
exit /b 1

:CHECK3
%SVNLOOK% changed -t %TXN% %REPOS% | findstr /R /I ".ext3$"
if %ERRORLEVEL% EQU 1 goto OK
echo Your commit has been blocked because you are trying to commit a restricted file. Restricted formats %FORMATS% >&2
exit /b 1

:OK
exit /b 0


问:
NodeJS Change variable from within a function
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

```<code>app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});
</code>```

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

答:
Javascript is asynchronous in nature. The function 'steamAPI.ResolveVanityURL()' is taking time to execute and therefore next statement 'console.log(steamID)' is getting executed before waiting for the result.

You can either use callbacks or below is an example using 'q' promise library to solve your problem -

```<code>var Q = require('q');

app.get('/:steamid', function(req, res) {
    var steamID;
    resolveUrl(req.params.steamid).then(function(steamID) {
        console.log(steamID); //<--- This will return steamID
        (...)
    });
});

function resolveUrl(id) {
    var deferred = Q.defer();
    steamAPI.ResolveVanityURL(id, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        deferred.resolve(res);
    });
    return deferred.promise;
}
</code>```

Also here is a link to get more information about promises in node.js -
http://www.dotnetcurry.com/nodejs/1242/promises-nodejs-using-q-goodbye-callbacks

Hope this solves your problem.

Body:
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

Body:
Javascript is asynchronous in nature. The function 'steamAPI.ResolveVanityURL()' is taking time to execute and therefore next statement 'console.log(steamID)' is getting executed before waiting for the result.

You can either use callbacks or below is an example using 'q' promise library to solve your problem -

var Q = require('q');

app.get('/:steamid', function(req, res) {
    var steamID;
    resolveUrl(req.params.steamid).then(function(steamID) {
        console.log(steamID); //<--- This will return steamID
        (...)
    });
});

function resolveUrl(id) {
    var deferred = Q.defer();
    steamAPI.ResolveVanityURL(id, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        deferred.resolve(res);
    });
    return deferred.promise;
}

Also here is a link to get more information about promises in node.js -
http://www.dotnetcurry.com/nodejs/1242/promises-nodejs-using-q-goodbye-callbacks

Hope this solves your problem.


答:
This doesn't immediately seem like an obvious problem, but the . character needs to be escaped because you're trying to literally match that character.

This regex, with escaped . and forward slashes works:

```<code>^(nfs:\/\/)(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):([0-9]{4})
</code>```

The problem was that since each capturing group that matches digits can match as few as one digit or as many as three, the regex engine looked at the first 1 (in 172), found that it was valid, then tried matching .  (any character) and found the digit 7, which is not what you want.

In nfs://172.1.1:2049, the second capturing group in your regex matched the first 1 in the IP address, the . matched the 7, the third capturing group matched the 2.. and so on.

Try it here: https://regex101.com/r/TNXDiQ/1

Title: JSON schema pattern validation is failing

Body:
I am using below pattern in json schema to validate strings.

"pattern": "^(nfs://)(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):([0-9]{4})"

But currently it is not validating "nfs://172.1.1:2049" as invalid string.

Body:
This doesn't immediately seem like an obvious problem, but the . character needs to be escaped because you're trying to literally match that character.

This regex, with escaped . and forward slashes works:

^(nfs:\/\/)(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?):([0-9]{4})

The problem was that since each capturing group that matches digits can match as few as one digit or as many as three, the regex engine looked at the first 1 (in 172), found that it was valid, then tried matching .  (any character) and found the digit 7, which is not what you want.

In nfs://172.1.1:2049, the second capturing group in your regex matched the first 1 in the IP address, the . matched the 7, the third capturing group matched the 2.. and so on.

Try it here: https://regex101.com/r/TNXDiQ/1


问:
How to traverse through XML data in Golang?
I have used xml.UnMarshal method to get a struct object but it has it's own limitations. I need a way where I can get all the descendants of a particular type inside a node without specifying the exact xpath.

For example, I have an xml data of the following format:

```<code><content>
    <p>this is content area</p>
    <animal>
        <p>This id dog</p>
        <dog>
           <p>tommy</p>
        </dog>
    </animal>
    <birds>
        <p>this is birds</p>
        <p>this is birds</p>
    </birds>
    <animal>
        <p>this is animals</p>
    </animal>
</content>
</code>```

Now I want to traverse through the above xml and process each node and it's children in that order. The problem is that this structure is not fixed and order of elements may change. So I need a way so that I can traverse like

```<code>While(Content.nextnode())
{
   switch(type of node)
   {
      //Process the node or traverse the child node deeper
   }
}
</code>```

答: xmlquery supports parse an XML document as DOM tree to traverse all nodes, like Go's html package.</p>

Body:
I have used xml.UnMarshal method to get a struct object but it has it's own limitations. I need a way where I can get all the descendants of a particular type inside a node without specifying the exact xpath.

For example, I have an xml data of the following format:

<content>

this is content area

    <animal>

This id dog

        <dog>

tommy

        </dog>
    </animal>
    <birds>

this is birds

this is birds

    </birds>
    <animal>

this is animals

    </animal>
</content>

Now I want to traverse through the above xml and process each node and it's children in that order. The problem is that this structure is not fixed and order of elements may change. So I need a way so that I can traverse like

While(Content.nextnode())
{
   switch(type of node)
   {
      //Process the node or traverse the child node deeper
   }
}


问:
Storing username in cookie to increase cacheability?
Using: PHP, Symfony 1.4, Doctrine, sfGuard

I have a site where the majority of pages could be cached as full HTML pages.  But there is the traditional 'user account toolbar' that appears at the top right of most sites (shows the logged in username, logout link etc.)

This obviously prevents the page from being fully cached as HTML so I plan on outputting the page as standard HTML and adding in the username etc. after page load, via Javascript.

When the user logs in, I will create an extra cookie storing just the username.  Javascript can then check if the cookie exists and create the account toolbar.  The username will only be used for display purposes.  In order to actually log in the users will have to go through the normal login page, using their password etc.

I've searched for blog posts etc on this but not found much. Can anyone identify any security or other concerns with this?

答:
As long as the user name is only used for display purposes you should be golden.  Alternatly you could use an XHR to grab the username from PHP's $_SESSION.

My concerns are that you'd be using the user name to authenticate that user.  Or using the user name as a key to access your cache,  where by changing the user name would give an attacker access to another's cache.


问:
how to check array index
I have following code in jquery

```<code>var newFeeds = [];
$(data.d).each(function () {
  newFeeds.push({
    content: this.Name,
    id: this.Id
  });
});
</code>```

I am able to access values from newFeeds[0].content, newFeeds[1].content, newFeeds[2].content but when I tried to
 access newFeeds[3].content its showing undefined error and checked typeof equals(===) undefined but its showing Uncaught TypeError: Cannot read property 'content' of undefined error. How can I avoid this error. I have only 3 elements in the array. Is there a way in Jquery to avoid this error or Can I set value not available in non existence index ?

答:
You can do something like this:</p>

```<code>var newFeeds = [];
$(data.d).each(function (val) {
    if(val !== undefined) {
        newFeeds.push({
            content: val,
        });
    }
});
</code>```

Title: how to check array index

Body:
I have following code in jquery

var newFeeds = [];
$(data.d).each(function () {
  newFeeds.push({
    content: this.Name,
    id: this.Id
  });
});

I am able to access values from newFeeds[0].content, newFeeds[1].content, newFeeds[2].content but when I tried to
 access newFeeds[3].content its showing undefined error and checked typeof equals(===) undefined but its showing Uncaught TypeError: Cannot read property 'content' of undefined error. How can I avoid this error. I have only 3 elements in the array. Is there a way in Jquery to avoid this error or Can I set value not available in non existence index ?

Body:
You can do something like this:

var newFeeds = [];
$(data.d).each(function (val) {
    if(val !== undefined) {
        newFeeds.push({
            content: val,
        });
    }
});