问:
Static allocation of opaque data types
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

```<code>// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}
</code>```

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

```<code>void create_handle(handle_t *handle);
</code>```

And then the caller could create the handle this way:

```<code>// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}
</code>```

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

答:
The least grim solution I've seen to this has been to provide an opaque struct for the caller's use, which is large enough, plus maybe a bit, along with a mention of the types used in the real struct, to ensure that the opaque struct will be aligned well enough compared to the real one:

```<code>struct Thing {
    union {
        char data[16];
        uint32_t b;
        uint8_t a;
    } opaque;
};
typedef struct Thing Thing;
</code>```

Then functions take a pointer to one of those:

```<code>void InitThing(Thing *thing);
void DoThingy(Thing *thing,float whatever);
</code>```

Internally, not exposed as part of the API, there is a struct that has the true internals:

```<code>struct RealThing {
    uint32_t private1,private2,private3;
    uint8_t private4;
};
typedef struct RealThing RealThing;
</code>```

(This one just has uint32_t' anduint8_t' -- that's the reason for the appearance of these two types in the union above.)

Plus probably a compile-time assert to make sure that RealThing's size doesn't exceed that of Thing:

```<code>typedef char CheckRealThingSize[sizeof(RealThing)<=sizeof(Thing)?1:-1];
</code>```

Then each function in the library does a cast on its argument when it's going to use it:

```<code>void InitThing(Thing *thing) {
    RealThing *t=(RealThing *)thing;

    /* stuff with *t */
}
</code>```

With this in place, the caller can create objects of the right size on the stack, and call functions against them, the struct is still opaque, and there's some checking that the opaque version is large enough.

One potential issue is that fields could be inserted into the real struct that mean it requires an alignment that the opaque struct doesn't, and this won't necessarily trip the size check. Many such changes will change the struct's size, so they'll get caught, but not all. I'm not sure of any solution to this.

Alternatively, if you have a special public-facing header(s) that the library never includes itself, then you can probably (subject to testing against the compilers you support...) just write your public prototypes with one type and your internal ones with the other. It would still be a good idea to structure the headers so that the library sees the public-facing Thing struct somehow, though, so that its size can be checked.

Title: Static allocation of opaque data types

Body:
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

void create_handle(handle_t *handle);

And then the caller could create the handle this way:

// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

Body:
The least grim solution I've seen to this has been to provide an opaque struct for the caller's use, which is large enough, plus maybe a bit, along with a mention of the types used in the real struct, to ensure that the opaque struct will be aligned well enough compared to the real one:

struct Thing {
    union {
        char data[16];
        uint32_t b;
        uint8_t a;
    } opaque;
};
typedef struct Thing Thing;

Then functions take a pointer to one of those:

void InitThing(Thing *thing);
void DoThingy(Thing *thing,float whatever);

Internally, not exposed as part of the API, there is a struct that has the true internals:

struct RealThing {
    uint32_t private1,private2,private3;
    uint8_t private4;
};
typedef struct RealThing RealThing;

(This one just has uint32_t' anduint8_t' -- that's the reason for the appearance of these two types in the union above.)

Plus probably a compile-time assert to make sure that RealThing's size doesn't exceed that of Thing:

typedef char CheckRealThingSize[sizeof(RealThing)<=sizeof(Thing)?1:-1];

Then each function in the library does a cast on its argument when it's going to use it:

void InitThing(Thing *thing) {
    RealThing *t=(RealThing *)thing;

    /* stuff with *t */
}

With this in place, the caller can create objects of the right size on the stack, and call functions against them, the struct is still opaque, and there's some checking that the opaque version is large enough.

One potential issue is that fields could be inserted into the real struct that mean it requires an alignment that the opaque struct doesn't, and this won't necessarily trip the size check. Many such changes will change the struct's size, so they'll get caught, but not all. I'm not sure of any solution to this.

Alternatively, if you have a special public-facing header(s) that the library never includes itself, then you can probably (subject to testing against the compilers you support...) just write your public prototypes with one type and your internal ones with the other. It would still be a good idea to structure the headers so that the library sees the public-facing Thing struct somehow, though, so that its size can be checked.

OwnerDisplayName: please delete me

LastEditorDisplayName: please delete me


来源: stackexchange

问:
Python: Trying to execute command to clear screen if user inputs certain number
I'm trying to remake a terminal from the Fallout series, if any of you know what that is.

Basically, the program shows a bunch of options they can choose from, then they have to input a number (1-5) to select which thing they want to view. The program will use an if statement to determine which thing they want to view. For example, if the user inputted one, then it will clear the screen and print a bunch of information, then the user has to input enter, then the screen clears and the options from the beginning are displayed again. This whole thing is inside a while statement, and while the user input is not "C", it will still display all of that other stuff, and when it does become "C", the program will clear everything and the program ends.

I know all of that sounded confusing, but basically the problem is that if the person inputs a number, it doesn't do the clearing thing, it just displays the choices again.

I'll just display the code, so if anyone could tell me what the problem is, that would greatly be appreciated.

```<code>def confusingFunction():
    from os import system
    userChoice = ""

    while userChoice.upper() != "C":
        print("Choice 1")
        print("Choice 2")
        print("Choice 3")
        print("Choice 4")
        print("Choice 5")
        userChoice = input(">>>")

        if userChoice == 1:
            system('cls')
            print("Stuff")
            print("Stuff")
            print("Stuff")
            input(">>>")
            system('cls')

    system('cls')
    return
</code>```

答:
There is an issue with type conversion. Python takes input as string.
Try the code

if int(userChoice) == 1:

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to remake a terminal from the Fallout series, if any of you know what that is.

Basically, the program shows a bunch of options they can choose from, then they have to input a number (1-5) to select which thing they want to view. The program will use an if statement to determine which thing they want to view. For example, if the user inputted one, then it will clear the screen and print a bunch of information, then the user has to input enter, then the screen clears and the options from the beginning are displayed again. This whole thing is inside a while statement, and while the user input is not "C", it will still display all of that other stuff, and when it does become "C", the program will clear everything and the program ends.

I know all of that sounded confusing, but basically the problem is that if the person inputs a number, it doesn't do the clearing thing, it just displays the choices again.

I'll just display the code, so if anyone could tell me what the problem is, that would greatly be appreciated.

def confusingFunction():
    from os import system
    userChoice = ""

    while userChoice.upper() != "C":
        print("Choice 1")
        print("Choice 2")
        print("Choice 3")
        print("Choice 4")
        print("Choice 5")
        userChoice = input(">>>")

        if userChoice == 1:
            system('cls')
            print("Stuff")
            print("Stuff")
            print("Stuff")
            input(">>>")
            system('cls')

    system('cls')
    return


问:
Sort DRF serializer output of DictField by key
I have a Django Rest Framework serializer that uses a DictField:

```<code>class FlatArticleSerializer(Serializer):
    attributes = DictField(child=FlatArticleAttributeSerializer())
</code>```

The output is all the time different, since the attributes are a dictionary, which is by definition not sorted. Is there a way to sort these in the output nevertheless, alphabetically on string for instance?

答:
Why not use a nested serializer instead? I believe it will sort the keys as dictated by the fields of your serializer:

```<code>class FlatArticleSerializer(Serializer):
    attributes = FlatArticleAttributeSerializer()
</code>```

Body:
I have a Django Rest Framework serializer that uses a DictField:

class FlatArticleSerializer(Serializer):
    attributes = DictField(child=FlatArticleAttributeSerializer())

The output is all the time different, since the attributes are a dictionary, which is by definition not sorted. Is there a way to sort these in the output nevertheless, alphabetically on string for instance?

Body:
Why not use a nested serializer instead? I believe it will sort the keys as dictated by the fields of your serializer:

class FlatArticleSerializer(Serializer):
    attributes = FlatArticleAttributeSerializer()


问:
Dynamic style - Angular
Basivally i have a div ,which i'm putting a dynamic style

```<code><div style="position:relative; left: {{et.getNumPadStyle()}}px">
</code>```

My function getNumPadStyle will have

```<code>function getNumPadStyle {
    var num = "25";
    return num;
}
</code>```

This is giving me an error

```<code>Referencing DOM nodes in Angular expressions is disallowed! Expression: et.getNumPadStyle()
</code>```

And when i inspect the element, the exact number is not reflecting

```<code>element {
    position:relative;
    left:{{et.getNumPadStyle()}}px
}
</code>```

How to resolve this?

答:
Your angular function has to be in scope and called with $scope.getNumPadStyle()

```<code>    $scope.getNumPadStyle = function ()
    {
        var num = "25";
        return num;
    }
</code>```

See it working here: https://jsfiddle.net/AKMorris/nq19be7h/

Title: Dynamic style - Angular

Body:
Basivally i have a div ,which i'm putting a dynamic style

My function getNumPadStyle will have

function getNumPadStyle {
    var num = "25";
    return num;
}

This is giving me an error

Referencing DOM nodes in Angular expressions is disallowed! Expression: et.getNumPadStyle()

And when i inspect the element, the exact number is not reflecting

element {
    position:relative;
    left:{{et.getNumPadStyle()}}px
}

How to resolve this?

Body:
Your angular function has to be in scope and called with $scope.getNumPadStyle()

    $scope.getNumPadStyle = function ()
    {
        var num = "25";
        return num;
    }

See it working here: https://jsfiddle.net/AKMorris/nq19be7h/


问:
TestBed configureTestingModule define imports, declarations, providers, and pipes common to all spec.ts in one Module - pattern
Is there a optimal way to define imports, declarations, providers common to all spec.ts  (i.e modules common to all specs one place define like we do it in @NgModule) in one place like we do in @NgModule for application Unit tests.

Note : Call configureTestingModule within a beforeEach so that TestBed can reset itself to a base state before each test runs. as on doc

Here in one of my test spec.ts i have to load same modules components and directives ..etc which is used by some other spec too.

```<code>describe('Component: Login', () => {
let loginFixture, loginComponent, loginComponentElement,loginComponentDebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
  imports: [FormsModule, ReactiveFormsModule, MaterialRootModule, ModalModule, DatepickerModule,
    DropdownModule, AccordionModule], //--> here we load n number of mudoles
  declarations: [LoginComponent, LoginHeaderComponent, LoginColumnComponent, LoginColumnContentComponent,
    LoginStatusLaneComponent, LoginSettingsComponent,
    LoginLaneComponent, SortableDirective, WindowHeightDirective, ConfirmDirective, ConfirmPopoverComponent, ConfirmationDialogComponent,
    ConfirmationDialogDirective],         //--> here we load n number of components directive and piper
  providers: [LoginComponent,
    MockBackend,
    BaseRequestOptions,
    ComponentLoaderFactory,
    ConfirmOptions,
    {
      provide: Http,
      useFactory: (backend, options) => new Http(backend, options),
      deps: [MockBackend, BaseRequestOptions]
    },
    {provide: AuthService, useClass: MockAuthService},
    {provide: AppContextService, useClass: MockAppContextService},
    {provide: NotificationsService, useClass: MockNotificationsService},
    {provide: PositioningService}]       //--> here we load n number of services
}).compileComponents();
loginFixture = TestBed.createComponent(LoginComponent);
loginComponent = loginFixture.componentInstance;
loginComponentElement = LoginFixture.nativeElement;
loginComponentDebugElement = LoginFixture.debugElement;
}));

 it('should have a defined component', () => {
expect(LoginComponent).toBeDefined();
});
});
</code>```

Note : Git Angular issue TestBed.configureTestingModule Performance Issue

Is there any pattern to make it common like loading all this modules components etc in starting  before running all spec.ts file and inject respective dependency for each specs . Any help would be great.

答:
My answer is incomplete you have come to expect.
But I hope if it can help you even a little.

router-stubs.ts

```<code>//----------Default Import------------
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
...snip...
export const test_imports = [
               BrowserModule,
               FormsModule,
               HttpModule,
               BrowserAnimationsModule
             ];
</code>```

each test.spec.ts

```<code>import { test_imports }   from '../testing/router-stubs';
..snip..
      imports: [test_imports],
</code>```

but providers/declarations can't use in the same way.

Body:
Is there a optimal way to define imports, declarations, providers common to all spec.ts  (i.e modules common to all specs one place define like we do it in @NgModule) in one place like we do in @NgModule for application Unit tests.

Note : Call configureTestingModule within a beforeEach so that TestBed can reset itself to a base state before each test runs. as on doc

Here in one of my test spec.ts i have to load same modules components and directives ..etc which is used by some other spec too.

describe('Component: Login', () => {
let loginFixture, loginComponent, loginComponentElement,loginComponentDebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
  imports: [FormsModule, ReactiveFormsModule, MaterialRootModule, ModalModule, DatepickerModule,
    DropdownModule, AccordionModule], //--> here we load n number of mudoles
  declarations: [LoginComponent, LoginHeaderComponent, LoginColumnComponent, LoginColumnContentComponent,
    LoginStatusLaneComponent, LoginSettingsComponent,
    LoginLaneComponent, SortableDirective, WindowHeightDirective, ConfirmDirective, ConfirmPopoverComponent, ConfirmationDialogComponent,
    ConfirmationDialogDirective],         //--> here we load n number of components directive and piper
  providers: [LoginComponent,
    MockBackend,
    BaseRequestOptions,
    ComponentLoaderFactory,
    ConfirmOptions,
    {
      provide: Http,
      useFactory: (backend, options) => new Http(backend, options),
      deps: [MockBackend, BaseRequestOptions]
    },
    {provide: AuthService, useClass: MockAuthService},
    {provide: AppContextService, useClass: MockAppContextService},
    {provide: NotificationsService, useClass: MockNotificationsService},
    {provide: PositioningService}]       //--> here we load n number of services
}).compileComponents();
loginFixture = TestBed.createComponent(LoginComponent);
loginComponent = loginFixture.componentInstance;
loginComponentElement = LoginFixture.nativeElement;
loginComponentDebugElement = LoginFixture.debugElement;
}));

 it('should have a defined component', () => {
expect(LoginComponent).toBeDefined();
});
});

