问:
C++ executable, sh 1:not found
I created a c++ programm that works with ros. The first step would be to open a roscore in a terminal and move on from there. I do so with system("roscore &");

I compiled my file and can run it just fine with ./file.

However, I want to be able to run it as an application (double click). I created a .desktop file and the program shows up in my application list. When i start it though, all I get is a terminal that opens with the message

sh: 1: roscore: not found

etc.

The same applies for the roslaunch commands. I also fork and exec a roslaunch command, which does not work as well.

I tried system("ls"); which worked. All cout messages work as well.

Any idea what is wrong here?

答: roscore executable is not located in std paths (/bin:/usr/bin:). Use the absolute path - system("/path/to/roscore &")

Title: C++ executable, sh 1:not found


来源: stackexchange

问:
golang functions: parallel execution with return
How to make two functions calls f1(2) and f1(1) execute in parallel so that all the program would execute for 2 seconds not for 3.

```<code>package main

import (
    "fmt"
    "time"
)

// sleeps for `secs` seconds
func f1(secs time.Duration) (result string) {
    fmt.Printf("waiting %V\n", secs)
    time.Sleep(secs * time.Second)
    result = fmt.Sprintf("waited for %d seconds", secs)
    return
}

// prints arg1, arg2
func f2(arg1, arg2 string) {
    fmt.Println(arg1)
    fmt.Println(arg2)
}

// this function executes for 3 seconds, because waits a lot
func runNotParallel() {

    out1 := f1(2)
    out2 := f1(1)
    f2(out1, out2)

}

// golang parallel return functions
// todo: make it run so all the function will executes for 2 seconds not for 3
func runParallel() {
    out1 := f1(2)
    out2 := f1(1)
    f2(out1, out2)
}

func main() {
    runNotParallel()
    runParallel()
}
</code>```

playground

I guess I can do it only with channels. Should I redefine function f1 or I can leave it as is and change only way I call it?

答:
Another way you could do it is using WaitGroup

I wrote this utility function to help parallelize a group of functions:

```<code>import "sync"

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

So in your case, we could do this

```<code>value1 := ""
value2 := ""

func1 := func() {
    value1 = f1(2)
}

func2 = func() {
    value2 = f1(1)
}

Parallelize(func1, func2)

f2(out1, out2)
</code>```

If you wanted to use the Parallelize function, you can find it here https://github.com/shomali11/util

ContentLicense: CC BY-SA 3.0

Body:
How to make two functions calls f1(2) and f1(1) execute in parallel so that all the program would execute for 2 seconds not for 3.

package main

import (
    "fmt"
    "time"
)

// sleeps for `secs` seconds
func f1(secs time.Duration) (result string) {
    fmt.Printf("waiting %V\n", secs)
    time.Sleep(secs * time.Second)
    result = fmt.Sprintf("waited for %d seconds", secs)
    return
}

// prints arg1, arg2
func f2(arg1, arg2 string) {
    fmt.Println(arg1)
    fmt.Println(arg2)
}

// this function executes for 3 seconds, because waits a lot
func runNotParallel() {

    out1 := f1(2)
    out2 := f1(1)
    f2(out1, out2)

}

// golang parallel return functions
// todo: make it run so all the function will executes for 2 seconds not for 3
func runParallel() {
    out1 := f1(2)
    out2 := f1(1)
    f2(out1, out2)
}

func main() {
    runNotParallel()
    runParallel()
}

playground

I guess I can do it only with channels. Should I redefine function f1 or I can leave it as is and change only way I call it?

Body:
Another way you could do it is using WaitGroup

I wrote this utility function to help parallelize a group of functions:

import "sync"

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So in your case, we could do this

value1 := ""
value2 := ""

func1 := func() {
    value1 = f1(2)
}

func2 = func() {
    value2 = f1(1)
}

Parallelize(func1, func2)

f2(out1, out2)

If you wanted to use the Parallelize function, you can find it here https://github.com/shomali11/util


问:
Need BrowserAnimationsModule in Angular but gives error in Universal
Hi I am using Angular that uses the BrowserAnimationsModule. But in the universal server side it gives the error "document is not defined".

Because Universal doesn't support BrowserAnimationsModule I need a way to make the server ignore BrowserAnimationsModule and replace it with NoopAnimationsModule.

This is what I have right now but it's not working. Any other methods are welcome too.

```<code>let imports = [
    BrowserModule.withServerTransition({appId: 'ang4-seo'}),
    FormsModule,
    HttpModule,
    routes
];

if(isPlatformBrowser(PLATFORM_ID)){
    imports.push(BrowserAnimationsModule);
}

@NgModule({
    imports: imports,
</code>```

Are there any ways to solve this?

答:
Edit: this solution doesn’t appear to work as of version 6.1. I’ll leave the below solution in case it works again someday and update if I find another solution.

Original answer:

I was having this exact same problem. Full credit goes to this fork on github from pquarme.

What you need to do is:

1) Remove any reference to BrowserAnimationsModule from app.module.ts and create a separate app.browser.module.ts file which contains:

```<code>import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { AppModule} from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserAnimationsModule,
    AppModule
  ],
  bootstrap: [AppComponent]
})
export class AppBrowserModule { }
</code>```

Basically your app.module.ts file will now be platform agnostic. Then, you'll have separate files for your app, your browser environment and your server environment.

2) Import NoopAnimationsModule to your app.server.module.ts so you don't throw errors in Node.

3) Modify your main.ts file to bootstrap AppBrowserModule instead of AppModule

After about 2 hours of searching, this was the only solution that worked for me.

Body:
Hi I am using Angular that uses the BrowserAnimationsModule. But in the universal server side it gives the error "document is not defined".

Because Universal doesn't support BrowserAnimationsModule I need a way to make the server ignore BrowserAnimationsModule and replace it with NoopAnimationsModule.

This is what I have right now but it's not working. Any other methods are welcome too.

let imports = [
    BrowserModule.withServerTransition({appId: 'ang4-seo'}),
    FormsModule,
    HttpModule,
    routes
];

if(isPlatformBrowser(PLATFORM_ID)){
    imports.push(BrowserAnimationsModule);
}

@NgModule({
    imports: imports,

Are there any ways to solve this?

Body:
Edit: this solution doesn’t appear to work as of version 6.1. I’ll leave the below solution in case it works again someday and update if I find another solution.

Original answer:

I was having this exact same problem. Full credit goes to this fork on github from pquarme.

What you need to do is:

1) Remove any reference to BrowserAnimationsModule from app.module.ts and create a separate app.browser.module.ts file which contains:

import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { AppModule} from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserAnimationsModule,
    AppModule
  ],
  bootstrap: [AppComponent]
})
export class AppBrowserModule { }

Basically your app.module.ts file will now be platform agnostic. Then, you'll have separate files for your app, your browser environment and your server environment.

2) Import NoopAnimationsModule to your app.server.module.ts so you don't throw errors in Node.

3) Modify your main.ts file to bootstrap AppBrowserModule instead of AppModule

After about 2 hours of searching, this was the only solution that worked for me.

ContentLicense: CC BY-SA 4.0


问:
Calculate performance based on rating in another table
There is a table for Sales with revenue each day and another table for Rating which is used to calculate the performance based on revenue milestone

```<code>CREATE TABLE #Rating(
    [Revenue] int NULL,
    [Percentage] float NULL
) ON [PRIMARY]