Note : Git Angular issue TestBed.configureTestingModule Performance Issue

Is there any pattern to make it common like loading all this modules components etc in starting  before running all spec.ts file and inject respective dependency for each specs . Any help would be great.

Body:
My answer is incomplete you have come to expect.
But I hope if it can help you even a little.

router-stubs.ts

//----------Default Import------------
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
...snip...
export const test_imports = [
               BrowserModule,
               FormsModule,
               HttpModule,
               BrowserAnimationsModule
             ];

each test.spec.ts

import { test_imports }   from '../testing/router-stubs';
..snip..
      imports: [test_imports],

but providers/declarations can't use in the same way.


问:
Code Sign Error in macOS Monterey, Xcode - resource fork, Finder information, or similar detritus not allowed
Already tried : Code Sign Error on macOS Sierra, Xcode 8

Please see image showing error

```<code>CodeSign /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app
    cd "/Volumes/Development/Project/Top Best Games/19. Lets Flow/35/let's FLOW - source/proj.ios_mac"
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "iPhone Distribution: New Free Games (2CHN583K4J)"
Provisioning Profile: "Super Flow Flipp AppStore"
                      (c6c30d2a-1025-4a23-8d12-1863ff684a05)

    /usr/bin/codesign --force --sign E48B98966150110E55EAA9B149F731901A41B37F --entitlements /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Intermediates/Flow.build/Debug-iphoneos/Super\ Flow\ Flip.build/Super\ Flow\ Flip.app.xcent --timestamp=none /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app

/Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super Flow Flip.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1
</code>```

In Code Sign section its allowing me to select profile and certificate...but still giving error.

How to fix this problem ?

答:
My problem is every change I make in the code and execute again the error reappears. Then I find a solution to execute the command automatically every compilation/execution of code.

Thanks to @rich-able I discovered "Run Script". Then I put the command "xattr -cr ." in the field.

ContentLicense: CC BY-SA 4.0

Body:
Already tried : Code Sign Error on macOS Sierra, Xcode 8

Please see image showing error

CodeSign /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app
    cd "/Volumes/Development/Project/Top Best Games/19. Lets Flow/35/let's FLOW - source/proj.ios_mac"
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "iPhone Distribution: New Free Games (2CHN583K4J)"
Provisioning Profile: "Super Flow Flipp AppStore"
                      (c6c30d2a-1025-4a23-8d12-1863ff684a05)

    /usr/bin/codesign --force --sign E48B98966150110E55EAA9B149F731901A41B37F --entitlements /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Intermediates/Flow.build/Debug-iphoneos/Super\ Flow\ Flip.build/Super\ Flow\ Flip.app.xcent --timestamp=none /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app

/Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super Flow Flip.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1

In Code Sign section its allowing me to select profile and certificate...but still giving error.

How to fix this problem ?


问:
Java io library: What is the difference between File.toString() and File.getPath()
... since it seems that both returns the same string - take a look at this Scala code:</p>

```<code>scala> val f = new File("log.txt")
scala> f.getPath
// res6: String = log
scala> f.toString
// res7: String = log
</code>```

答:
If you look at java.io.file toString function actually calls path's getter.</p>

```<code>public String toString() {
    return getPath();
}
</code>```

Body:
... since it seems that both returns the same string - take a look at this Scala code:

scala> val f = new File("log.txt")
scala> f.getPath
// res6: String = log
scala> f.toString
// res7: String = log

Body:
If you look at java.io.file toString function actually calls path's getter.

public String toString() {
    return getPath();
}


问:
Java 8: Can we use map to make an instance method ref in a stream?
I'm trying to refactor some of my code to Java 8. Is it possible to make an instance method ref to a method that takes 2 params with map method in streams? Below is my code.

```<code>for (SubjectAreaMappings pageFromEnum : SubjectAreaMappings.values()) {
    if (page.equals(pageFromEnum.toString())) {
        for (SubjectAreaCode subjectAreaCode : pageFromEnum.getCodes()) {
            list.addAll(areaDAO.getData(context, subjectAreaCode));
        }
    }
}
</code>```

I'm trying to refactor the inner for loop to something like the following code, but is it map() that I should be using or reduce()? How can I pass the 2 params context and subjectAreaCode?

```<code>Arrays.asList(pageFromEnum.getCode()).stream().map(somethng wrt method ref here).collect(toList())
</code>```

答:
reduce() is not an alternative to map(). It is an alternative to collect(). In your example you are collecting the processed elements to a List, so you should use collect().

You cannot pass explicit parameters to method references. Therefore you should use a lambda expression in this scenario:

```<code>Arrays.asList(pageFromEnum.getCodes()).stream().map(code -> areaDAO.getData(context, code)).collect(toList());
</code>```

BTW, your Stream pipeline seems to only replace the inner for loop. You could write a Stream pipeline to replace both the outer and inner loops:

```<code>list =
    Arrays.stream(SubjectAreaMappings.values())
          .filter(s -> page.equals(s.toString()))
          .flatMap(s -> Arrays.stream(s.getCodes())
                              .map(code -> areaDAO.getData(context, code)))
          .collect(toList());
</code>```

Body:
I'm trying to refactor some of my code to Java 8. Is it possible to make an instance method ref to a method that takes 2 params with map method in streams? Below is my code.

for (SubjectAreaMappings pageFromEnum : SubjectAreaMappings.values()) {
    if (page.equals(pageFromEnum.toString())) {
        for (SubjectAreaCode subjectAreaCode : pageFromEnum.getCodes()) {
            list.addAll(areaDAO.getData(context, subjectAreaCode));
        }
    }
}

I'm trying to refactor the inner for loop to something like the following code, but is it map() that I should be using or reduce()? How can I pass the 2 params context and subjectAreaCode?

Arrays.asList(pageFromEnum.getCode()).stream().map(somethng wrt method ref here).collect(toList())

Body:
reduce() is not an alternative to map(). It is an alternative to collect(). In your example you are collecting the processed elements to a List, so you should use collect().

You cannot pass explicit parameters to method references. Therefore you should use a lambda expression in this scenario:

Arrays.asList(pageFromEnum.getCodes()).stream().map(code -> areaDAO.getData(context, code)).collect(toList());

BTW, your Stream pipeline seems to only replace the inner for loop. You could write a Stream pipeline to replace both the outer and inner loops:

list =
    Arrays.stream(SubjectAreaMappings.values())
          .filter(s -> page.equals(s.toString()))
          .flatMap(s -> Arrays.stream(s.getCodes())
                              .map(code -> areaDAO.getData(context, code)))
          .collect(toList());


问:
SSRS Export to Excel results in (500) Server Error
I have an SSRS report (SSRS 2012) that when I try to export to Excel, always crashes after a minute or so with a 500 server error.

The report itself runs successfully.  And I can successfully export the result to CSV, which actually only takes a few seconds to do after the report itself has rendered.

I am experiencing this on result sets greater than around 20000 records; my current example has 36000 records - it crashes the Excel export but the CSV export is successful.

I've tried checking the SSRS logs (C:\Program Files\Microsoft SQL Server\MSRS11.SQL2012\Reporting Services\LogFiles) no errors are shown in there, just a couple entries for RenderForNewSession and RenderFromSession pointing to my report.

The Event Viewer Application log shows a Warning entry for ASP.NET 2.0:

Exception information:
    Exception type: COMException
    Exception message: This network connection does not exist. (Exception from HRESULT: 0x800708CA)

Is there any place else I might find useful debugging information? I'd really rather not have to direct the client to "not export large reports to Excel, use CSV instead" if I don't have to. Or are there any known issues or quirks when exporting to Excel from the SSRS web report viewer?

EDIT:

After some further digging, I've found some more info but have yet to find an actual solution.  I did find where I could turn up the debugging level in the logs - in the ReportingSErvicesService.exe.config file there are two settings, DefaultTraceSwitch and Components underneath an RSTrace tag. They have default values of 3 but bumping each to 4 provides what appears to be a verbose logging output.

That was interesting, but didn't really point me to anything new other than confirming that it looks like the client execution is timing out.

Next I've come across a TechNet article that at least seems to describe the various places I might be able to set an SSRS timeout.  From what I can tell it seems like the Excel export renderer is hitting an execution timeout somewhere, but all of the SSRS settings appear to cover plenty of headroom for running anything.

Should the web.config httpRuntime executionTimeout setting override the machine.config settings? The TechNet article implies that the machine.config settings seems to line up with the timeout I'm seeing when exporting, but the ReportServer web.config has an executionTimeout setting much larger than the ASP.NET default setting.

答:
a conflation of ideas, but this is often a problem in SSRS 2008r2

As for SSRS2012 - there are two excel export formats

```<code>Version of SSRS      Render format name to use
2008 R2              EXCEL
2012                 EXCELOPENXML
</code>```

Is it possible that you're opening the 2008r2 version? (which has a 65K row limit).  if so, you can turn off this option in the ssrs config on the server (but will turn it off for all reports)

With 36K rows you shouldn't have this issue, even in EXCEL (2008r2) export, but is there any possibility you're outputting 2 rows for each result?

Body:
a conflation of ideas, but this is often a problem in SSRS 2008r2

As for SSRS2012 - there are two excel export formats

Version of SSRS      Render format name to use
2008 R2              EXCEL
2012                 EXCELOPENXML

Is it possible that you're opening the 2008r2 version? (which has a 65K row limit).  if so, you can turn off this option in the ssrs config on the server (but will turn it off for all reports)

With 36K rows you shouldn't have this issue, even in EXCEL (2008r2) export, but is there any possibility you're outputting 2 rows for each result?


问:
Android, get value from firebase database
I need to add markers from all users on my map. I'm saving all coordinates in my firebase

My database looks like:

So, when I want to get values: lat, lng from database(I do it in onMapReady method):

```<code>int allUsers = 100;
    while(allUsers >= 0) {
        double latAll = Double.parseDouble(users.child("lat").toString());
        double lngAll = Double.parseDouble(users.child("lng").toString());
        mMap.addMarker(new MarkerOptions().position(new LatLng(latAll, lngAll)));
    }
</code>```

I get an error

Here i'm saving values ito my database:

```<code>GPSTracker gpstracker = new GPSTracker(mContext, SearchActivity.this);
                double locationLng = gpstracker.getLongitude();
                double locationLat = gpstracker.getLatitude();

                databaseReference.child("lng").setValue(locationLng);
                databaseReference.child("lat").setValue(locationLat);
</code>```

here is my error:

FATAL EXCEPTION: main
                                                   Process: kz.mul.livemeet_finalversion, PID: 24598
                                                   java.lang.NumberFormatException: For input string: "https://livemeetfinalversion.firebaseio.com/ekeLu1W_1RU%3AAPA91bFt2knzJYknyWLpuFb1Wm1nxl0TkM-bWdkNrjaoPUmv5JP_hm6b64Hx3m3X805A3QR8paMAOABJN6DZcb99z_EfwGwadN1dUN6ngtqTbGwxD6iMLlP7IW6RvEzg9UTW7HQKHyT0/lat"
                                                       at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1306)
                                                       at java.lang.Double.parseDouble(Double.java:547)
                                                       at kz.mul.livemeet_finalversion.MapsActivity.onMapReady(MapsActivity.java:118)
                                                       at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
                                                       at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
                                                       at android.os.Binder.transact(Binder.java:499)
                                                       at com.google.android.gms.maps.internal.bw.a(:com.google.android.gms.DynamiteModulesB:82)
                                                       at com.google.maps.api.android.lib6.impl.bf.run(:com.google.android.gms.DynamiteModulesB:1805)
                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

答:
Step 1) Make a PoJo.class which contains all the keys that are in database in you case like age,lat,lng etc.

Step 2) Now call this method for getting all the data.like below

```<code>    public void getAllUsersFromFirebase() {
    DatabaseReference UserRef = FirebaseDatabase.getInstance().getReference().child("Parent_child");
    UserRef.keepSynced(true);
    UserRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
            List<PoJo> fcmUsers = new ArrayList<>();
            while (dataSnapshots.hasNext()) {
                DataSnapshot dataSnapshotChild = dataSnapshots.next();
                PoJo fcmUser = dataSnapshotChild.getValue(PoJo.class);
                fcmUsers.add(fcmUser);

            }

            // Check your arraylist size and pass to list view like
            if(fcmUsers.size()>0)
            {
                fcmUsers arraylist pass to your Map activity.

            }else
            {
                // Display dialog for there is no user available.
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
                // for handling database error
        }
    });
}
</code>```

Body:
I need to add markers from all users on my map. I'm saving all coordinates in my firebase

My database looks like:

So, when I want to get values: lat, lng from database(I do it in onMapReady method):

int allUsers = 100;
    while(allUsers >= 0) {
        double latAll = Double.parseDouble(users.child("lat").toString());
        double lngAll = Double.parseDouble(users.child("lng").toString());
        mMap.addMarker(new MarkerOptions().position(new LatLng(latAll, lngAll)));
    }

I get an error

Here i'm saving values ito my database:

GPSTracker gpstracker = new GPSTracker(mContext, SearchActivity.this);
                double locationLng = gpstracker.getLongitude();
                double locationLat = gpstracker.getLatitude();

                databaseReference.child("lng").setValue(locationLng);
                databaseReference.child("lat").setValue(locationLat);

here is my error:

FATAL EXCEPTION: main
                                                   Process: kz.mul.livemeet_finalversion, PID: 24598
                                                   java.lang.NumberFormatException: For input string: "https://livemeetfinalversion.firebaseio.com/ekeLu1W_1RU%3AAPA91bFt2knzJYknyWLpuFb1Wm1nxl0TkM-bWdkNrjaoPUmv5JP_hm6b64Hx3m3X805A3QR8paMAOABJN6DZcb99z_EfwGwadN1dUN6ngtqTbGwxD6iMLlP7IW6RvEzg9UTW7HQKHyT0/lat"
                                                       at java.lang.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1306)
                                                       at java.lang.Double.parseDouble(Double.java:547)
                                                       at kz.mul.livemeet_finalversion.MapsActivity.onMapReady(MapsActivity.java:118)
                                                       at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
                                                       at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
                                                       at android.os.Binder.transact(Binder.java:499)
                                                       at com.google.android.gms.maps.internal.bw.a(:com.google.android.gms.DynamiteModulesB:82)
                                                       at com.google.maps.api.android.lib6.impl.bf.run(:com.google.android.gms.DynamiteModulesB:1805)
                                                       at android.os.Handler.handleCallback(Handler.java:751)
                                                       at android.os.Handler.dispatchMessage(Handler.java:95)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Body:
Step 1) Make a PoJo.class which contains all the keys that are in database in you case like age,lat,lng etc.

Step 2) Now call this method for getting all the data.like below

    public void getAllUsersFromFirebase() {
    DatabaseReference UserRef = FirebaseDatabase.getInstance().getReference().child("Parent_child");
    UserRef.keepSynced(true);
    UserRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
            List<PoJo> fcmUsers = new ArrayList<>();
            while (dataSnapshots.hasNext()) {
                DataSnapshot dataSnapshotChild = dataSnapshots.next();
                PoJo fcmUser = dataSnapshotChild.getValue(PoJo.class);
                fcmUsers.add(fcmUser);

            }

            // Check your arraylist size and pass to list view like
            if(fcmUsers.size()>0)
            {
                fcmUsers arraylist pass to your Map activity.

            }else
            {
                // Display dialog for there is no user available.
            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
                // for handling database error
        }
    });
}


问:
Not allowed to load local resource: file:///C://abc.png
1atable(jquery) i want to show image in column but it is giving me a error Not allowed to load local resource:even file path is correct  </p>

```<code>var UserTable = $('.Users_Detail').DataTable({
  data: JsonData,
  columns: [{
      render: function(data, type, row) {
        return '<input type="radio" name="SelectRow" value="' + row.USER_ID + '"  style="margin-left:15px;" class="CheckedRow">';
      },
    },
    {
      "data": "USER_NAME"
    },
    {
      "data": "CISRMNM"
    },
    {
      "data": "CISRMDESIG"
    },
    {
      "data": "EMAIL_ID"
    },
  ],
  "columnDefs": [{
      "width": "5%",
      "targets": 0
    },
    {
      "targets": 6,
      "data": "img",
      "render": function(data, type, row) {
        return '<img  src="C:\\Users\\Images\\tick.png"/ >'
      }
    }
  ],
});
</code>```