insert into [#Rating] select 20000, 1.1
insert into [#Rating] select 30000, 1.2
insert into [#Rating] select 40000, 1.3

CREATE TABLE #Sales(
    [Date] datetime,
    [Revenue] int NULL
) ON [PRIMARY]

insert into #Sales select '2017-01-01', 7000
insert into #Sales select '2017-01-02', 22000
insert into #Sales select '2017-01-03', 33000
insert into #Sales select '2017-01-04', 46000
insert into #Sales select '2017-01-05', 50000
</code>```

We would like to evaluate the sales performance based on rating. For instance,

If Revenue reaches 20000 milestone, performance = revenue * 1.0

If Revenue reaches 30000 milestone, performance = revenue * 1.1

So the final performance should be as follow

```<code>Date, Revenue, Performance
'2017-01-01', 7000, 7000
'2017-01-02', 22000, 24200
'2017-01-03', 33000, 39600
'2017-01-04', 46000, 59800
'2017-01-05', 50000, 65000
</code>```

May I know how to setup the query for the matching? Thanks

[Edited to revise the wordings]

答:
try this:</p>

```<code> Select S.Date
       ,S.Revenue
       ,(   (Select Max(R.Percentage)
             From Rating R
             Where S.Revenue < R.Revenue)
         * S.Revenue) as Performance
 From Sales S
</code>```

Body:
There is a table for Sales with revenue each day and another table for Rating which is used to calculate the performance based on revenue milestone

CREATE TABLE #Rating(
    [Revenue] int NULL,
    [Percentage] float NULL
) ON [PRIMARY]

insert into [#Rating] select 20000, 1.1
insert into [#Rating] select 30000, 1.2
insert into [#Rating] select 40000, 1.3

CREATE TABLE #Sales(
    [Date] datetime,
    [Revenue] int NULL
) ON [PRIMARY]

insert into #Sales select '2017-01-01', 7000
insert into #Sales select '2017-01-02', 22000
insert into #Sales select '2017-01-03', 33000
insert into #Sales select '2017-01-04', 46000
insert into #Sales select '2017-01-05', 50000

We would like to evaluate the sales performance based on rating. For instance,

If Revenue reaches 20000 milestone, performance = revenue * 1.0

If Revenue reaches 30000 milestone, performance = revenue * 1.1

So the final performance should be as follow

Date, Revenue, Performance
'2017-01-01', 7000, 7000
'2017-01-02', 22000, 24200
'2017-01-03', 33000, 39600
'2017-01-04', 46000, 59800
'2017-01-05', 50000, 65000

May I know how to setup the query for the matching? Thanks

[Edited to revise the wordings]

Body:
try this:

 Select S.Date
       ,S.Revenue
       ,(   (Select Max(R.Percentage)
             From Rating R
             Where S.Revenue < R.Revenue)
         * S.Revenue) as Performance
 From Sales S


问:
GAE/J request log format breakdown
Here is a sample of GAE Console log record:

 http://i.stack.imgur.com/M2iJX.png for readable high res version.

I would like to provide a breakdown of the fileds, displayed both in the collpased (summary) view and the expended (detail) view. I will fill the fields I know their meaning and would appreciate assistannce with dichipering the rest. This post will be updated once new information is available.

Thank you,

Maxim.

Open issues:

How to read timestamp? [...-prod/0-0-39.346862139187007139]

Why in summary it says request took 343ms but in details is says 344ms ?

If request spend 123ms on cpu and 30ms on API calls where did the rest of the time go? Why the total request time is 343/344ms ?

答:
Isn't 57.593 seconds.milliseconds?
And cpm_usd represents an estimate of what 1,000 requests similar to this request would cost in US dollars.

ContentLicense: CC BY-SA 2.5

Title: GAE/J request log format breakdown


问:
use lookahead to match a string that starts and ends with a quotes and strip the quotes?
I'd like to match on strings that start and end with the same quote, but only with the quotes at the start and end:

```<code>"foo bar"
'foo bar'
"the quick brown fox"
</code>```

But I don't want these matched or stripped:

```<code>foo "bar"
foo 'bar'
'foo bar"
"the lazy" dogs
</code>```

I tried with this java regexp but it doesn't quite work for all the cases:

```<code>Pattern.compile("^\"|^'(.+)\"$|'$").matcher(quotedString).replaceAll("");
</code>```

I think there is a way to do lookahead, but I don't know how to use it in this case.

Or would it be more efficient to set up an if statement that checks them separately?

```<code>Pattern startPattern = Pattern.compile("^\"|^');
Pattern endPattern = Pattern.compile(\"$|'$");

if (startPattern.matcher(s).find() && endPattern.matcher(s).find()) {
    ...
}
</code>```

(of course, this would match 'foo bar", which I do not want)

答:
Here's a method that can check all your requirements:

```<code>public static boolean matches (final String str)
{
    boolean matches = false;

    // check for null string
    if (str == null) return false;

    if ((str.startsWith("\"") && str.endsWith("\"")) ||
        (str.startsWith("\'") && str.endsWith("\'")))
    {
        String strip = str.substring(1, str.length() - 1);

        // make sure the stripped string does not have a quote
        if (strip.indexOf("\"") == -1 && strip.indexOf("\'") == -1)
        {
            matches = true;
        }
    }
    return matches;
}
</code>```

Test:

```<code>public static void main(String[] args)
{
    System.out.println("Should Pass\n-----------");
    System.out.println(matches("\"foo bar\""));
    System.out.println(matches("\'foo bar\'"));
    System.out.println(matches("\"the quick brown fox\""));

    System.out.println("\nShould Fail\n-----------");
    System.out.println(matches("foo \"bar\""));
    System.out.println(matches("foo \'bar\'"));
    System.out.println(matches("'foo bar\""));
    System.out.println(matches("\"the lazy\" dogs"));

}
</code>```

Output:

```<code>Should Pass
-----------
true
true
true

Should Fail
-----------
false
false
false
false
</code>```

Body:
I'd like to match on strings that start and end with the same quote, but only with the quotes at the start and end:

"foo bar"
'foo bar'
"the quick brown fox"

But I don't want these matched or stripped:

foo "bar"
foo 'bar'
'foo bar"
"the lazy" dogs

I tried with this java regexp but it doesn't quite work for all the cases:

Pattern.compile("^\"|^'(.+)\"$|'$").matcher(quotedString).replaceAll("");

I think there is a way to do lookahead, but I don't know how to use it in this case.

Or would it be more efficient to set up an if statement that checks them separately?

Pattern startPattern = Pattern.compile("^\"|^');
Pattern endPattern = Pattern.compile(\"$|'$");

if (startPattern.matcher(s).find() && endPattern.matcher(s).find()) {
    ...
}

(of course, this would match 'foo bar", which I do not want)

Body:
Here's a method that can check all your requirements:

public static boolean matches (final String str)
{
    boolean matches = false;

    // check for null string
    if (str == null) return false;

    if ((str.startsWith("\"") && str.endsWith("\"")) ||
        (str.startsWith("\'") && str.endsWith("\'")))
    {
        String strip = str.substring(1, str.length() - 1);

        // make sure the stripped string does not have a quote
        if (strip.indexOf("\"") == -1 && strip.indexOf("\'") == -1)
        {
            matches = true;
        }
    }
    return matches;
}

Test:

public static void main(String[] args)
{
    System.out.println("Should Pass\n-----------");
    System.out.println(matches("\"foo bar\""));
    System.out.println(matches("\'foo bar\'"));
    System.out.println(matches("\"the quick brown fox\""));

    System.out.println("\nShould Fail\n-----------");
    System.out.println(matches("foo \"bar\""));
    System.out.println(matches("foo \'bar\'"));
    System.out.println(matches("'foo bar\""));
    System.out.println(matches("\"the lazy\" dogs"));

}

Output:

Should Pass
-----------
true
true
true

Should Fail
-----------
false
false
false
false


问:
Java for loop i++ as a string
Let's say we have a for loop

```<code>for(int i = 0; i < 10; i++) {
    ...
}
</code>```

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

```<code>for(int i = 0; i < 10; increment) {
    ...
}
</code>```

How can I make this work?

答:
You could parse the increment string to an int then use that as your increment in your loop:</p>

```<code>String increment = "i+2"; // Will also work for "i++" or "i+n" (n = a number)
String num = increment.replaceAll("i\\+*", "");
int incValue = 1;
if(!num.isEmpty())
    incValue = Integer.parseInt(num);

for(int i = 0; i < 10 ; i+=incValue)
{
    System.out.println(i);
}
</code>```

Title: Java for loop i++ as a string

Body:
Let's say we have a for loop

for(int i = 0; i < 10; i++) {
    ...
}

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

for(int i = 0; i < 10; increment) {
    ...
}

How can I make this work?

Body:
You could parse the increment string to an int then use that as your increment in your loop:

String increment = "i+2"; // Will also work for "i++" or "i+n" (n = a number)
String num = increment.replaceAll("i\\+*", "");
int incValue = 1;
if(!num.isEmpty())
    incValue = Integer.parseInt(num);

for(int i = 0; i < 10 ; i+=incValue)
{
    System.out.println(i);
}


问:
Tomcat Clustering
I have made Tomcat clustering using Apache HTTPD and Two Tomcat 7.0.xx with MOD_JK. I do not use session sharing as my old application is not supporting Serializeable. But Load Balancer is working fine with ratio 1:1.

When I stop first tomcat. any further request came to second one and it also working fine.

When I stop application on first tomcat(tomcat is running for other applications) then it cannot shift load to second tomcat. Half request does not entertains and 500 error in half request. Any further solution ??? ..

答: mod_jk loadbalances between servers, not applications.  Therefore, if a tomcat is up and the application inside it is down, you will have errors 50% of the time. </p>

Title: Tomcat Clustering


问:
translate CGContext generating image method from ios to mac
Is anyone able to help me translate this method in ios to mac version? Code is written in C# in Xamarin</p>

```<code>public static UIImage GetImageFromColor(UIColor color, float borderWidth = 1.0f)
    {
        var rect = new CGRect(0.0f, 0.0f, borderWidth, borderWidth);
        UIGraphics.BeginImageContext(rect.Size);
        var context = UIGraphics.GetCurrentContext();
        context.SetFillColor(color.CGColor);
        context.FillRect(rect);

        var image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return image.CreateResizableImage(new UIEdgeInsets(1.0f, 1.0f, 1.0f, 1.0f));
    }
</code>```

答:
UIGraphics.BeginImageContext translates to a CGBitmapContext (or CGContext depending upon what you need).

So to fill a CGBitmapContext with a color:

```<code>var size = new CGSize(width, height);
var rect = new CGRect(new CGPoint(), size);

NSImage image;
using (var context = new CGBitmapContext(IntPtr.Zero, width, height, 8, width * 4, NSColorSpace.GenericRGBColorSpace.ColorSpace, CGImageAlphaInfo.PremultipliedFirst))
{
    context.SetFillColor(NSColor.Red.CGColor);
    context.FillRect(rect);
    using (var cgImage = context.ToImage())
    {
        image = new NSImage(cgImage, size);
    }
}
</code>```

Note: You should use using or make sure that you Dispose of the context and CGImage to avoid a memory leak

Body:
Is anyone able to help me translate this method in ios to mac version? Code is written in C# in Xamarin

public static UIImage GetImageFromColor(UIColor color, float borderWidth = 1.0f)
    {
        var rect = new CGRect(0.0f, 0.0f, borderWidth, borderWidth);
        UIGraphics.BeginImageContext(rect.Size);
        var context = UIGraphics.GetCurrentContext();
        context.SetFillColor(color.CGColor);
        context.FillRect(rect);

        var image = UIGraphics.GetImageFromCurrentImageContext();
        UIGraphics.EndImageContext();

        return image.CreateResizableImage(new UIEdgeInsets(1.0f, 1.0f, 1.0f, 1.0f));
    }

Body:
UIGraphics.BeginImageContext translates to a CGBitmapContext (or CGContext depending upon what you need).

So to fill a CGBitmapContext with a color:

var size = new CGSize(width, height);
var rect = new CGRect(new CGPoint(), size);

NSImage image;
using (var context = new CGBitmapContext(IntPtr.Zero, width, height, 8, width * 4, NSColorSpace.GenericRGBColorSpace.ColorSpace, CGImageAlphaInfo.PremultipliedFirst))
{
    context.SetFillColor(NSColor.Red.CGColor);
    context.FillRect(rect);
    using (var cgImage = context.ToImage())
    {
        image = new NSImage(cgImage, size);
    }
}

Note: You should use using or make sure that you Dispose of the context and CGImage to avoid a memory leak


问:
Angular2 router: how to correctly load children modules with their own routing rules
here is my Angular2 app structure:

Here is part of my code. The following is the main module of the Angular2 app, that imports its routing rules and a child module (EdgeModule) and uses some components related to some pages.

app.module.ts

```<code>@NgModule({
    declarations: [
        AppComponent,
        PageNotFoundComponent,
        LoginComponent
    ],
    imports: [
        ...
        appRouting,
        EdgeModule
    ],
    providers: [
        appRoutingProviders,
        LoginService
    ],
    bootstrap: [AppComponent]
})

export class AppModule {
}
</code>```

Here is the routing rules for the main module. It have paths to login page and page not found.

app.routing.ts

```<code>const appRoutes: Routes = [
    { path: 'login', component: LoginComponent },
    { path: '**', component: PageNotFoundComponent }
];

export const appRoutingProviders: any[] = [];

export const appRouting = RouterModule.forRoot(appRoutes, { useHash: true });
</code>```

Here is EdgeModule that declares the component that it uses and import its own routing rules and 2 child modules (FirstSectionModule and SecondSectionModule).

edge.module.ts

```<code>@NgModule({
    declarations: [
        EdgeComponent,
        SidebarComponent,
        TopbarComponent
    ],
    imports: [
        ...
        edgeRouting,
        FirstSectionModule,
        SecondSectionModule
    ],
    providers: [
        AuthGuard
    ]
})

export class EdgeModule {
}
</code>```

Here is the routing rules for the module that loads, as you can see, topbar and sidebar components.

edge.routing.ts

```<code>Paths['edgePaths'] = {
    firstSection: 'firstSection',
    secondSection: 'secondSection'
};

const appRoutes: Routes = [
    { path: '', component: EdgeComponent,
        canActivate: [AuthGuard],
        children: [
            { path: Paths.edgePaths.firstSection, loadChildren: '../somepath/first-section.module#FirstModule' },
            { path: Paths.edgePaths.secondSection, loadChildren: '../someotherpath/second-section.module#SecondModule' },
            { path: '', redirectTo: edgePaths.dashboard, pathMatch: 'full' }
        ]
    }
];

export const edgeRouting = RouterModule.forChild(appRoutes);
</code>```

Finally, this is one of the two child module, that have its components and imports its routing rules.

first-section.module.ts

```<code>@NgModule({
    declarations: [
        FirstSectionComponent,
        SomeComponent
    ],
    imports: [
        ...
        firstSectionRouting
    ],
    providers: [
        AuthGuard,
    ]
})

export class FirstSectionModule {
}
</code>```

These are the routing rules for the pages (components) of FirstSectionModule

first-section.routing.ts

```<code>Paths['firstSectionPaths'] = {
    someSubPage: 'some-sub-page',
    someOtherSubPage: 'some-other-sub-page'
};

const appRoutes: Routes = [
    {
        path: '',
        children: [
            { path: Paths.firstSectionPaths.someSubPage, component: someSubPageComponent},
            { path: Paths.firstSectionPaths.someOtherSubPage, component: someOtherSubPageComponent},
            { path: '', component: AnagraficheComponent }
        ]
    }
];

export const firstSectionRouting = RouterModule.forChild(appRoutes);
</code>```

Almost the same happens for second-section.module.ts and second-section.routing.ts files.

When i run the app the first things that load is the page related to FirstSectionComponent, with no sidebar nor topbar.

Can you tell me what's wrong with my code? There are not errors in the console.

答:
You can try this using loadChildren where the homeModule, productModule, aboutModule have their own route rules.

```<code>const routes: Routes = [
    { path: 'home', loadChildren: 'app/areas/home/home.module#homeModule' },
    { path: 'product', loadChildren: 'app/areas/product/product.module#ProductModule' },
    { path: 'drawing', loadChildren: 'app/areas/about/about.module#AboutModule' }
];

export const appRouting = RouterModule.forRoot(routes);
</code>```

and the home route rules will be like

```<code>export const RouteConfig: Routes = [
    {
        path: '',
        component: HomeComponent,
        canActivate: [AuthGuard],
        children: [
            { path: '', component: HomePage },
            { path: 'test/:id', component: Testinfo},
            { path: 'test2/:id', component: Testinfo1},
            { path: 'test3/:id', component: Testinfo2}
        ]
    }
];
</code>```

this is also known as lazy loading the modules.

```<code>{ path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }
</code>```

There's a few important things to notice here:
We use the property loadChildren instead of component.
We pass a string instead of a symbol to avoid loading the module eagerly.
We define not only the path to the module but the name of the class as well.
There's nothing special about LazyModule other than it has its own routing and a component called LazyComponent.

Check out this awesome tutorial related to this:
https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html

Body:
here is my Angular2 app structure:

Here is part of my code. The following is the main module of the Angular2 app, that imports its routing rules and a child module (EdgeModule) and uses some components related to some pages.

app.module.ts

@NgModule({
    declarations: [
        AppComponent,
        PageNotFoundComponent,
        LoginComponent
    ],
    imports: [
        ...
        appRouting,
        EdgeModule
    ],
    providers: [
        appRoutingProviders,
        LoginService
    ],
    bootstrap: [AppComponent]
})

export class AppModule {
}

Here is the routing rules for the main module. It have paths to login page and page not found.

app.routing.ts

const appRoutes: Routes = [
    { path: 'login', component: LoginComponent },
    { path: '**', component: PageNotFoundComponent }
];

export const appRoutingProviders: any[] = [];

export const appRouting = RouterModule.forRoot(appRoutes, { useHash: true });

Here is EdgeModule that declares the component that it uses and import its own routing rules and 2 child modules (FirstSectionModule and SecondSectionModule).

edge.module.ts

@NgModule({
    declarations: [
        EdgeComponent,
        SidebarComponent,
        TopbarComponent
    ],
    imports: [
        ...
        edgeRouting,
        FirstSectionModule,
        SecondSectionModule
    ],
    providers: [
        AuthGuard
    ]
})

export class EdgeModule {
}

Here is the routing rules for the module that loads, as you can see, topbar and sidebar components.

edge.routing.ts

Paths['edgePaths'] = {
    firstSection: 'firstSection',
    secondSection: 'secondSection'
};

const appRoutes: Routes = [
    { path: '', component: EdgeComponent,
        canActivate: [AuthGuard],
        children: [
            { path: Paths.edgePaths.firstSection, loadChildren: '../somepath/first-section.module#FirstModule' },
            { path: Paths.edgePaths.secondSection, loadChildren: '../someotherpath/second-section.module#SecondModule' },
            { path: '', redirectTo: edgePaths.dashboard, pathMatch: 'full' }
        ]
    }
];

export const edgeRouting = RouterModule.forChild(appRoutes);

Finally, this is one of the two child module, that have its components and imports its routing rules.

first-section.module.ts

@NgModule({
    declarations: [
        FirstSectionComponent,
        SomeComponent
    ],
    imports: [
        ...
        firstSectionRouting
    ],
    providers: [
        AuthGuard,
    ]
})

export class FirstSectionModule {
}

These are the routing rules for the pages (components) of FirstSectionModule

first-section.routing.ts

Paths['firstSectionPaths'] = {
    someSubPage: 'some-sub-page',
    someOtherSubPage: 'some-other-sub-page'
};

const appRoutes: Routes = [
    {
        path: '',
        children: [
            { path: Paths.firstSectionPaths.someSubPage, component: someSubPageComponent},
            { path: Paths.firstSectionPaths.someOtherSubPage, component: someOtherSubPageComponent},
            { path: '', component: AnagraficheComponent }
        ]
    }
];

export const firstSectionRouting = RouterModule.forChild(appRoutes);

Almost the same happens for second-section.module.ts and second-section.routing.ts files.

When i run the app the first things that load is the page related to FirstSectionComponent, with no sidebar nor topbar.

Can you tell me what's wrong with my code? There are not errors in the console.

Body:
You can try this using loadChildren where the homeModule, productModule, aboutModule have their own route rules.

const routes: Routes = [
    { path: 'home', loadChildren: 'app/areas/home/home.module#homeModule' },
    { path: 'product', loadChildren: 'app/areas/product/product.module#ProductModule' },
    { path: 'drawing', loadChildren: 'app/areas/about/about.module#AboutModule' }
];

export const appRouting = RouterModule.forRoot(routes);

and the home route rules will be like

export const RouteConfig: Routes = [
    {
        path: '',
        component: HomeComponent,
        canActivate: [AuthGuard],
        children: [
            { path: '', component: HomePage },
            { path: 'test/:id', component: Testinfo},
            { path: 'test2/:id', component: Testinfo1},
            { path: 'test3/:id', component: Testinfo2}
        ]
    }
];

this is also known as lazy loading the modules.

{ path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }

There's a few important things to notice here:
We use the property loadChildren instead of component.
We pass a string instead of a symbol to avoid loading the module eagerly.
We define not only the path to the module but the name of the class as well.
There's nothing special about LazyModule other than it has its own routing and a component called LazyComponent.

Check out this awesome tutorial related to this:
https://angular-2-training-book.rangle.io/handout/modules/lazy-loading-module.html


问:
Use a variable from a previous iteration in a future iteration
Is it possible to use $SecretFolder from the else statement in future Iterations if the company is the same. E.g. Multiple users exist on the list from one company but they all need to have a link generated for 1 folder for the company to access.</p>

```<code>#Location of original dataset
$csv = Import-Csv c:\export.csv

#loops through every line of the csv
Foreach ($line in $csv){

    #Generate random folder name (8 Characters long)
    $SecretFolder = -join ((48..57) + (97..122) | Get-Random -Count 8 | % {[char]$_})

    #Create URL
    $url = "www.website.com.au/2017Rates/$SecretFolder"

    #Test: Has the company already had a folder created
    if (Get-Variable $line.CompanyName -Scope Global -ErrorAction SilentlyContinue)
        {
           #Append URL to CSV for a person who already has a company folder
           $report =@()
           $report += New-Object psobject -Property @{CompanyName=$line.CompanyName;FirstName=$line.FirstName;LastName=$line.LastName;EmailAddress=$line.EmailAddress;'Letter Type'=$line.'Letter Type';URL=$URL}
           $report | export-csv testreporting.csv -Append
        }

     else
     {
        #Create Folder with Random Cryptic name
        mkdir C:\Users\bford\test\$SecretFolder

        #Copy item from FileLocation in CSV to SecretFolder Location
        Copy-Item -Path $line.FileLocation -Destination c:\users\bford\test\$SecretFolder -Recurse -ErrorAction SilentlyContinue

        #Create Variable for Logic test with the Name CompanyName
        New-Variable -Name $line.CompanyName

        #Append csv with the updated details
        $S_report =@()
        $S_report += New-Object psobject -Property @{CompanyName=$line.CompanyName;FirstName=$line.FirstName;LastName=$line.LastName;EmailAddress=$line.EmailAddress;'Letter Type'=$line.'Letter Type';URL=$url}
        $S_report | export-csv testreporting.csv -Append

    }
}

#Cleanup remove all the variables added
Remove-Variable * -ErrorAction SilentlyContinue
</code>```

答:
Do you have any reason to think it's impossible? Yeah it's possible, you should Google hashtables and find that they do everything you're trying to do with get-variable, only way better.

But your question amounts to "how do I rewrite my script so it works?" and rewriting your script to me means getting rid of the duplicate @()+= triple lines, the mystery numbers, the global variables, and the extra variables and the if/else, and it ends up a completely different script altogether.

A completely different, and mostly untested, script:

```<code># import and group all people in the same company together
# then loop over the groups (companies)
Import-Csv -Path c:\export.csv |
  Group-Object -Property CompanyName |
  ForEach-Object {

    # This loop is once per company, make one secret folder for this company.
    $SecretFolder = -join ( [char[]]'abcdefghijklmnopqrstuvwxyz1234567890' | Get-Random -Count 8 )
    New-Item -ItemType Directory -Path "C:\Users\bford\test\$SecretFolder"

    # Loop through all the people in this company, and copy their files into this company's secret folder
    $_.Group | ForEach-Object {
        Copy-Item -Path $_.FileLocation -Destination c:\users\bford\test\$SecretFolder -Recurse -ErrorAction SilentlyContinue
    }

    # Output each person in this company with just the properties needed, and a new one for this company's URL
    $_.Group | Select-Object -Property CompanyName , FirstName,
                                       LastName, EmailAddress, 'Letter Type',
                                       @{Name='Url'; Expression={"www.website.com.au/2017Rates/$SecretFolder"}}

} | Export-Csv -Path testreporting.csv -NoTypeInformation
</code>```

But to edit your script to do what you want, use a hashtable, e.g.

```<code>$SecretFolders = @{} #at top of your script, outside loops

# in loops:
if (-not $SecretFolders.ContainsKey($line.CompanyName))
{
    $SecretFolders[$line.CompanyName] = -join (random name generation here)
}

$SecretFolder = $SecretFolders[$line.CompanyName]
</code>```

Body:
Is it possible to use $SecretFolder from the else statement in future Iterations if the company is the same. E.g. Multiple users exist on the list from one company but they all need to have a link generated for 1 folder for the company to access.

#Location of original dataset
$csv = Import-Csv c:\export.csv

#loops through every line of the csv
Foreach ($line in $csv){

    #Generate random folder name (8 Characters long)
    $SecretFolder = -join ((48..57) + (97..122) | Get-Random -Count 8 | % {[char]$_})

    #Create URL
    $url = "www.website.com.au/2017Rates/$SecretFolder"

    #Test: Has the company already had a folder created
    if (Get-Variable $line.CompanyName -Scope Global -ErrorAction SilentlyContinue)
        {
           #Append URL to CSV for a person who already has a company folder
           $report =@()
           $report += New-Object psobject -Property @{CompanyName=$line.CompanyName;FirstName=$line.FirstName;LastName=$line.LastName;EmailAddress=$line.EmailAddress;'Letter Type'=$line.'Letter Type';URL=$URL}
           $report | export-csv testreporting.csv -Append
        }

     else
     {
        #Create Folder with Random Cryptic name
        mkdir C:\Users\bford\test\$SecretFolder

        #Copy item from FileLocation in CSV to SecretFolder Location
        Copy-Item -Path $line.FileLocation -Destination c:\users\bford\test\$SecretFolder -Recurse -ErrorAction SilentlyContinue

        #Create Variable for Logic test with the Name CompanyName
        New-Variable -Name $line.CompanyName

        #Append csv with the updated details
        $S_report =@()
        $S_report += New-Object psobject -Property @{CompanyName=$line.CompanyName;FirstName=$line.FirstName;LastName=$line.LastName;EmailAddress=$line.EmailAddress;'Letter Type'=$line.'Letter Type';URL=$url}
        $S_report | export-csv testreporting.csv -Append

    }
}

#Cleanup remove all the variables added
Remove-Variable * -ErrorAction SilentlyContinue

Body:
Do you have any reason to think it's impossible? Yeah it's possible, you should Google hashtables and find that they do everything you're trying to do with get-variable, only way better.

But your question amounts to "how do I rewrite my script so it works?" and rewriting your script to me means getting rid of the duplicate @()+= triple lines, the mystery numbers, the global variables, and the extra variables and the if/else, and it ends up a completely different script altogether.

A completely different, and mostly untested, script:

# import and group all people in the same company together
# then loop over the groups (companies)
Import-Csv -Path c:\export.csv |
  Group-Object -Property CompanyName |
  ForEach-Object {

    # This loop is once per company, make one secret folder for this company.
    $SecretFolder = -join ( [char[]]'abcdefghijklmnopqrstuvwxyz1234567890' | Get-Random -Count 8 )
    New-Item -ItemType Directory -Path "C:\Users\bford\test\$SecretFolder"

    # Loop through all the people in this company, and copy their files into this company's secret folder
    $_.Group | ForEach-Object {
        Copy-Item -Path $_.FileLocation -Destination c:\users\bford\test\$SecretFolder -Recurse -ErrorAction SilentlyContinue
    }

    # Output each person in this company with just the properties needed, and a new one for this company's URL
    $_.Group | Select-Object -Property CompanyName , FirstName,
                                       LastName, EmailAddress, 'Letter Type',
                                       @{Name='Url'; Expression={"www.website.com.au/2017Rates/$SecretFolder"}}

} | Export-Csv -Path testreporting.csv -NoTypeInformation

But to edit your script to do what you want, use a hashtable, e.g.

$SecretFolders = @{} #at top of your script, outside loops

# in loops:
if (-not $SecretFolders.ContainsKey($line.CompanyName))
{
    $SecretFolders[$line.CompanyName] = -join (random name generation here)
}

$SecretFolder = $SecretFolders[$line.CompanyName]


问:
How can I create folders during installation process?
I know that some folders will create during the setup process by using Setup Project, but I want to create another folder. For example, in C:\Users\User Name\Document.Plus,i want to use code to create it. I'm new to programming. I hope you will help me to achieve it. Thanks</p>

答:
There's some third Party tool to create an executable file:

If the tool has an option to create a new folder then you are lucky.

You can create a folder in your code-behind when your project opens
the  first time, if you have the right permissions that target the
    directory you want.

I suggest do create a folder upon your Project run on the first time using Code Behind


问:
std::fstream crashes after main while using pre-allocated memory
I currently have a std::ofstream being created on the stack, and when it allocates off a global operator new that assigns it memory from a pre-allocated buffer the program will crash after main completes citing std::locale0 : line 59. Read Access Violation. nodeptr was 0x... as the program crash point. nodeptr's memory address is a real address. I have no idea why this is happening, and I can only assume it was because I misunderstand what the allocations are actually doing.

This behaviour happens on a release build tested on MSVC Version 19.10.25019 x86, building on debug has the program complete without a crash. Dr. Memory reports no leaks in debug mode.

Minimal Code:

```<code>#include <fstream>
#include <cstdlib>

std::uint8_t *byte = static_cast<std::uint8_t*>(malloc(134217728)); // 134217728 = 128 MiB

void *operator new(size_t bytes) throw(std::bad_alloc)
    {
        return static_cast<void*>(byte); // Tested empirically, and this is only called once so this shouldnt be a cause of a problem
    }

void operator delete(void *memory) throw()
    {}

int main()
    {
        std::ofstream out("abc");

        free(byte);
    }
</code>```

答:
There are two obvious bugs:

What if operator new is called more than once? What if the constructor of out constructs a sub-object?

You free byte while out is still in scope. When out's destructor runs, you've already returned its memory to the system.

Try this:

```<code>#include <fstream>
#include <cstdlib>

std::uint8_t *byte = static_cast<std::uint8_t*>(malloc(134217728)); // 134217728 = 128 MiB

void *operator new(size_t bytes) throw(std::bad_alloc)
    {
        static int offset = 0;
        void * ret = static_cast<void*>(byte + offset);
        offset += 16 * ((bytes + 15) / 16);
        return ret;
    }

void operator delete(void *memory) throw()
    {}

int main()
    {
        {
            std::ofstream out("abc");
        }

        free(byte);
    }
</code>```

Body:
I currently have a std::ofstream being created on the stack, and when it allocates off a global operator new that assigns it memory from a pre-allocated buffer the program will crash after main completes citing std::locale0 : line 59. Read Access Violation. nodeptr was 0x... as the program crash point. nodeptr's memory address is a real address. I have no idea why this is happening, and I can only assume it was because I misunderstand what the allocations are actually doing.

This behaviour happens on a release build tested on MSVC Version 19.10.25019 x86, building on debug has the program complete without a crash. Dr. Memory reports no leaks in debug mode.

Minimal Code:

#include <fstream>
#include <cstdlib>

std::uint8_t *byte = static_cast<std::uint8_t*>(malloc(134217728)); // 134217728 = 128 MiB

void *operator new(size_t bytes) throw(std::bad_alloc)
    {
        return static_cast<void*>(byte); // Tested empirically, and this is only called once so this shouldnt be a cause of a problem
    }

void operator delete(void *memory) throw()
    {}

int main()
    {
        std::ofstream out("abc");

        free(byte);
    }

Body:
There are two obvious bugs:

What if operator new is called more than once? What if the constructor of out constructs a sub-object?

You free byte while out is still in scope. When out's destructor runs, you've already returned its memory to the system.

Try this:

#include <fstream>
#include <cstdlib>

std::uint8_t *byte = static_cast<std::uint8_t*>(malloc(134217728)); // 134217728 = 128 MiB

void *operator new(size_t bytes) throw(std::bad_alloc)
    {
        static int offset = 0;
        void * ret = static_cast<void*>(byte + offset);
        offset += 16 * ((bytes + 15) / 16);
        return ret;
    }

void operator delete(void *memory) throw()
    {}

int main()
    {
        {
            std::ofstream out("abc");
        }

        free(byte);
    }


问:
belongs_to through associations
Given the following associations, I need to reference the Question that a Choice is attached through from the Choice model. I have been attempting to use belongs_to :question, through: :answer to perform this action.

```<code>class User
  has_many :questions
  has_many :choices
end

class Question
  belongs_to :user
  has_many :answers
  has_one :choice, :through => :answer
end

class Answer
  belongs_to :question
end

class Choice
  belongs_to :user
  belongs_to :answer
  belongs_to :question, :through => :answer

  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
end
</code>```

I am getting

NameError uninitialized constant User::Choice

when I try to do current_user.choices

It works fine, if I don't include the

```<code>belongs_to :question, :through => :answer
</code>```

But I want to use that because I want to be able to do the validates_uniqueness_of

I am probably overlooking something simple. Any help would be appreciated.

答:
So you cant have the behavior that you want but you can do something that feels like it. You want to be able to do Choice.first.question

what I have done in the past is something like this

```<code>class Choice
  belongs_to :user
  belongs_to :answer
  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
  ...
  def question
    answer.question
  end
end
</code>```

this way the you can now call question on Choice

Title: belongs_to through associations

Body:
Given the following associations, I need to reference the Question that a Choice is attached through from the Choice model. I have been attempting to use belongs_to :question, through: :answer to perform this action.

class User
  has_many :questions
  has_many :choices
end

class Question
  belongs_to :user
  has_many :answers
  has_one :choice, :through => :answer
end

class Answer
  belongs_to :question
end

class Choice
  belongs_to :user
  belongs_to :answer
  belongs_to :question, :through => :answer

  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
end

I am getting

NameError uninitialized constant User::Choice

when I try to do current_user.choices

It works fine, if I don't include the

belongs_to :question, :through => :answer

But I want to use that because I want to be able to do the validates_uniqueness_of

I am probably overlooking something simple. Any help would be appreciated.

Body:
So you cant have the behavior that you want but you can do something that feels like it. You want to be able to do Choice.first.question

what I have done in the past is something like this

class Choice
  belongs_to :user
  belongs_to :answer
  validates_uniqueness_of :answer_id, :scope => [ :question_id, :user_id ]
  ...
  def question
    answer.question
  end
end

this way the you can now call question on Choice


问:
What is the correct way to create webservice interface for inserting records using Swagger/Swashbuckle?
I'm building an .Net based web service (using Swagger and Swashbuckle).
I'm new to the tools and having some issues with exposing a call to insert data.

This is what my datamodel class looks like on the server:

```<code>public class User
{
  public long? UserCode { get; set; }
  public string UserName { get; set; } = string.Empty;
  public string EmailAddress { get; set; } = string.Empty;
  public string SomeOtherField1 { get; set; } = string.Empty;
  public string SomeOtherField2 { get; set; } = string.Empty;
}
</code>```

This is what my service definition (controller) looks like:

```<code>[Authorize]
[Route("api/[controller]")]
public class AuditSettingUserController : Controller
{
  private AppSettings AppSettings { get; set; }

  public AuditSettingUserController(IOptions<AppSettings> settings)
  {
    AppSettings = settings.Value;
  }

  [HttpPut()]
  [Route("api/DashboardSettings/CreateUser/{userrecord}")]
  public void CreateUser(User userrecord)
  {
  }
}
</code>```

This is what the call looks like from the client side:

```<code>IO.Swagger.Api.SettingUserApi dsApi = new IO.Swagger.Api.SettingUserApi("http://localhost:56995");
IO.Swagger.Model.User record = new IO.Swagger.Model.User()
{
   UserCode = 100,
   UserName = "Foo",
   EmailAddress = "Foo2"
};
string sSerializedRecord = JsonConvert.SerializeObject(record);
dsApi.ApiSettingUserApiSettingsCreateUserByUserrecordPut(sSerializedRecord);
</code>```

Everything build successfully and runs with out errors.

However there are two issues.
First, when I look at the service call method definition in the generated code on the client side, I'm a little confused. I don't understand the prototype that was generated.

The definition looks like this:

```<code>public void ApiSettingUserApiSettingsCreateUserByUserrecordPut (string userrecord, long? userCode = null, string userName = null, string emailAddress = null, string SomeOtherField1 = null, string SomeOtherField2 = null)
</code>```

Secondly, on the server side, the record passed in is empty. (The record is not null, but the values inside are null/empty).

What am I doing wrong here? Do I not have my service call, its parameters defined correctly?

Thanks

答:
The issue was with the service method definition and it's decorations.

```<code>[HttpPut()]
[Route("api/DashboardSettings/CreateUser/{userrecord}")]
public void CreateUser(User userrecord)
{
}
</code>```

Should be:

```<code>[HttpPut()]
[Route("api/DashboardSettings/CreateUser")]
public void CreateUser(User userrecord)
{
}
</code>```

By having the method parameter included in the [Route] definition, the method was expecting the parameter to be part of the command line.
I removed the parameter from the [Route] and all works as expected.

Body:
I'm building an .Net based web service (using Swagger and Swashbuckle).
I'm new to the tools and having some issues with exposing a call to insert data.

This is what my datamodel class looks like on the server:

public class User
{
  public long? UserCode { get; set; }
  public string UserName { get; set; } = string.Empty;
  public string EmailAddress { get; set; } = string.Empty;
  public string SomeOtherField1 { get; set; } = string.Empty;
  public string SomeOtherField2 { get; set; } = string.Empty;
}

This is what my service definition (controller) looks like:

[Authorize]
[Route("api/[controller]")]
public class AuditSettingUserController : Controller
{
  private AppSettings AppSettings { get; set; }

  public AuditSettingUserController(IOptions<AppSettings> settings)
  {
    AppSettings = settings.Value;
  }

  [HttpPut()]
  [Route("api/DashboardSettings/CreateUser/{userrecord}")]
  public void CreateUser(User userrecord)
  {
  }
}

This is what the call looks like from the client side:

IO.Swagger.Api.SettingUserApi dsApi = new IO.Swagger.Api.SettingUserApi("http://localhost:56995");
IO.Swagger.Model.User record = new IO.Swagger.Model.User()
{
   UserCode = 100,
   UserName = "Foo",
   EmailAddress = "Foo2"
};
string sSerializedRecord = JsonConvert.SerializeObject(record);
dsApi.ApiSettingUserApiSettingsCreateUserByUserrecordPut(sSerializedRecord);

Everything build successfully and runs with out errors.

However there are two issues.
First, when I look at the service call method definition in the generated code on the client side, I'm a little confused. I don't understand the prototype that was generated.

The definition looks like this:

public void ApiSettingUserApiSettingsCreateUserByUserrecordPut (string userrecord, long? userCode = null, string userName = null, string emailAddress = null, string SomeOtherField1 = null, string SomeOtherField2 = null)

Secondly, on the server side, the record passed in is empty. (The record is not null, but the values inside are null/empty).

What am I doing wrong here? Do I not have my service call, its parameters defined correctly?

Thanks

Body:
The issue was with the service method definition and it's decorations.

[HttpPut()]
[Route("api/DashboardSettings/CreateUser/{userrecord}")]
public void CreateUser(User userrecord)
{
}

Should be:

[HttpPut()]
[Route("api/DashboardSettings/CreateUser")]
public void CreateUser(User userrecord)
{
}

By having the method parameter included in the [Route] definition, the method was expecting the parameter to be part of the command line.
I removed the parameter from the [Route] and all works as expected.


问:
NSAttributedString from html with blockquote
I've got some simple HTML with a blockquote tag I would like to show in a UILabel (which is inside UITableViewCell, so I don't think using UIWebView is the solution to my problem).

I decided to convert it to NSAttributedString and all worked fine, but what I received is quoted text looking exactly the same as text not being cited (no indentation, no block mark).

I would like to ask if there is any way you can achieve something similar to modern quote mentioned here? Or at least some indentation and prefix before every line of paragraph with quotation (ie > like oldschool email quotation) using NSAttributedString?

答:
I understand that you have asked this in Obj-C, but I was just clicking through and noticed it's been three years and no answers and I'd done this already elsewhere so I might as well share.

```<code>let parsedCommentHTML = html.replacingOccurrences(of: "<blockquote>\n", with: "<blockquote>\n<k style=\"color:#ccc; font-size: 2em; font-family: 'Copperplate'\">“</k>")
let blockQuoteCSS = "\nblockquote > p {color:#808080; display: inline;} \n blockquote { background: #f9f9f9;}"
let pCSS = "p {margin-bottom: 0px;}"
let cssStyle = "\(blockQuoteCSS)\n\(pCSS)\n"

return try NSAttributedString(data: ("<html><head><style>\(cssStyle)</style></head><span style=\"font-family: HelveticaNeue-Thin; font-size: 17\">\(parsedCommentHTML)</span></html>").data(using: String.Encoding.unicode)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)
</code>```

This produces a nice (in my opinion) looking quote:

Body:
I understand that you have asked this in Obj-C, but I was just clicking through and noticed it's been three years and no answers and I'd done this already elsewhere so I might as well share.

let parsedCommentHTML = html.replacingOccurrences(of: "<blockquote>\n", with: "<blockquote>\n<k style=\"color:#ccc; font-size: 2em; font-family: 'Copperplate'\">“</k>")
let blockQuoteCSS = "\nblockquote > p {color:#808080; display: inline;} \n blockquote { background: #f9f9f9;}"
let pCSS = "p {margin-bottom: 0px;}"
let cssStyle = "\(blockQuoteCSS)\n\(pCSS)\n"

return try NSAttributedString(data: ("<html><head><style>\(cssStyle)</style></head><span style=\"font-family: HelveticaNeue-Thin; font-size: 17\">\(parsedCommentHTML)</span></html>").data(using: String.Encoding.unicode)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)

This produces a nice (in my opinion) looking quote:


问:
JSON serialization error when creating a Luigi task graph
I'm trying to batch up the processing of a few Jupyter notebooks using Luigi, and I've run into a problem.

I have two classes. The first, transform.py:

```<code>import nbformat
import nbconvert

import luigi
from nbconvert.preprocessors.execute import CellExecutionError

class Transform(luigi.Task):
    """Foo."""
    notebook = luigi.Parameter()
    requirements = luigi.ListParameter()

    def requires(self):
        return self.requirements

    def run(self):
        nb = nbformat.read(self.notebook, nbformat.current_nbformat)
        # https://nbconvert.readthedocs.io/en/latest/execute_api.html
        ep = nbconvert.preprocessors.ExecutePreprocessor(timeout=600, kernel_name='python3')
        try:
            ep.preprocess(nb, {'metadata': {'path': "/".join(self.notebook.split("/")[:-1])}})
            with self.output().open('w') as f:
                nbformat.write(nb, f)
        except CellExecutionError:
            pass  # TODO

    def output(self):
        return luigi.LocalTarget(self.notebook)
</code>```

This defines a Luigi task that takes a notebook as input (along with possible prior requirements to running this task) and ought to run that notebook and report a success or failure as output.

To run Transform tasks I have a tiny Runner class:

```<code>import luigi

class Runner(luigi.Task):
    requirements = luigi.ListParameter()

    def requires(self):
        return self.requirements
</code>```

To run my little job, I do:

```<code>from transform Transform
trans = Transform("../tests/fixtures/empty_valid_errorless_notebook.ipynb", [])
from runner import Runner
run_things = Runner([trans])
</code>```

But this raises TypeError: Object of type 'Transform' is not JSON serializable!

Is my luigi task format correct? If so, is it obvious what component in run is making the entire class unserializable? If not, how should I go about debugging this?

答:
requires() is supposed to return a task or tasks, not a parameter.

e.g.,

```<code>class Runner(luigi.Task):
  notebooks = luigi.ListParameter()

  def requires(self):
    required_tasks = []
    for notebook in self.notebooks:
      required_tasks.append(Transform(notebook))
    return required_tasks

class Transform(luigi.Task):
   notebook = luigi.Parameter()

   def requires(self):
      return []

# then to run at cmd line
luigi --module YourModule Runner --noteboooks '["notebook1.pynb","notebook2.pynb"]'
</code>```

Body:
I'm trying to batch up the processing of a few Jupyter notebooks using Luigi, and I've run into a problem.

I have two classes. The first, transform.py:

import nbformat
import nbconvert

import luigi
from nbconvert.preprocessors.execute import CellExecutionError

class Transform(luigi.Task):
    """Foo."""
    notebook = luigi.Parameter()
    requirements = luigi.ListParameter()

    def requires(self):
        return self.requirements

    def run(self):
        nb = nbformat.read(self.notebook, nbformat.current_nbformat)
        # https://nbconvert.readthedocs.io/en/latest/execute_api.html
        ep = nbconvert.preprocessors.ExecutePreprocessor(timeout=600, kernel_name='python3')
        try:
            ep.preprocess(nb, {'metadata': {'path': "/".join(self.notebook.split("/")[:-1])}})
            with self.output().open('w') as f:
                nbformat.write(nb, f)
        except CellExecutionError:
            pass  # TODO

    def output(self):
        return luigi.LocalTarget(self.notebook)

This defines a Luigi task that takes a notebook as input (along with possible prior requirements to running this task) and ought to run that notebook and report a success or failure as output.

To run Transform tasks I have a tiny Runner class:

import luigi

class Runner(luigi.Task):
    requirements = luigi.ListParameter()

    def requires(self):
        return self.requirements

To run my little job, I do:

from transform Transform
trans = Transform("../tests/fixtures/empty_valid_errorless_notebook.ipynb", [])
from runner import Runner
run_things = Runner([trans])

But this raises TypeError: Object of type 'Transform' is not JSON serializable!

Is my luigi task format correct? If so, is it obvious what component in run is making the entire class unserializable? If not, how should I go about debugging this?

Body:
requires() is supposed to return a task or tasks, not a parameter.

e.g.,

class Runner(luigi.Task):
  notebooks = luigi.ListParameter()

  def requires(self):
    required_tasks = []
    for notebook in self.notebooks:
      required_tasks.append(Transform(notebook))
    return required_tasks

class Transform(luigi.Task):
   notebook = luigi.Parameter()

   def requires(self):
      return []

# then to run at cmd line
luigi --module YourModule Runner --noteboooks '["notebook1.pynb","notebook2.pynb"]'


问:
Creating a barplot from an s3 constructor
I have most of this s3 constructor assignment working, thanks to stackoverflow contributors, but now I'm having issues creating a barplot of the information:

My constructor and variables are currently:

```<code># Create constructor
ChlorReads <- function(theid, thename, thegender, theldl, thehdl, thetrigl) {
  x <- list(id=theid, name=thename, gender=thegender, ldl=theldl, hdl=thehdl, trigl=thetrigl)
  class(x) = "Patient"
  return(x)
}

# Prints the patient information (one item in the list)
print.Patient = function(x, ...){

  cat("ID: ", x$id, " Name: ", x$name, " Gender: ", x$gender,
      "\nLDL: ", x$ldl, " HDL: ", x$hdl, " Triglycerides: ", x$trigl,"\n", sep="")

}

# Input p1
p1 <- ChlorReads(9876, "Virgil", "M", 248, 45, 148)
</code>```

I want to ultimately plot(p1), so I'm trying to create another function that allows me to create a table that looks like the following image:

I currently have:

```<code>plot.Patient = function(x, ...) {
  counts <- table(x$ldl,x$hdl,x$trigl)
  barplot(counts, main="Chloresterol Readings")
}
</code>```

But the table isn't working. I get the following error:  Error in barplot.default(counts, main = "Chloresterol Readings") :
  'height' must be a vector or a matrix

答:
For anyone coming across this, the code below created output similar to the example image posted above.

plot.Patient = function(x, ...) {
  counts <- c(x$ldl,x$hdl,x$trigl)
  barplot(counts, main="Chloresterol Readings", xlab = c("Name: ", x$name), names.arg = c("LDL", "HDL", "Triglycerides"))
}

Body:
I have most of this s3 constructor assignment working, thanks to stackoverflow contributors, but now I'm having issues creating a barplot of the information:

My constructor and variables are currently:

# Create constructor
ChlorReads <- function(theid, thename, thegender, theldl, thehdl, thetrigl) {
  x <- list(id=theid, name=thename, gender=thegender, ldl=theldl, hdl=thehdl, trigl=thetrigl)
  class(x) = "Patient"
  return(x)
}

# Prints the patient information (one item in the list)
print.Patient = function(x, ...){

  cat("ID: ", x$id, " Name: ", x$name, " Gender: ", x$gender,
      "\nLDL: ", x$ldl, " HDL: ", x$hdl, " Triglycerides: ", x$trigl,"\n", sep="")

}

# Input p1
p1 <- ChlorReads(9876, "Virgil", "M", 248, 45, 148)

I want to ultimately plot(p1), so I'm trying to create another function that allows me to create a table that looks like the following image:

I currently have:

plot.Patient = function(x, ...) {
  counts <- table(x$ldl,x$hdl,x$trigl)
  barplot(counts, main="Chloresterol Readings")
}

But the table isn't working. I get the following error:  Error in barplot.default(counts, main = "Chloresterol Readings") :
  'height' must be a vector or a matrix


问:
dalvik.system.PathClassLoader cannot be cast to java.net.URLClassLoader
Android - Adding jar file dynamically to a ClassLoader like:

```<code>String strJarfile = "/data/data/com.example.classloader/files/apps/Calc/SumAndSub.jar";
URLClassLoader sysloader = (URLClassLoader) ClassLoader
                .getSystemClassLoader();
        try
        {
            File f = new File(strJarfile);
            URL u = f.toURI().toURL();

            Class[] parameters = new Class[] { URL.class };
            Method method = URLClassLoader.class.getDeclaredMethod("addURL",
                    parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[] { u });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
</code>```

And, error:

```<code>Caused by: java.lang.ClassCastException: dalvik.system.PathClassLoader cannot be cast to java.net.URLClassLoader
</code>```

This code work fine in java-core, but not with android.
What is solution?
Thanks,

答:
```<code>URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();

ClassLoader.getSystemClassLoader()
</code>```

will return the PathClassLoader as a ClassLoader, so the (URLClassLoader) will cause the exception.

Body:
Android - Adding jar file dynamically to a ClassLoader like:

String strJarfile = "/data/data/com.example.classloader/files/apps/Calc/SumAndSub.jar";
URLClassLoader sysloader = (URLClassLoader) ClassLoader
                .getSystemClassLoader();
        try
        {
            File f = new File(strJarfile);
            URL u = f.toURI().toURL();

            Class[] parameters = new Class[] { URL.class };
            Method method = URLClassLoader.class.getDeclaredMethod("addURL",
                    parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[] { u });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

And, error:

Caused by: java.lang.ClassCastException: dalvik.system.PathClassLoader cannot be cast to java.net.URLClassLoader

This code work fine in java-core, but not with android.
What is solution?
Thanks,

Body:
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();

ClassLoader.getSystemClassLoader()

will return the PathClassLoader as a ClassLoader, so the (URLClassLoader) will cause the exception.


问:
C language structure
I'm learning the C language. Can anybody help me to understand the following result:

```<code>int main()
{
  struct xx
  {
    int x;
    char name[];
  };
  struct xx *s;
  printf("%d",s->x);
  printf("%s",s->name);
   return 0;
}
</code>```

output:- Segmentation fault

I wrote another code which is:

```<code>struct Foo
{
  char *pName;
};

int main()
{
  struct Foo *obj = malloc(sizeof(struct Foo));
  strcpy(obj->pName,"Your Name");
  printf("%s", obj->pName);
  return 0;
}
</code>```

output : Segmentation Fault (core dumped);

Why am I getting segmentation fault? What's wrong with the code? What is the meaning of core dumped ?

答:
The pointer in the struct is not initiallized when being used(which is called wild pointer). Even though the pointer has been initialized, it shoud point to an effective memory area.

When learning C language, memory operation is the top thing.

Title: C language structure

Body:
I'm learning the C language. Can anybody help me to understand the following result:

int main()
{
  struct xx
  {
    int x;
    char name[];
  };
  struct xx *s;
  printf("%d",s->x);
  printf("%s",s->name);
   return 0;
}

output:- Segmentation fault

I wrote another code which is:

struct Foo
{
  char *pName;
};

int main()
{
  struct Foo *obj = malloc(sizeof(struct Foo));
  strcpy(obj->pName,"Your Name");
  printf("%s", obj->pName);
  return 0;
}

output : Segmentation Fault (core dumped);

Why am I getting segmentation fault? What's wrong with the code? What is the meaning of core dumped ?


问:
How to put a UIView in a UITableView and It will be pinned on the bottom
I am trying to build a UITableView Controller, which will be my app's ABOUT information session.

At the bottom of the view, it will be reserved as circle menu. So I need a UIView with height of 200 there, when I drag a UIView to the controller, it always sit as a table cell.

As you can see, the red area always sit under the last table cell group, how to pin it on the bottom of the View Controller.

Thanks in advance.

答:
You can't add a UIView at the bottom of the UITableViewController. If that is a hard requirement you have to switch to UIViewController. And then you can use UITableView and other UIView's as well.

If you are using a navigation controller with UITableViewController then you can use UIToolBar which sticks at the bottom of view controller but have some limitations too. See this


问:
What are the proper permissions for an upload folder with PHP/Apache?
Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.

I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:

```<code>chown apache:apache -R uploads/
chmod 755 -R uploads/
</code>```

The only problem now is that the FTP user can not modify the uploaded files at all.

Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user?

答:
Based on the answer from @Ryan Ahearn, following is what I did on Ubuntu 16.04 to create a user front that only has permission for nginx's web dir /var/www/html.

Steps:

```
* pre-steps:
    * basic prepare of server,
    * create user 'dev'
        which will be the owner of "/var/www/html",
    *
    * install nginx,
    *
*
* create user 'front'
    sudo useradd -d /home/front -s /bin/bash front
    sudo passwd front

    # create home folder, if not exists yet,
    sudo mkdir /home/front
    # set owner of new home folder,
    sudo chown -R front:front /home/front

    # switch to user,
    su - front

    # copy .bashrc, if not exists yet,
    cp /etc/skel/.bashrc ~front/
    cp /etc/skel/.profile ~front/

    # enable color,
    vi ~front/.bashrc
    # uncomment the line start with "force_color_prompt",

    # exit user
    exit
*
* add to group 'dev',
    sudo usermod -a -G dev front
* change owner of web dir,
    sudo chown -R dev:dev /var/www
* change permission of web dir,
    chmod 775 $(find /var/www/html -type d)
    chmod 664 $(find /var/www/html -type f)
*
* re-login as 'front'
    to make group take effect,
*
* test
*
* ok
*

```

Body:
Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.

I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:

chown apache:apache -R uploads/
chmod 755 -R uploads/

The only problem now is that the FTP user can not modify the uploaded files at all.

Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user?

Body:
Based on the answer from @Ryan Ahearn, following is what I did on Ubuntu 16.04 to create a user front that only has permission for nginx's web dir /var/www/html.

Steps:

* pre-steps:
    * basic prepare of server,
    * create user 'dev'
        which will be the owner of "/var/www/html",
    *
    * install nginx,
    *
*
* create user 'front'
    sudo useradd -d /home/front -s /bin/bash front
    sudo passwd front

    # create home folder, if not exists yet,
    sudo mkdir /home/front
    # set owner of new home folder,
    sudo chown -R front:front /home/front

    # switch to user,
    su - front

    # copy .bashrc, if not exists yet,
    cp /etc/skel/.bashrc ~front/
    cp /etc/skel/.profile ~front/

    # enable color,
    vi ~front/.bashrc
    # uncomment the line start with "force_color_prompt",

    # exit user
    exit
*
* add to group 'dev',
    sudo usermod -a -G dev front
* change owner of web dir,
    sudo chown -R dev:dev /var/www
* change permission of web dir,
    chmod 775 $(find /var/www/html -type d)
    chmod 664 $(find /var/www/html -type f)
*
* re-login as 'front'
    to make group take effect,
*
* test
*
* ok
*


问:
Which IDE for Scala 2.8?
This is the same question for older version of Scala, but they say that Eclipse plugin has been improved vastly. Is it the best IDE now? How do different Scala IDE compare today? </p>

答:
My experiences clearly point to IntelliJ IDEA:

About six months ago, when I started a serious Scala (multi module) project, I had to abandon Eclipse as my favorite Java IDE and switched to IntelliJ (9.0.x). Eclipse Scala IDE was way to buggy and often stopped responding at some point, even for the most simple projects. For CI (Hudson) and command line build, I depend on Maven (with Scala plugin). The Maven dependencies (incl. Scala libs) are picked up nicely by IntelliJ.

A few days back I updated to IDEA X (CE) with the current plugin (nightly build) and work became even smoother. Although fsc still terminates after a while when inactive.

From what I see, I'd like to add, that there seems to be way more activity on the IntelliJ side to respond to bugs and improve the plugin continuously. Correct me when I'm wrong, but Eclipse Scala IDE development seems almost stalled. Still no 'official' Helios release!

NB: Just to provide some context (not bragging, really): The aforementioned project consists of about 25 Scala modules (POMs), 5 Java modules, 325 Scala files with a total of about 360 Scala classes, case classes and traits (> 19 kLOC, including comments). My platform is OS X 10.6, Scala 2.8.1, Java 1.6.

UPDATE: After having the need for pretty extensive refactorings (mainly move class, rename package), I discovered that the recent IDEA 10.0.1 plugin 0.4.413 (and probably older versions, too) has quite some problems getting stuff right. I don't want to explain the specifics, but I (almost ever) ended up manually fixing unresolved references or otherwise messed-up code. You can have a look at http://youtrack.jetbrains.net to get an idea.

For everyone who is really considering doing some serious development with Scala, I strongly recommend to evaluate the IDEs in question beyond the basics. When you are into an agile approach, which in my option requires a painless refactoring support without surprises (especially in multi-module projects), things are pretty tight at the moment.

It would be pretty neat, if someone came up with a IDE independent specification-like list of refactorings (and desired outcomes), which could be used to verify an IDE's refactoring support.

Title: Which IDE for Scala 2.8?


问:
Player often continues to move after releasing key
for some reason, my player object continues to move after the movement key is released. The velocity stays at the players movespeed until the key is released pressed and released again. while looking at console output of velX and velY i see something it toggling each frame from 8 to 16 after a few seconds of hold down. and occasionally after releasing the key the velocity will stay at 8 or -8 anyways.

```<code>//Player tick method
public void tick() {

    //Dissalow Exceess Velocity
    velX = Calculations.clamp(velX, -getMaxSpeed(), getMaxSpeed());
    velY = Calculations.clamp(velY, -getMaxSpeed(), getMaxSpeed());

    //move the player
    x += velX;
    y += velY;

    //dissalow exiting room
    x = Calculations.clamp(x, 0, Game.WIDTH - 32);
    y = Calculations.clamp(y, 0, Game.HEIGHT - 32);

    //check for collisions with objects
    collision();
}
</code>```

here is my Clamp method as used above (Calculations.clamp)

```<code>//clamp
public static int clamp(int var, int min, int max)
{
    if(var >= max)
        return var = max;
    else if(var <= min)
        return var = min;
    else return var;
}
</code>```

finally my Keyboard input method

```<code>import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class KeyInput extends KeyAdapter
{
    private Handler myHandler;

    public KeyInput(Handler handler)
    {
        this.myHandler = handler;

    }
    public void keyPressed(KeyEvent e)
    {
        int key = e.getKeyCode();

        for(GameObject object : myHandler.objects)
        {
            if(object.getId() == ID.player)
            {
             if(key == KeyEvent.VK_W) object.setVelY(object.getVelY() - object.getMaxSpeed());
             if(key == KeyEvent.VK_S) object.setVelY(object.getVelY() + object.getMaxSpeed());
             if(key == KeyEvent.VK_A) object.setVelX(object.getVelX() - object.getMaxSpeed());
             if(key == KeyEvent.VK_D) object.setVelX(object.getVelX() + object.getMaxSpeed());
            }
        }
    }
    public void keyReleased(KeyEvent e)
    {
        int key = e.getKeyCode();
        for(GameObject object : myHandler.objects)
        {
            if(object.getId() == ID.player)
            {
             if(key == KeyEvent.VK_W) object.setVelY(object.getVelY() + object.getMaxSpeed());
             if(key == KeyEvent.VK_S) object.setVelY(object.getVelY() - object.getMaxSpeed());
             if(key == KeyEvent.VK_A) object.setVelX(object.getVelX() + object.getMaxSpeed());
             if(key == KeyEvent.VK_D) object.setVelX(object.getVelX() - object.getMaxSpeed());
            }
        }
    }
}
</code>```

答:
Setting the velocity to the maximum velocity or zero instead of adding or subtracting max velocity might solve the problem. </p>

```<code>public void keyPressed(KeyEvent e)
{
    int key = e.getKeyCode();

    for(GameObject object : myHandler.objects)
    {
        if(object.getId() == ID.player)
        {
         if(key == KeyEvent.VK_W) object.setVelY(-object.getMaxSpeed());
         if(key == KeyEvent.VK_S) object.setVelY(object.getMaxSpeed());
         if(key == KeyEvent.VK_A) object.setVelX(-object.getMaxSpeed());
         if(key == KeyEvent.VK_D) object.setVelX(object.getMaxSpeed());
        }
    }
}

public void keyReleased(KeyEvent e)
{
    int key = e.getKeyCode();
    for(GameObject object : myHandler.objects)
    {
        if(object.getId() == ID.player)
        {
         if(key == KeyEvent.VK_W) object.setVelY(0);
         if(key == KeyEvent.VK_S) object.setVelY(0);
         if(key == KeyEvent.VK_A) object.setVelX(0);
         if(key == KeyEvent.VK_D) object.setVelX(0);
        }
    }
}
</code>```

Body:
for some reason, my player object continues to move after the movement key is released. The velocity stays at the players movespeed until the key is released pressed and released again. while looking at console output of velX and velY i see something it toggling each frame from 8 to 16 after a few seconds of hold down. and occasionally after releasing the key the velocity will stay at 8 or -8 anyways.

//Player tick method
public void tick() {

    //Dissalow Exceess Velocity
    velX = Calculations.clamp(velX, -getMaxSpeed(), getMaxSpeed());
    velY = Calculations.clamp(velY, -getMaxSpeed(), getMaxSpeed());

    //move the player
    x += velX;
    y += velY;

    //dissalow exiting room
    x = Calculations.clamp(x, 0, Game.WIDTH - 32);
    y = Calculations.clamp(y, 0, Game.HEIGHT - 32);

    //check for collisions with objects
    collision();
}

here is my Clamp method as used above (Calculations.clamp)

//clamp
public static int clamp(int var, int min, int max)
{
    if(var >= max)
        return var = max;
    else if(var <= min)
        return var = min;
    else return var;
}

finally my Keyboard input method

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class KeyInput extends KeyAdapter
{
    private Handler myHandler;

    public KeyInput(Handler handler)
    {
        this.myHandler = handler;

    }
    public void keyPressed(KeyEvent e)
    {
        int key = e.getKeyCode();

        for(GameObject object : myHandler.objects)
        {
            if(object.getId() == ID.player)
            {
             if(key == KeyEvent.VK_W) object.setVelY(object.getVelY() - object.getMaxSpeed());
             if(key == KeyEvent.VK_S) object.setVelY(object.getVelY() + object.getMaxSpeed());
             if(key == KeyEvent.VK_A) object.setVelX(object.getVelX() - object.getMaxSpeed());
             if(key == KeyEvent.VK_D) object.setVelX(object.getVelX() + object.getMaxSpeed());
            }
        }
    }
    public void keyReleased(KeyEvent e)
    {
        int key = e.getKeyCode();
        for(GameObject object : myHandler.objects)
        {
            if(object.getId() == ID.player)
            {
             if(key == KeyEvent.VK_W) object.setVelY(object.getVelY() + object.getMaxSpeed());
             if(key == KeyEvent.VK_S) object.setVelY(object.getVelY() - object.getMaxSpeed());
             if(key == KeyEvent.VK_A) object.setVelX(object.getVelX() + object.getMaxSpeed());
             if(key == KeyEvent.VK_D) object.setVelX(object.getVelX() - object.getMaxSpeed());
            }
        }
    }
}

Body:
Setting the velocity to the maximum velocity or zero instead of adding or subtracting max velocity might solve the problem.

public void keyPressed(KeyEvent e)
{
    int key = e.getKeyCode();

    for(GameObject object : myHandler.objects)
    {
        if(object.getId() == ID.player)
        {
         if(key == KeyEvent.VK_W) object.setVelY(-object.getMaxSpeed());
         if(key == KeyEvent.VK_S) object.setVelY(object.getMaxSpeed());
         if(key == KeyEvent.VK_A) object.setVelX(-object.getMaxSpeed());
         if(key == KeyEvent.VK_D) object.setVelX(object.getMaxSpeed());
        }
    }
}

public void keyReleased(KeyEvent e)
{
    int key = e.getKeyCode();
    for(GameObject object : myHandler.objects)
    {
        if(object.getId() == ID.player)
        {
         if(key == KeyEvent.VK_W) object.setVelY(0);
         if(key == KeyEvent.VK_S) object.setVelY(0);
         if(key == KeyEvent.VK_A) object.setVelX(0);
         if(key == KeyEvent.VK_D) object.setVelX(0);
        }
    }
}


问:
Azure Servicebus: Receive all the message from one session id of a queue
I have 2 question for which I failed to find any solution.

Is there any built in way in azure service bus queue, where I can receive messages only from one session (for that sessionId) in my session handler.

Also is there any way I can receive messages only from the deadlettered queue for that session alone.

I can do this programmatically in my code, but I don't want to write if else logic in my code.

答:
Is there any built in way in azure service bus queue, where I can receive messages only from one session (for that sessionId) in my session handler.

As Sean Feldman mentioned QueueClient.AcceptMessageSessionAsync(sessionID) allows to achieve that for a normal queue.

If want to use QueueClient.AcceptMessageSessionAsync(sessionID) to receive queue message, we need to create the with RequiresSession true,

```<code>var description = new QueueDescription(QueueName)
{
    RequiresSession = true
};

namespaceManager.CreateQueue(description);
</code>```

Also is there any way I can receive messages only from the deadlettered queue for that session alone.

Base on my test we can't get the dead-letter queue message from the deadletter queue with following code

```<code>   var dlqName= QueueClient.FormatDeadLetterPath(queueName);
   var dlqClient = QueueClient.CreateFromConnectionString(connectionstring, dfQueue);
   var gid = Guid.NewGuid().ToString();
   var messageSession = client.AcceptMessageSession(gid);
   var receiveMessage = messageSession.Receive();
</code>```

Cannot create a MessageSession for a sub-queue. TrackingId:06a39820-7bf6-412d-ab31-80ef5c174a12_G20_B31, SystemTracker:tomsbservice:Queue: queuename |$DeadLetterQueue

My workaround is that we could get the dead-letter queue message and submit to queue or another normal queue.

Body:
Is there any built in way in azure service bus queue, where I can receive messages only from one session (for that sessionId) in my session handler.

As Sean Feldman mentioned QueueClient.AcceptMessageSessionAsync(sessionID) allows to achieve that for a normal queue.

If want to use QueueClient.AcceptMessageSessionAsync(sessionID) to receive queue message, we need to create the with RequiresSession true,

var description = new QueueDescription(QueueName)
{
    RequiresSession = true
};

namespaceManager.CreateQueue(description);

Also is there any way I can receive messages only from the deadlettered queue for that session alone.

Base on my test we can't get the dead-letter queue message from the deadletter queue with following code

   var dlqName= QueueClient.FormatDeadLetterPath(queueName);
   var dlqClient = QueueClient.CreateFromConnectionString(connectionstring, dfQueue);
   var gid = Guid.NewGuid().ToString();
   var messageSession = client.AcceptMessageSession(gid);
   var receiveMessage = messageSession.Receive();

Cannot create a MessageSession for a sub-queue. TrackingId:06a39820-7bf6-412d-ab31-80ef5c174a12_G20_B31, SystemTracker:tomsbservice:Queue: queuename |$DeadLetterQueue

My workaround is that we could get the dead-letter queue message and submit to queue or another normal queue.


问:
How to render contents in all components using react native?
I want to add header and footer in all pages like below.

Example :

Then how render header and footer in other components ?

That means write code once then how render it in various pages?

答:
i never try that react-native-router-flux, but when i see the docs, maybe you can do something like this:

import React, { Component } from 'react';
import { Router, Scene } from 'react-native-router-flux';

import PageOne from './PageOne';
import PageTwo from './PageTwo';

export default class App extends Component {
  render() {
    return (
      <View style={{ flex:1 }}>
        <YourHeaderComponent />
        <Router>
          <Scene key="root">
            <Scene key="pageOne" component={PageOne} title="PageOne" initial={true} />
            <Scene key="pageTwo" component={PageTwo} title="PageTwo" />
          </Scene>
        </Router>
        <YourFooterComponent />
      </View>
    )
  }
}```

You can wrap the Router with View which its sibling is your header and footer component.

Body:
i never try that react-native-router-flux, but when i see the docs, maybe you can do something like this:

import React, { Component } from 'react';
import { Router, Scene } from 'react-native-router-flux';

import PageOne from './PageOne';
import PageTwo from './PageTwo';

export default class App extends Component {
  render() {
    return (
      <View style={{ flex:1 }}>
        <YourHeaderComponent />
        <Router>
          <Scene key="root">
            <Scene key="pageOne" component={PageOne} title="PageOne" initial={true} />
            <Scene key="pageTwo" component={PageTwo} title="PageTwo" />
          </Scene>
        </Router>
        <YourFooterComponent />
      </View>
    )
  }
}

You can wrap the Router with View which its sibling is your header and footer component.


问:
C# Console Application, search for matching string[] from two text files
I have two text files: animal.txt that has

```<code>number,letter,color,animal
1,a,green,alligator
2,b,brown,bear
3,c,black,cat
4,d,white,dog
5,e,pink,elephant
</code>```

and habit.txt that has

```<code>colour,animal,found,diet
green,alligator,swamp,fish
green,alligator,swamp,bird
brown,bear,forest,fruit
black,cat,home,catfood
white,dog,home,dogfood
pink,elephant,space,spacefruit
</code>```

My code so far asks for a number and a letter. and searches the text file using string[] and split.

```<code>class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        string line;
        string number;
        string letter;
        bool lineFound = false;

        do
        {
            Console.WriteLine("Enter number");
            number = Console.ReadLine();

            Console.WriteLine("\nEnter letter");
            letter = Console.ReadLine();

            System.IO.StreamReader file = new System.IO.StreamReader("animal.txt");
            while ((line = file.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                if ((number == words[1]) && (letter == words[0]))
                {
                    Console.WriteLine(line);
                    lineFound = true;
                }

                counter++;
            }

            if (!lineFound)
            {
                Console.WriteLine("Invalid number and/or letter");
            }

            file.Close();

        }
            while (!lineFound);
</code>```

depending on the input it'll display the line with color and animal.
How do I make it so that it will search another file, habit.txt for matching lines found in animal.txt. for example input can be '1' and 'a' the console will display

```<code>green,alligator,swamp,fish
green,alligator,swamp,bird
</code>```

答:
```<code>String.Contains("some text")
</code>```

I recommend to use a database for you to script desired data rather than a .text file that stands up like a long strings.

Body:
I have two text files: animal.txt that has

number,letter,color,animal
1,a,green,alligator
2,b,brown,bear
3,c,black,cat
4,d,white,dog
5,e,pink,elephant

and habit.txt that has

colour,animal,found,diet
green,alligator,swamp,fish
green,alligator,swamp,bird
brown,bear,forest,fruit
black,cat,home,catfood
white,dog,home,dogfood
pink,elephant,space,spacefruit

My code so far asks for a number and a letter. and searches the text file using string[] and split.

class Program
{
    static void Main(string[] args)
    {
        int counter = 0;
        string line;
        string number;
        string letter;
        bool lineFound = false;

        do
        {
            Console.WriteLine("Enter number");
            number = Console.ReadLine();

            Console.WriteLine("\nEnter letter");
            letter = Console.ReadLine();

            System.IO.StreamReader file = new System.IO.StreamReader("animal.txt");
            while ((line = file.ReadLine()) != null)
            {
                string[] words = line.Split(',');
                if ((number == words[1]) && (letter == words[0]))
                {
                    Console.WriteLine(line);
                    lineFound = true;
                }

                counter++;
            }

            if (!lineFound)
            {
                Console.WriteLine("Invalid number and/or letter");
            }

            file.Close();

        }
            while (!lineFound);

depending on the input it'll display the line with color and animal.
How do I make it so that it will search another file, habit.txt for matching lines found in animal.txt. for example input can be '1' and 'a' the console will display

green,alligator,swamp,fish
green,alligator,swamp,bird

Body:
String.Contains("some text")

I recommend to use a database for you to script desired data rather than a .text file that stands up like a long strings.


问:
Java: Possible to use a single for-loop instead of two?
My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.

```<code>public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];

    for (int arr_i = 0; arr_i < n; arr_i++) {
        arr[arr_i] = in.nextInt();
    }

    for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
        System.out.print(arr[reverse_i]);

        if (reverse_i != 0) {
            System.out.print(" ");
        }
    }
}
</code>```

An example input:

```<code>4
1 2 3 4
</code>```

Expected output:

```<code>4 3 2 1
</code>```

答:
The simplest approach I found is to use String Builder here:</p>

```<code>Scanner in = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
while (in.hasNext()) {
   stringBuilder.append(in.next());
   if(in.hasNext()) {
     stringBuilder.append(" ");
   }
}

System.out.print(stringBuilder.reverse());
</code>```

Body:
My code is as below. It first takes input from user and prints it in reverse. I'm new to Java. I achieve this by using two 'for loops' to first iterate through the input and another for-loop to print the numbers in reverse. My question is if there's any way to improve my code - by using just a single loop perhaps? Any suggestion is appreciated. Thank you.

public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];

    for (int arr_i = 0; arr_i < n; arr_i++) {
        arr[arr_i] = in.nextInt();
    }

    for (int reverse_i = n-1; reverse_i >= 0; reverse_i--) {
        System.out.print(arr[reverse_i]);

        if (reverse_i != 0) {
            System.out.print(" ");
        }
    }
}

An example input:

4
1 2 3 4

Expected output:

4 3 2 1

Body:
The simplest approach I found is to use String Builder here:

Scanner in = new Scanner(System.in);
StringBuilder stringBuilder = new StringBuilder();
while (in.hasNext()) {
   stringBuilder.append(in.next());
   if(in.hasNext()) {
     stringBuilder.append(" ");
   }
}

System.out.print(stringBuilder.reverse());


问:
C++ constexpr reference multiple definition
I'm trying to use a constexpr reference pointer to an external defined object.

hardware.h

```<code>extern int crypticName;
</code>```

hardware.cpp

```<code>#include "hardware.h"
int crypticName;
</code>```

shared.h

```<code>#include "hardware.h"
constexpr int& usefulName = crypticName; // This is the reference I'm interested in
</code>```

main.cpp

```<code>#include "shared.h"
int main() {return 0;}
</code>```

other.cpp

```<code>#include "shared.h"
</code>```

GCC doesn't seem to have a problem with the syntax used. However when the linker tries to bring everything together, I get a multiple definition problem.

```<code>.bld/other.cpp.o:(.rodata.usefulName+0x0): multiple definition of `usefulName'
.bld/main.cpp.o:(.rodata.usefulName+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
</code>```

I'm guessing that the compiler is guessing (or using some placeholder for) some location for crypticName in each compilation unit and loses the extern linkage that normally deals with these issues. So maybe this is expected behavior.

Is there some simple thing I'm missing? Or do I need to change how I'm abstracting my hardware?

One way to "solve" this is to use constexpr int * const usefulName = crypticName instead of the reference assignment. However, I'd prefer to not need to dereference usefulName all the time. After all, one of the points of this abstraction in my use case is to hide the pointer stuff.

Of note, this SO question might be the same.

答:
You can declare usefulName to be static explicitly to force it to have internal linkage:

```<code>static constexpr int& usefulName = crypticName;
</code>```

I'm not sure why it isn't static by default, given that it's constexpr, but explicitly declaring it static seems to fix the problem.

Body:
I'm trying to use a constexpr reference pointer to an external defined object.

hardware.h

extern int crypticName;

hardware.cpp

#include "hardware.h"
int crypticName;

shared.h

#include "hardware.h"
constexpr int& usefulName = crypticName; // This is the reference I'm interested in

main.cpp

#include "shared.h"
int main() {return 0;}

other.cpp

#include "shared.h"

GCC doesn't seem to have a problem with the syntax used. However when the linker tries to bring everything together, I get a multiple definition problem.

.bld/other.cpp.o:(.rodata.usefulName+0x0): multiple definition of `usefulName'
.bld/main.cpp.o:(.rodata.usefulName+0x0): first defined here
collect2.exe: error: ld returned 1 exit status

I'm guessing that the compiler is guessing (or using some placeholder for) some location for crypticName in each compilation unit and loses the extern linkage that normally deals with these issues. So maybe this is expected behavior.

Is there some simple thing I'm missing? Or do I need to change how I'm abstracting my hardware?

One way to "solve" this is to use constexpr int * const usefulName = crypticName instead of the reference assignment. However, I'd prefer to not need to dereference usefulName all the time. After all, one of the points of this abstraction in my use case is to hide the pointer stuff.

Of note, this SO question might be the same.

Body:
You can declare usefulName to be static explicitly to force it to have internal linkage:

static constexpr int& usefulName = crypticName;

I'm not sure why it isn't static by default, given that it's constexpr, but explicitly declaring it static seems to fix the problem.