答:
You can't load local resources into your web application you need to place them into your server directory first try saving all the resources into the application directory and then load them using relative path.

https://www.w3schools.com/html/html_filepaths.asp

Body:
1atable(jquery) i want to show image in column but it is giving me a error Not allowed to load local resource:even file path is correct

var UserTable = $('.Users_Detail').DataTable({
  data: JsonData,
  columns: [{
      render: function(data, type, row) {
        return '<input type="radio" name="SelectRow" value="' + row.USER_ID + '"  style="margin-left:15px;" class="CheckedRow">';
      },
    },
    {
      "data": "USER_NAME"
    },
    {
      "data": "CISRMNM"
    },
    {
      "data": "CISRMDESIG"
    },
    {
      "data": "EMAIL_ID"
    },
  ],
  "columnDefs": [{
      "width": "5%",
      "targets": 0
    },
    {
      "targets": 6,
      "data": "img",
      "render": function(data, type, row) {
        return ''
      }
    }
  ],
});


问:
Formatting a string into columns using String Interpolation
I need to print doubles so that definite number of symbols (like 8) is allocated for string representation of value. Next words should start at same index from beginning of string in each string. Now I have:

```<code>value: 0 test
value: 0.3333333333333 test
value: 0.5 test
</code>```

I need:

```<code>value: 0           test
value: 0.33333333  test
value: 0.5         test
</code>```

Test code:

```<code>double[] ar = new double[] { 0, (double)1 / 3, (double)1 / 2 };
string s = "test";

foreach (var d in ar)
{
    Console.WriteLine($"value: {d} {s}");
}
</code>```

What should I add after {d:?

答:
You can use Alignment Component for this purpose. Like this:

```<code>Console.WriteLine($"value: {d,-17} {s}");
</code>```

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

So this is why we use negative alignment because you want the first column be left-aligned.

Body:
I need to print doubles so that definite number of symbols (like 8) is allocated for string representation of value. Next words should start at same index from beginning of string in each string. Now I have:

value: 0 test
value: 0.3333333333333 test
value: 0.5 test

I need:

value: 0           test
value: 0.33333333  test
value: 0.5         test

Test code:

double[] ar = new double[] { 0, (double)1 / 3, (double)1 / 2 };
string s = "test";

foreach (var d in ar)
{
    Console.WriteLine($"value: {d} {s}");
}

What should I add after {d:?

Body:
You can use Alignment Component for this purpose. Like this:

Console.WriteLine($"value: {d,-17} {s}");

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

So this is why we use negative alignment because you want the first column be left-aligned.


问:
Making multiple rest client calls
I'm trying to make multiple client calls using org.apache.wink.client.RestClient to a service with Basic Auth.

The first PUT i get status code of 200 but then i get a connection timed out.

I tried re-creating the client each time i'm going to make the new put.

Here's my code:

```<code>for (int pos = 0; pos < jsonsToSend.size(); pos++) {
        BasicAuthSecurityHandler secHandler = new BasicAuthSecurityHandler();
        ClientConfig config = new ClientConfig();
        secHandler.setUserName(username);
        secHandler.setPassword(password);
        config.handlers(secHandler);

        RestClient client = new RestClient(config);
        Resource resource = client.resource(url);

        actualJson = JSONObject.parse(jsonsToSend.get(pos).toString());
        response = putJson(actualJson, resource);
    }
</code>```

This is the putJson method:

```<code>private ClientResponse putJson(JSONObject jsonSend, Resource resource) throws Exception {
    try {
        ClientResponse response = resource.contentType("text/plain; charset=utf-8").accept("*/*").put(jsonSend.toString());
        return response;
    } catch (Exception e) {
        throw e;
    }
}
</code>```

Do you know how to make multiple rest calls?

答:
Yes you could. Here is how I did:
Service Layer:
...
//First one
ResponseEntity> firstResponse = firstClient.createEntity(requestPayload1);

//Second one
ResponseEntity> secondResponse = secondClient.createEntity(requestPayload2);

Both could pass same requestPayload object.

So, you need to have two clients (if you don't want to change the builder each time dynamically)

I assume you know how to create the client already. In my case, I used  restTemplate.getUriTemplateHandler() to create the URI, then RequestEntity and ParameterizedTypeReference to exchange.

If you are not doing any transactional work, I would think calling in order as I did would be OK.

Title: Making multiple rest client calls

Body:
I'm trying to make multiple client calls using org.apache.wink.client.RestClient to a service with Basic Auth.

The first PUT i get status code of 200 but then i get a connection timed out.

I tried re-creating the client each time i'm going to make the new put.

Here's my code:

for (int pos = 0; pos < jsonsToSend.size(); pos++) {
        BasicAuthSecurityHandler secHandler = new BasicAuthSecurityHandler();
        ClientConfig config = new ClientConfig();
        secHandler.setUserName(username);
        secHandler.setPassword(password);
        config.handlers(secHandler);

        RestClient client = new RestClient(config);
        Resource resource = client.resource(url);

        actualJson = JSONObject.parse(jsonsToSend.get(pos).toString());
        response = putJson(actualJson, resource);
    }

This is the putJson method:

private ClientResponse putJson(JSONObject jsonSend, Resource resource) throws Exception {
    try {
        ClientResponse response = resource.contentType("text/plain; charset=utf-8").accept("*/*").put(jsonSend.toString());
        return response;
    } catch (Exception e) {
        throw e;
    }
}

Do you know how to make multiple rest calls?


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
Jimmy has it right, when you want to be able to use a single variable for multiple types, but all of those types implement the same method via an interface declaration.  Then you can call them main method on the interface typed variable.

There's a second reason to use interfaces, however.  When the project architect is a different person than the implementation coder, or there are several implementation coders and one project manager.  The person in charge can write a whole bunch of interfaces and see that the system interoperates, and then leave it to the developers to fill in the interfaces with implementation classes.  This is the best way to ensure multiple people write compatible classes, and they can do it in parallel.

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ALassek

OwnerDisplayName: Karl


问:
Using a simple scanner, reading a string with spaces, how come .trim() method isn't working?
```<code>import java.util.Scanner;
import java.lang.String;

public class Test
{
    public static void main(String[] args)
    {
        char[] sArray;

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Palindrome : ");
        String s = scan.nextLine();
        s = s.trim();

        sArray = new char[s.length()];

        for(int i = 0; i < s.length(); i++)
        {
            sArray[i] = s.charAt(i);
            System.out.println(sArray[i]);
        }
    }
}
</code>```

答:
Trim doesn't work how you expect it to.  trim() only removes whitespace from the ends of the string.

The documentation for trim():

Returns a copy of the string, with leading and trailing whitespace omitted.

To remove all whitespace try the following instead of calling trim():

```<code>s = s.replaceAll("\\s+", "");
</code>```

This uses a very simple regular expression to remove all whitespace anywhere in the string.

Body:
Trim doesn't work how you expect it to.  trim() only removes whitespace from the ends of the string.

The documentation for trim():

Returns a copy of the string, with leading and trailing whitespace omitted.

To remove all whitespace try the following instead of calling trim():

s = s.replaceAll("\\s+", "");

This uses a very simple regular expression to remove all whitespace anywhere in the string.


问:
Will a VB6 Application run on Windows 10
We have an legacy application(VB,.NET 2.0, Vs2005 COM dlls)  that runs fine on window 7, now what kind of issue can we forsee if we were to move to windows 10,
i was reading this link

and in that it is mentioned that "Your app must not take a dependency on the VB6 runtime" but again in this link it is mentioned that it supports

my question is, am i looking into the correct document or can anyone share the correct link

答:
I created a new VB6 exe on Windows 7, which uses the WebBrowser control.  Then copied only my new exe to a new Windows 10 trial I setup. (Did not copy any DLLs, etc..  my exe only).

Ran my VB6 program/exe on Windows 10, and it worked! It loaded a web page using the (I guess) latest Windows 10 WebBrowser control.

So at least I know I can develop VB6 WebBrowser stuff on Windows 7, and my exe works on Windows 10...

Please verify, thanks.  :-)


问:
HTML5 Pattern for writing name
Pattern for writing name in HTML5

I wrote below pattern but it's not working for me.

[A-Za-z]+\s?

I want a pattern that accept the name with below functionalities

Start with a letter.

Can contain only first name.

Can contain multiple names (first middle last).

Should contain only one space among names if multiple.

Should not contain space at the end and last of input field.

答:
For 1, 2 and 5: use the ^(start of line) and $(end of line) pattern

^[A-Za-z]+$ matches a set of characters with no space(first name in this case)

For 3 and 4: use groups and repitition

(\s[A-Za-z]+) matches a single space followed by any number of characters(space followed by middle / last names) -- Group.

Since there could be 0 to 2 such occurences(Only First, First & Last(?), First, Middle and Last), this changes to (\s[A-Za-z]+){0,2} -- Repitition

Combining these will give the expression you need: ^[A-Za-z]+(\s[A-Za-z]+){0,2}$

Title: HTML5 Pattern for writing name


问:
Reading Mails from Outlook Javamail
Am trying to read the emails from the outlook using javamail

herez the code snippet.

```<code>try {
      Properties props = new Properties();
      props.setProperty("mail.store.protocol", "imap");
      props.setProperty("mail.imaps.starttls.enable", "true");
      props.setProperty("mail.imaps.host", "outlook.office365.com");
      props.setProperty("mail.imaps.port", "143");
      Session mailSession = Session.getInstance(props);
      mailSession.setDebug(true);
      Store mailStore = mailSession.getStore("imaps");
      mailStore.connect("outlook.office365.com", "<username>", "<password>");
  } catch (Exception ex){
      ex.printStackTrace();
  }
</code>```

Exception

javax.mail.MessagingException: Unrecognized SSL message, plaintext connection?;
  nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:727)

Any pointers are appreciated.

答:
Your code is very confused.  Keep it simple:

```<code>  Properties props = new Properties();
  props.setProperty("mail.imap.ssl.enable", "true");
  Session mailSession = Session.getInstance(props);
  mailSession.setDebug(true);
  Store mailStore = mailSession.getStore("imap");
  mailStore.connect("outlook.office365.com", "<username>", "<password>");
</code>```

Use the "imap" protocol, but tell JavaMail to enable SSL.  Don't worry about ports, JavaMail knows what to do.  More detail in the JavaMail FAQ.

Title: Reading Mails from Outlook Javamail

Body:
Am trying to read the emails from the outlook using javamail

herez the code snippet.

try {
      Properties props = new Properties();
      props.setProperty("mail.store.protocol", "imap");
      props.setProperty("mail.imaps.starttls.enable", "true");
      props.setProperty("mail.imaps.host", "outlook.office365.com");
      props.setProperty("mail.imaps.port", "143");
      Session mailSession = Session.getInstance(props);
      mailSession.setDebug(true);
      Store mailStore = mailSession.getStore("imaps");
      mailStore.connect("outlook.office365.com", "<username>", "<password>");
  } catch (Exception ex){
      ex.printStackTrace();
  }

Exception

javax.mail.MessagingException: Unrecognized SSL message, plaintext connection?;
  nested exception is:
    javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:727)

Any pointers are appreciated.

Body:
Your code is very confused.  Keep it simple:

  Properties props = new Properties();
  props.setProperty("mail.imap.ssl.enable", "true");
  Session mailSession = Session.getInstance(props);
  mailSession.setDebug(true);
  Store mailStore = mailSession.getStore("imap");
  mailStore.connect("outlook.office365.com", "<username>", "<password>");

Use the "imap" protocol, but tell JavaMail to enable SSL.  Don't worry about ports, JavaMail knows what to do.  More detail in the JavaMail FAQ.


问:
Python: Trying to execute command to clear screen if user inputs certain number
I'm trying to remake a terminal from the Fallout series, if any of you know what that is.

Basically, the program shows a bunch of options they can choose from, then they have to input a number (1-5) to select which thing they want to view. The program will use an if statement to determine which thing they want to view. For example, if the user inputted one, then it will clear the screen and print a bunch of information, then the user has to input enter, then the screen clears and the options from the beginning are displayed again. This whole thing is inside a while statement, and while the user input is not "C", it will still display all of that other stuff, and when it does become "C", the program will clear everything and the program ends.

I know all of that sounded confusing, but basically the problem is that if the person inputs a number, it doesn't do the clearing thing, it just displays the choices again.

I'll just display the code, so if anyone could tell me what the problem is, that would greatly be appreciated.

```<code>def confusingFunction():
    from os import system
    userChoice = ""

    while userChoice.upper() != "C":
        print("Choice 1")
        print("Choice 2")
        print("Choice 3")
        print("Choice 4")
        print("Choice 5")
        userChoice = input(">>>")

        if userChoice == 1:
            system('cls')
            print("Stuff")
            print("Stuff")
            print("Stuff")
            input(">>>")
            system('cls')

    system('cls')
    return
</code>```

答:
If anyone needs the entire, actual code, here you go...`

```<code>locked = False
#Define Function
def accessGranted():
    import time
    from os import system
    userChoice = ""
    while userChoice.upper() != "C":
        print("Welcome to BunkerSoft Corporations(TM) Terminal\nClearance: Overseer Eyes Only\nBy using this terminal, you are acknowledging that you are an authorized user or technician. Unauthorized users must cease reading and log out of this terminal immediately. Violators will be subject to civil and criminal penalties.\n")
        time.sleep(0.1)
        print("1. [BUNKER 012 OVERSEER INSTRUCTIONS]")
        time.sleep(0.1)
        print("2. [Overseer Logs]")
        time.sleep(0.1)
        print("3. [Experiments]")
        time.sleep(0.1)
        print("4. [Lab]")
        time.sleep(0.1)
        print("5. [Cache]\n")
        time.sleep(0.1)
        userChoice = input(">>>")
        while userChoice == 1:
            system('cls')
            print("Welcome to BunkerSoft Corporations(TM)
Terminal\nClearance: Overseer Eyes Only\n")
            print("CONFIDENTIAL CONFIDENTIAL CONFIDENTIAL\nOVERSEER EYES ONLY | VIOLATION BST&A-01001\n")
            print("Bunker 012 is designed to research infectious diseases on various lifeforms, including human beings, with particular attention paid to potential mutations in a climate of heavy radiation, with an eventual hope to discover a cure and immunity to this cancerous .")
        print("Due to long-term exposure to post-nuclear gamma radiation, infected lifeforms have had their brains permenantly damaged, resulting in complete loss of normal reasoning capabilities and higher thought processes, becoming more animalistic, impulsive, and hostile to anything.")
        print("As of the post-nuclear sealment of this bunker, you are aware of the Bunkers two sections. The main section is where a total of 128 Bunker residents can live in for the foreseeable future, and the secret closed off section of the Bunker, with a Bunker door designed not to close properly. This will be where main testing of the effects of gamma radiation will be conducted.")
        print("Clinical trials are a vital part of Bunker 012's mission. Trials will be performed in three stages: Firstly, live specimens from outside the bunker will be held captive to study their neurogical and physical subconcious. Secondly, Bunker residents will be asked to enter the vault for screening, where they will unknowingly be exposed to different diseases and cures for the radiation poisoning via propellant nozzles that the resident should suspect is the cleansing spray. Thirdly, the secret Bunker's connection and barrier to the main vault will be open, exposing all the residents to the radiation poisoning, and using the final created cure to cure and immunize the residents.")
        print("For your safety and for the scientific staff, you and them will be restricted to the hermetically-sealed research area, and under no circumstance will you engage in direct communication with any of the Bunker residents unless instructed otherwise from BunkerSoft HQ. This measure reduces the chance of cross contamination between Bunker staff and residents.")
        print("As a Bunker Overseer, biological and neurogical scientists, and survivor of the nuclear war, you agree that you have been assigned to a task that will bring forth a better future for the last remnants of humanity: to create an ultimate cure to fight the gamma radiation the Chinese communists have plagued us with. Make BunkerSoft proud, Overseer Bridgeman.")
        userChoice=input(">>>")
        system('cls')
system('cls')
return

def hackingMinigame():
    #Import modules
    import random
    import time
    from os import system

    #Declare  Variables
    tryAgain = "Y"
    characters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    pwdString = (characters[18], characters[19], characters[14], characters[15])
    pwdStop = ''.join(pwdString)
    pwdString = (characters[10], characters[8], characters[11], characters[11])
    pwdKill = ''.join(pwdString)
    pwdString = (characters[19], characters[17], characters[8], characters[15])
    pwdTrip = ''.join(pwdString)
    pwdString = (characters[18], characters[7], characters[8], characters[15])
    pwdShip = ''.join(pwdString)
    pwdString = (characters[17], characters[20], characters[11], characters[4])
    pwdRule = ''.join(pwdString)
    pwdString = (characters[6], characters[17], characters[14], characters[22])
    pwdGrow = ''.join(pwdString)
    pwdString = (characters[15], characters[0], characters[18], characters[18])
    pwdPass = ''.join(pwdString)
    pwdString = (characters[22], characters[4], characters[13], characters[19])
    pwdWent = ''.join(pwdString)
    pwdString = (characters[22], characters[8], characters[13], characters[3])
    pwdWind = ''.join(pwdString)
    pwdString = (characters[25], characters[14], characters[13], characters[4])
    pwdZone = ''.join(pwdString)
    passwords = [pwdStop,pwdKill,pwdTrip,pwdShip,pwdRule,pwdGrow,pwdPass,pwdWent,pwdWind,pwdZone]

    while tryAgain.upper() == "Y":
        attempts = 4
        check = ""
        userInput = ""
        correctPassword = random.sample(passwords,1)
        correctPassword = ''.join(correctPassword)
        print("Welcome to BunkerSoft Corporations(TM) Terminal")
        time.sleep(0.1)
        print("Password Required")
        time.sleep(0.1)
        print("4 Attempts\n")
        print("0x587C  ;'%@*([}^.']   Ox6030  <_`%[:._^~.$")
        time.sleep(0.1)
        print("0x588F  ^&'KILL*$(#*   Ox604G  #%^!5>:,>|='")
        time.sleep(0.1)
        print("0x589H  ,&;|$)![}*/,   Ox605A  GROW|/+&!;^$")
        time.sleep(0.1)
        print("0x590Y  @{=_*}:*=^_{   Ox6068  -*=],&'%`>_}")
        time.sleep(0.1)
        print("0x591R  '`<=%,_<?~%?   Ox6073  %`-[{!]{__#<")
        time.sleep(0.1)
        print("0x592W  >'|>%~\$=,#_   Ox608F  |./$(%;)!;^$")
        time.sleep(0.1)
        print("0x593N  `.++}[}_TRIP   Ox609A  ,>:$(PASS^$>")
        time.sleep(0.1)
        print("0x5945  -_%@*(-]%)|!   Ox610S  ~!<`*?(WENT@")
        time.sleep(0.1)
        print("0x5958  `.*+}[}_){'(   Ox611Y  %@}*-\_`,(:'")
        time.sleep(0.1)
        print("0x596G  \_'\?*#-%*]{   Ox612K  +%&{*)~+{;[_")
        time.sleep(0.1)
        print("0x597C  +#-SHIP!>^_[   Ox613L  =!];./#%~~<*")
        time.sleep(0.1)
        print("0x5981  ;'RULE^%!;,>   Ox614O  #;^WIND)+[|%")
        time.sleep(0.1)
        print("0x599F  (]=){_~`,_<&   Ox615U  $&%)^'%})!/%")
        time.sleep(0.1)
        print("0x6006  '>=-`[).$]|]   Ox6160  @}*-\_`,(:',")
        time.sleep(0.1)
        print("0x601L  ;'%@*([}^[ST   Ox617O  %:<{ZONE~]!#")
        time.sleep(0.1)
        print("0x602I  OP@*#;,>?[=]   Ox618J  |./$(%!)!;^$")
        print(correctPassword)

        while attempts > 0:
            userInput = input(">>>").upper()

            if len(userInput) != len(correctPassword):
                print("Error")
                continue
            for i in range(4):
                if userInput[i] not in characters:
                    print("Error")
                    continue

            check = ''
            if userInput != correctPassword:
                for i in range(4):
                    if userInput[i] == correctPassword[i]:
                        check += "X"
                attempts = attempts-1
                print("Access Denied")
            elif userInput == correctPassword:
                print("Access Granted")
                time.sleep(1)
                system('cls')
                locked = True
                accessGranted()
                attempts = 0
                continue

            if attempts != 0 and check != "XXXX":
                print("Likeness =", len(check))
            elif attempts == 0 and check != "XXXX":
                print("Init Lockout")

            if attempts == 0:
                tryAgain = input("Reboot? (Y/N)")
                system('cls')
    return
while locked == False:
    hackingMinigame()
</code>```

It's a LOT, I know, and it's extremely confusing, but I'm open to any suggestions as to how this should work..

Body:
I'm trying to remake a terminal from the Fallout series, if any of you know what that is.

Basically, the program shows a bunch of options they can choose from, then they have to input a number (1-5) to select which thing they want to view. The program will use an if statement to determine which thing they want to view. For example, if the user inputted one, then it will clear the screen and print a bunch of information, then the user has to input enter, then the screen clears and the options from the beginning are displayed again. This whole thing is inside a while statement, and while the user input is not "C", it will still display all of that other stuff, and when it does become "C", the program will clear everything and the program ends.

I know all of that sounded confusing, but basically the problem is that if the person inputs a number, it doesn't do the clearing thing, it just displays the choices again.

I'll just display the code, so if anyone could tell me what the problem is, that would greatly be appreciated.

def confusingFunction():
    from os import system
    userChoice = ""

    while userChoice.upper() != "C":
        print("Choice 1")
        print("Choice 2")
        print("Choice 3")
        print("Choice 4")
        print("Choice 5")
        userChoice = input(">>>")

        if userChoice == 1:
            system('cls')
            print("Stuff")
            print("Stuff")
            print("Stuff")
            input(">>>")
            system('cls')

    system('cls')
    return

Body:
If anyone needs the entire, actual code, here you go...`

locked = False
#Define Function
def accessGranted():
    import time
    from os import system
    userChoice = ""
    while userChoice.upper() != "C":
        print("Welcome to BunkerSoft Corporations(TM) Terminal\nClearance: Overseer Eyes Only\nBy using this terminal, you are acknowledging that you are an authorized user or technician. Unauthorized users must cease reading and log out of this terminal immediately. Violators will be subject to civil and criminal penalties.\n")
        time.sleep(0.1)
        print("1. [BUNKER 012 OVERSEER INSTRUCTIONS]")
        time.sleep(0.1)
        print("2. [Overseer Logs]")
        time.sleep(0.1)
        print("3. [Experiments]")
        time.sleep(0.1)
        print("4. [Lab]")
        time.sleep(0.1)
        print("5. [Cache]\n")
        time.sleep(0.1)
        userChoice = input(">>>")
        while userChoice == 1:
            system('cls')
            print("Welcome to BunkerSoft Corporations(TM)
Terminal\nClearance: Overseer Eyes Only\n")
            print("CONFIDENTIAL CONFIDENTIAL CONFIDENTIAL\nOVERSEER EYES ONLY | VIOLATION BST&A-01001\n")
            print("Bunker 012 is designed to research infectious diseases on various lifeforms, including human beings, with particular attention paid to potential mutations in a climate of heavy radiation, with an eventual hope to discover a cure and immunity to this cancerous .")
        print("Due to long-term exposure to post-nuclear gamma radiation, infected lifeforms have had their brains permenantly damaged, resulting in complete loss of normal reasoning capabilities and higher thought processes, becoming more animalistic, impulsive, and hostile to anything.")
        print("As of the post-nuclear sealment of this bunker, you are aware of the Bunkers two sections. The main section is where a total of 128 Bunker residents can live in for the foreseeable future, and the secret closed off section of the Bunker, with a Bunker door designed not to close properly. This will be where main testing of the effects of gamma radiation will be conducted.")
        print("Clinical trials are a vital part of Bunker 012's mission. Trials will be performed in three stages: Firstly, live specimens from outside the bunker will be held captive to study their neurogical and physical subconcious. Secondly, Bunker residents will be asked to enter the vault for screening, where they will unknowingly be exposed to different diseases and cures for the radiation poisoning via propellant nozzles that the resident should suspect is the cleansing spray. Thirdly, the secret Bunker's connection and barrier to the main vault will be open, exposing all the residents to the radiation poisoning, and using the final created cure to cure and immunize the residents.")
        print("For your safety and for the scientific staff, you and them will be restricted to the hermetically-sealed research area, and under no circumstance will you engage in direct communication with any of the Bunker residents unless instructed otherwise from BunkerSoft HQ. This measure reduces the chance of cross contamination between Bunker staff and residents.")
        print("As a Bunker Overseer, biological and neurogical scientists, and survivor of the nuclear war, you agree that you have been assigned to a task that will bring forth a better future for the last remnants of humanity: to create an ultimate cure to fight the gamma radiation the Chinese communists have plagued us with. Make BunkerSoft proud, Overseer Bridgeman.")
        userChoice=input(">>>")
        system('cls')
system('cls')
return

def hackingMinigame():
    #Import modules
    import random
    import time
    from os import system

    #Declare  Variables
    tryAgain = "Y"
    characters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
    pwdString = (characters[18], characters[19], characters[14], characters[15])
    pwdStop = ''.join(pwdString)
    pwdString = (characters[10], characters[8], characters[11], characters[11])
    pwdKill = ''.join(pwdString)
    pwdString = (characters[19], characters[17], characters[8], characters[15])
    pwdTrip = ''.join(pwdString)
    pwdString = (characters[18], characters[7], characters[8], characters[15])
    pwdShip = ''.join(pwdString)
    pwdString = (characters[17], characters[20], characters[11], characters[4])
    pwdRule = ''.join(pwdString)
    pwdString = (characters[6], characters[17], characters[14], characters[22])
    pwdGrow = ''.join(pwdString)
    pwdString = (characters[15], characters[0], characters[18], characters[18])
    pwdPass = ''.join(pwdString)
    pwdString = (characters[22], characters[4], characters[13], characters[19])
    pwdWent = ''.join(pwdString)
    pwdString = (characters[22], characters[8], characters[13], characters[3])
    pwdWind = ''.join(pwdString)
    pwdString = (characters[25], characters[14], characters[13], characters[4])
    pwdZone = ''.join(pwdString)
    passwords = [pwdStop,pwdKill,pwdTrip,pwdShip,pwdRule,pwdGrow,pwdPass,pwdWent,pwdWind,pwdZone]

    while tryAgain.upper() == "Y":
        attempts = 4
        check = ""
        userInput = ""
        correctPassword = random.sample(passwords,1)
        correctPassword = ''.join(correctPassword)
        print("Welcome to BunkerSoft Corporations(TM) Terminal")
        time.sleep(0.1)
        print("Password Required")
        time.sleep(0.1)
        print("4 Attempts\n")
        print("0x587C  ;'%@*([}^.']   Ox6030  <_`%[:._^~.$")
        time.sleep(0.1)
        print("0x588F  ^&'KILL*$(#*   Ox604G  #%^!5>:,>|='")
        time.sleep(0.1)
        print("0x589H  ,&;|$)![}*/,   Ox605A  GROW|/+&!;^$")
        time.sleep(0.1)
        print("0x590Y  @{=_*}:*=^_{   Ox6068  -*=],&'%`>_}")
        time.sleep(0.1)
        print("0x591R  '`<=%,_<?~%?   Ox6073  %`-[{!]{__#<")
        time.sleep(0.1)
        print("0x592W  >'|>%~\$=,#_   Ox608F  |./$(%;)!;^$")
        time.sleep(0.1)
        print("0x593N  `.++}[}_TRIP   Ox609A  ,>:$(PASS^$>")
        time.sleep(0.1)
        print("0x5945  -_%@*(-]%)|!   Ox610S  ~!<`*?(WENT@")
        time.sleep(0.1)
        print("0x5958  `.*+}[}_){'(   Ox611Y  %@}*-\_`,(:'")
        time.sleep(0.1)
        print("0x596G  \_'\?*#-%*]{   Ox612K  +%&{*)~+{;[_")
        time.sleep(0.1)
        print("0x597C  +#-SHIP!>^_[   Ox613L  =!];./#%~~<*")
        time.sleep(0.1)
        print("0x5981  ;'RULE^%!;,>   Ox614O  #;^WIND)+[|%")
        time.sleep(0.1)
        print("0x599F  (]=){_~`,_<&   Ox615U  $&%)^'%})!/%")
        time.sleep(0.1)
        print("0x6006  '>=-`[).$]|]   Ox6160  @}*-\_`,(:',")
        time.sleep(0.1)
        print("0x601L  ;'%@*([}^[ST   Ox617O  %:<{ZONE~]!#")
        time.sleep(0.1)
        print("0x602I  OP@*#;,>?[=]   Ox618J  |./$(%!)!;^$")
        print(correctPassword)

        while attempts > 0:
            userInput = input(">>>").upper()

            if len(userInput) != len(correctPassword):
                print("Error")
                continue
            for i in range(4):
                if userInput[i] not in characters:
                    print("Error")
                    continue

            check = ''
            if userInput != correctPassword:
                for i in range(4):
                    if userInput[i] == correctPassword[i]:
                        check += "X"
                attempts = attempts-1
                print("Access Denied")
            elif userInput == correctPassword:
                print("Access Granted")
                time.sleep(1)
                system('cls')
                locked = True
                accessGranted()
                attempts = 0
                continue

            if attempts != 0 and check != "XXXX":
                print("Likeness =", len(check))
            elif attempts == 0 and check != "XXXX":
                print("Init Lockout")

            if attempts == 0:
                tryAgain = input("Reboot? (Y/N)")
                system('cls')
    return
while locked == False:
    hackingMinigame()

It's a LOT, I know, and it's extremely confusing, but I'm open to any suggestions as to how this should work..


问:
Removed string values from geo cordinates
I have massive dataset with more than two billion rows and 16 columns.

Two of the columns are latitude and longitude and one column of DateTime.

As the data is raw I am trying to sanitize it. In the process I came across some latitude longitude rows containing datetime which is been taken as string and latitude and longitude are float.

I am using re for other preprocessing but here I am not able to do it.

I want to remove the entire  row which has anything else but latitude and longitude in those two columns.

I am looking for some simple solution in python and pandas which will only remove those rows and keep the rest of the dataset as it is.

Edit: The input mini version is shared here. Last two columns are latitude & Longitude and a column before that is datetime row 10 as the error I mentioned.

Appriciate the help..  Thanks!

Body:
There is difference if all values are strings:

df = pd.DataFrame({'lat':[10,20,'d'], 'lon':[4,'hh', 7]}).astype(str)

mask = pd.to_numeric(df['lat'], errors='coerce').notnull() &
       pd.to_numeric(df['lon'], errors='coerce').notnull()

df = df[mask]
print (df)
  lat lon
0  10   4

Or values are mixed - some are numeric and some are strings:

df = pd.DataFrame({'lat':[10,20,'d'], 'lon':[4,'hh', 7]})

mask = (df['lat'].apply(type) != str) & (df['lon'].apply(type) != str)

df = df[mask]
print (df)
  lat lon
0  10   4

EDIT:

df = pd.read_csv('twt_mini_stack.csv')
#print (df)

mask = pd.to_numeric(df['Lat'], errors='coerce').notnull() &  \
       pd.to_numeric(df['Long'], errors='coerce').notnull()

df = df[mask]
print (df[['Tweeted Datetime','Lat','Long']])
        Tweeted Datetime       Lat      Long
0   3:59 PM - 1 Jan 2016  35.68501  139.7514
1   3:59 PM - 1 Jan 2016  35.68501  139.7514
2   3:59 PM - 1 Jan 2016  35.68501  139.7514
3   3:59 PM - 1 Jan 2016  35.68501  139.7514
4   3:59 PM - 1 Jan 2016  35.68501  139.7514
5   3:59 PM - 1 Jan 2016  35.68501  139.7514
6   3:59 PM - 1 Jan 2016  35.68501  139.7514
7   3:59 PM - 1 Jan 2016  35.68501  139.7514
9   3:58 PM - 1 Jan 2016  35.68501  139.7514
10  3:58 PM - 1 Jan 2016  35.68501  139.7514
11  3:58 PM - 1 Jan 2016  35.68501  139.7514
12  3:58 PM - 1 Jan 2016  35.68501  139.7514
13  3:58 PM - 1 Jan 2016  35.68501  139.7514


答:
The trim function removes leading and trailing spaces, not all spaces.

If you want to remove all spaces, you can call s = s.replaceAll(" ", "").

Title: Using a simple scanner, reading a string with spaces, how come .trim() method isn't working?

Body:
import java.util.Scanner;
import java.lang.String;

public class Test
{
    public static void main(String[] args)
    {
        char[] sArray;

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Palindrome : ");
        String s = scan.nextLine();
        s = s.trim();

        sArray = new char[s.length()];

        for(int i = 0; i < s.length(); i++)
        {
            sArray[i] = s.charAt(i);
            System.out.println(sArray[i]);
        }
    }
}


问:
How I can send custom parameters through java?
Suppose I want to send following parameters :

```<code>key1: value1,
key2: value2
</code>```

But currently I can't decide what will be there at place of key1,key2
That may be any string. key1 may be city,key2 may be code. Or key 1 may be companyName and key 2 is domain. So how can I set any custom unknown parametrs in method of java? Consider that I know total number of parameters and data type of their values, but can't determine their exact keys now. How to implement it in java?

答:
I assume what you mean to achieve is a method that can accept any type of argument and still do the work.

Below is the approach I would use:
Lets say you want to use myMethod:

```<code>  class MainClass  {

  public Object myMethod(Object A,Object B)
  {
      Object C=(Object) (A.toString()+","+B.toString());

      System.out.println(C.toString());

      return C;

  }
}
</code>```

And you can call it with any type of parameters:

```<code>public class TesterClass {

    MainClass mainClass=new MainClass();
    mainClass.myMethod(123, "PQR");
    mainClass.myMethod(123.00, "PQR");
    mainClass.myMethod(123.00, 123);
    mainClass.myMethod(new int[]{1,2,3}, "PQR");

}
</code>```

Your output will be:

```<code>123,PQR

123.0,PQR

123.0,123

[I@659e0bfd,PQR
</code>```

last one is array, you can manipulate its processing)

Body:
Suppose I want to send following parameters :

key1: value1,
key2: value2

But currently I can't decide what will be there at place of key1,key2
That may be any string. key1 may be city,key2 may be code. Or key 1 may be companyName and key 2 is domain. So how can I set any custom unknown parametrs in method of java? Consider that I know total number of parameters and data type of their values, but can't determine their exact keys now. How to implement it in java?

Body:
I assume what you mean to achieve is a method that can accept any type of argument and still do the work.

Below is the approach I would use:
Lets say you want to use myMethod:

  class MainClass  {

  public Object myMethod(Object A,Object B)
  {
      Object C=(Object) (A.toString()+","+B.toString());

      System.out.println(C.toString());

      return C;

  }
}

And you can call it with any type of parameters:

public class TesterClass {

    MainClass mainClass=new MainClass();
    mainClass.myMethod(123, "PQR");
    mainClass.myMethod(123.00, "PQR");
    mainClass.myMethod(123.00, 123);
    mainClass.myMethod(new int[]{1,2,3}, "PQR");

}

Your output will be:

123,PQR

123.0,PQR

123.0,123

[I@659e0bfd,PQR

last one is array, you can manipulate its processing)


问:
Is it possible to generate this query?
Select * From table1.

if table1.field1=1 then inner join table2

else if table1.field1=2 then inner join table3

答:
```<code>SELECT glbank.check_num
, glbank.ref_num
, glbank.check_amt
, glbank.check_date
, glbank.bank_code
, vendaddr.name
, vendor.vend_num
, vendor.vend_remit
FROM ((aptrxp_all
INNER JOIN glbank
ON aptrxp_all.check_num=glbank.check_num)
INNER JOIN vendaddr
ON aptrxp_all.vend_num=vendaddr.vend_num)
INNER JOIN vendor
ON vendaddr.vend_num=vendor.vend_num
If vendaddr.vend_num=vendor.vend_num Then
(SELECT vendaddr.name
FROM vendaddr
INNER JOIN vendor
ON vendaddr.vend_num=vendor.vend_num where vendaddr.vend_num=vendor.vend_num)
Else (SELECT vendaddr.name
FROM vendaddr
INNER JOIN vendor
ON vendaddr.vend_num=vendor.vend_remit where
vendaddr.vend_num=vendor.vend_remit)
end
where glbank.check_amt= @amount
</code>```

Title: Is it possible to generate this query?


问:
Multiple window project in c# - Updating data in Form1 from Form2
First I will outline the logic of my project so you know what I'm trying to achieve.

I have Form1 which is the main form.

I have Form2 which is opened when a button is clicked in Form1

I have a class Student which contains some properties (name, id, bday) which are all private but have getters and setters

Student can be instantiated by

Student s = new Student(name, int, bday);

I have a class University which has a property List<Student> which as you might imagine, contains a list of Students

Now how my program is meant to work is ..

Form1 displays the list of students

Form2 creates the students, and adds them to the studentList in Form1 when a button is clicked. Form2 also closes when this same button is clicked

What I was thinking I could do is have a "global" list in University and Form2 updates this "global" list, then Form1 displays this "global" list.

This is what Form1 looks like

And this is what Form2 looks like

I'm looking for ideas on how I can achieve this, here is some code from each Form that might help

Form1

```<code>    private static List<Student> studentListHome;
    University mainUniversity = new University(studentListHome);

    public List<Student> StudentListHome
    {
        get
        {
            return studentListHome;
        }
        set
        {
            studentListHome = value;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if(studentListHome != null)
        {
            mainUniversity.StudentList.Concat(studentListHome).ToList();
            studentListBox.DataSource = mainUniversity.StudentList;
            studentListBox.DisplayMember = "name";
        }

    }

    private void studentToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form2 studentForm = new Form2();
        studentForm.ShowDialog();
    }
</code>```

Form2

```<code>private string studentName;
private int studentID;
private string studentBDay;
private List<Student> studentListForm2 = new List<Student>();
Form1 homeForm ;

private void submitButton_Click(object sender, EventArgs e)
{
    if (comparator(nameInput) &
       comparator(idInput) &
       comparator(bdayInput)){
        variable_assignment();
        var tempStudent = StudentCreation();
        if(tempStudent != null)
        {
            studentListForm2.Add(tempStudent);
        }
        homeForm.StudentListHome = studentListForm2;
        Close();

    }
}
</code>```

In Form2 comparator is a function that returns a bool, it checks to make sure that the input fields aren't empty.

variable_assignment takes the user input and assigns it to the relative variable (studentName, studentID, studentBDay)

StudentCreation() is a function that returns a Student it simply instantiates a Student using the new values of studentName studentID studentBDay and in my case, is assigned to tempStudent

As my code is now, when I run it, I get an error
An unhandled exception of type 'System.NullReferenceException' occurred in TestProjectForProject5.exe

and it references this line of code

homeForm.StudentListHome = studentListForm2;

I'm guessing this is because homeForm is never instantiated. I have done this because I don't know how to reference this current Form1 that is open, I do not want to create a new Form1 and send data to it, I want to send data to the original Form1.

So my question is, how do I fix this error, and be able to send data to the original Form1 like I'm intending to do, not a new Form1

答:
your getting this error because your homeForm is null.

create a constructor in form 2 and pass parameter of form1 , something like in form2 :

```<code> public Form2(From1 frm1)
   {
   homeForm =frm1;
   }

 private void submitButton_Click(object sender, EventArgs e)
  {
     //your code
     homeForm.StudentListHome = studentListForm2;
     homeForm.BindData();
     Close();
   }
</code>```

Then Pass the object of form1,something like in form 1:

```<code> private void Form1_Load(object sender, EventArgs e)
  {
   BindData();
  }
  Public Void BindData()
   {
      if(studentListHome != null)
       {
          mainUniversity.StudentList.Concat(studentListHome).ToList();
          studentListBox.DataSource = mainUniversity.StudentList;
          studentListBox.DisplayMember = "name";
        }
    }

   private void studentToolStripMenuItem_Click(object sender, EventArgs e)
    {
      Form2 studentForm = new Form2(this);
      studentForm.ShowDialog();
    }
</code>```

Body:
First I will outline the logic of my project so you know what I'm trying to achieve.

I have Form1 which is the main form.

I have Form2 which is opened when a button is clicked in Form1

I have a class Student which contains some properties (name, id, bday) which are all private but have getters and setters

Student can be instantiated by

Student s = new Student(name, int, bday);

I have a class University which has a property List<Student> which as you might imagine, contains a list of Students

Now how my program is meant to work is ..

Form1 displays the list of students

Form2 creates the students, and adds them to the studentList in Form1 when a button is clicked. Form2 also closes when this same button is clicked

What I was thinking I could do is have a "global" list in University and Form2 updates this "global" list, then Form1 displays this "global" list.

This is what Form1 looks like

And this is what Form2 looks like

I'm looking for ideas on how I can achieve this, here is some code from each Form that might help

Form1

    private static List<Student> studentListHome;
    University mainUniversity = new University(studentListHome);

    public List<Student> StudentListHome
    {
        get
        {
            return studentListHome;
        }
        set
        {
            studentListHome = value;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if(studentListHome != null)
        {
            mainUniversity.StudentList.Concat(studentListHome).ToList();
            studentListBox.DataSource = mainUniversity.StudentList;
            studentListBox.DisplayMember = "name";
        }

    }

    private void studentToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form2 studentForm = new Form2();
        studentForm.ShowDialog();
    }

Form2

private string studentName;
private int studentID;
private string studentBDay;
private List<Student> studentListForm2 = new List<Student>();
Form1 homeForm ;

private void submitButton_Click(object sender, EventArgs e)
{
    if (comparator(nameInput) &
       comparator(idInput) &
       comparator(bdayInput)){
        variable_assignment();
        var tempStudent = StudentCreation();
        if(tempStudent != null)
        {
            studentListForm2.Add(tempStudent);
        }
        homeForm.StudentListHome = studentListForm2;
        Close();

    }
}

In Form2 comparator is a function that returns a bool, it checks to make sure that the input fields aren't empty.

variable_assignment takes the user input and assigns it to the relative variable (studentName, studentID, studentBDay)

StudentCreation() is a function that returns a Student it simply instantiates a Student using the new values of studentName studentID studentBDay and in my case, is assigned to tempStudent

As my code is now, when I run it, I get an error
An unhandled exception of type 'System.NullReferenceException' occurred in TestProjectForProject5.exe

and it references this line of code

homeForm.StudentListHome = studentListForm2;

I'm guessing this is because homeForm is never instantiated. I have done this because I don't know how to reference this current Form1 that is open, I do not want to create a new Form1 and send data to it, I want to send data to the original Form1.

So my question is, how do I fix this error, and be able to send data to the original Form1 like I'm intending to do, not a new Form1

Body:
your getting this error because your homeForm is null.

create a constructor in form 2 and pass parameter of form1 , something like in form2 :

 public Form2(From1 frm1)
   {
   homeForm =frm1;
   }

 private void submitButton_Click(object sender, EventArgs e)
  {
     //your code
     homeForm.StudentListHome = studentListForm2;
     homeForm.BindData();
     Close();
   }

Then Pass the object of form1,something like in form 1:

 private void Form1_Load(object sender, EventArgs e)
  {
   BindData();
  }
  Public Void BindData()
   {
      if(studentListHome != null)
       {
          mainUniversity.StudentList.Concat(studentListHome).ToList();
          studentListBox.DataSource = mainUniversity.StudentList;
          studentListBox.DisplayMember = "name";
        }
    }

   private void studentToolStripMenuItem_Click(object sender, EventArgs e)
    {
      Form2 studentForm = new Form2(this);
      studentForm.ShowDialog();
    }


问:
Square In Person Payment changed documentation intent fields, would that impact in future?
I noticed that documentation for Sqaure In Person Payments have changed the intent fields from S.com.squareup.register.WEB_CALLBACK_URI to S.com.squareup.pos.WEB_CALLBACK_URI. I had implemented the older one almost 2 to 3 months back.

Now I followed the documentation again, I see the difference. Anyhow I have tested In Person Payments yesterday, it was working fine though. I just want to be sure if this will effect or I need to change the intent fields?

答: You should change so that you can take advantage of future features. Read more on Square's Developer Blog</p>


问:
IllegalArgumentException: Unable to locate adb in Android Studio v2.3
Does anyone know how to fix this?

```<code>IllegalArgumentException: Unable to locate adb
</code>```

I installed android studio v2.3 and it won't let me run my app saying the error.
I searched online and said to click the  Launch Standalone Sdk manager but I am unable to locate it.

答:
Happened with me as well.
Try uninstalling and reinstalling SDK platform tools in the SDK manager located in Tools>>Android>>SDK Manager.
If this doesn't work(It usually does), then it is possible that for some reason your android-sdk folder doesn't have the Platform-Tools folder containing the adb.exe file.
Go to the ADT unzipped file from the first installation and just copy it to the correct path.</p>

Body:
Does anyone know how to fix this?

IllegalArgumentException: Unable to locate adb

I installed android studio v2.3 and it won't let me run my app saying the error.
I searched online and said to click the  Launch Standalone Sdk manager but I am unable to locate it.


问:
How do I use PowerShell to pull headers from a OneNote document
Background:
In my work environment, we have a transitional location for our knowledgebase notes.  These reside in a number of OneNote 2016 workbooks which have been maintained over years.  I am currently in the middle of delegating content update efforts to our staff and part of this work involves importing all our OneNote notebook names and section names into an excel spreadsheet for hierarchy management.

Task:  I spent ages looking online for an easy and quick way to export hierarchy information from OneNote to csv using PowerShell and could not for the life of me find an easy way that worked.  The following code resonated through the interwebs but each time I tried to run the code, I kept getting errors.

```<code>$onenote = New-Object -ComObject OneNote.Application
$scope = [Microsoft.Office.Interop.OneNote.HierarchyScope]::hsPages
[ref]$xml = $null

$onenote.GetHierarchy($null, $scope, $xml)

$schema = @{one=”http://schemas.microsoft.com/office/onenote/2013/onenote”}

$xpath = “//one:Notebook/one:Section”
Select-Xml -Xml (

$xml.Value) -Namespace $schema -XPath $xpath |
foreach {
$node = $psitem.Node

$npath = Split-Path -Path $node.Path -Parent

$props = [ordered]@{
Workbook =  Split-Path -Path $npath -Leaf
Section = $node.Name
}
New-Object -TypeName PSObject -Property $props
}
</code>```

Error:
The error I would get from executing this code was as follows:

value of type "System.String" to type "System.Xml.XmlNode".
At line:10 char:17
+ Select-Xml -Xml (

答:
Solution:
In the end I had to break down the established connection to the Onenote Application and found a workable solution for OneNote 2016.  I've provided my solution but am keen to hear of any other possible ways to manipulate this data effectively in the future:

```<code>Function Get-OneNoteHeaders{

[CmdletBinding()]
Param()

Begin
{
    $onenote = New-Object -ComObject OneNote.Application
    $scope = [Microsoft.Office.Interop.OneNote.HierarchyScope]::hsPages
    [ref]$xml = $null
    $csvOutput = "c:\temp\onenote-headers.csv"
}
Process
{
    $onenote.GetHierarchy($null, $scope, $xml)
    [xml]$result = ($xml.Value)

    Foreach($notebook in $($result.DocumentElement.Notebook)){
        Add-content -Path $csvOutput -Value "$($notebook.name)"
        Foreach($section in $($notebook.section)){
            Add-content -Path $csvOutput -Value ",$($section.name)"
            Foreach($page in $section.page){
                Add-content -Path $csvOutput -Value ",,$($page.name)"
            }
        }
    }
}
End{}
}

#Get-OneNoteHeaders
</code>```

Body:
Background:
In my work environment, we have a transitional location for our knowledgebase notes.  These reside in a number of OneNote 2016 workbooks which have been maintained over years.  I am currently in the middle of delegating content update efforts to our staff and part of this work involves importing all our OneNote notebook names and section names into an excel spreadsheet for hierarchy management.

Task:  I spent ages looking online for an easy and quick way to export hierarchy information from OneNote to csv using PowerShell and could not for the life of me find an easy way that worked.  The following code resonated through the interwebs but each time I tried to run the code, I kept getting errors.

$onenote = New-Object -ComObject OneNote.Application
$scope = [Microsoft.Office.Interop.OneNote.HierarchyScope]::hsPages
[ref]$xml = $null

$onenote.GetHierarchy($null, $scope, $xml)

$schema = @{one=”http://schemas.microsoft.com/office/onenote/2013/onenote”}

$xpath = “//one:Notebook/one:Section”
Select-Xml -Xml (

$xml.Value) -Namespace $schema -XPath $xpath |
foreach {
$node = $psitem.Node

$npath = Split-Path -Path $node.Path -Parent

$props = [ordered]@{
Workbook =  Split-Path -Path $npath -Leaf
Section = $node.Name
}
New-Object -TypeName PSObject -Property $props
}

Error:
The error I would get from executing this code was as follows:

value of type "System.String" to type "System.Xml.XmlNode".
At line:10 char:17
+ Select-Xml -Xml (

Body:
Solution:
In the end I had to break down the established connection to the Onenote Application and found a workable solution for OneNote 2016.  I've provided my solution but am keen to hear of any other possible ways to manipulate this data effectively in the future:

Function Get-OneNoteHeaders{

[CmdletBinding()]
Param()

Begin
{
    $onenote = New-Object -ComObject OneNote.Application
    $scope = [Microsoft.Office.Interop.OneNote.HierarchyScope]::hsPages
    [ref]$xml = $null
    $csvOutput = "c:\temp\onenote-headers.csv"
}
Process
{
    $onenote.GetHierarchy($null, $scope, $xml)
    [xml]$result = ($xml.Value)

    Foreach($notebook in $($result.DocumentElement.Notebook)){
        Add-content -Path $csvOutput -Value "$($notebook.name)"
        Foreach($section in $($notebook.section)){
            Add-content -Path $csvOutput -Value ",$($section.name)"
            Foreach($page in $section.page){
                Add-content -Path $csvOutput -Value ",,$($page.name)"
            }
        }
    }
}
End{}
}

#Get-OneNoteHeaders