问:
OpenAPI 3.0 file format giving error around allowedValues in parameters
I've API Spec specified in OAS 3.0

```<code>post:
  tags:
    - One Time Payment
  summary: One Time Payment API
  operationId: oneTimePaymentUsingPOST
  parameters:
    - in: body
      name: realTimePaymentRequest
      description: realTimePaymentRequest
      required: true
      schema:
        $ref: '#/components/schemas/RealTimePaymentRequest'
</code>```

When I edit this spec file in https://editor.swagger.io/ - It's throwing errors as :

```<code>Structural error at paths./banks/payments.post.parameters.0.in
should be equal to one of the allowed values
allowedValues: path, query, header, cookie
</code>```

I can see that describing in: body in parameters is supported as per https://swagger.io/docs/specification/2-0/describing-request-body/

thought Swagger Editor is throwing errors. What could be wrong here ? schema ?

Any help is appreciated. Thank you.

答:
In OpenAPI 3.0, in: body and in: formData parameters were replaced with requestBody:

post:
  tags:
    - One Time Payment
  summary: One Time Payment API
  operationId: oneTimePaymentUsingPOST

  requestBody:
    description: realTimePaymentRequest
    required: true
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/RealTimePaymentRequest'
```

The documentation link you posted is for OpenAPI 2.0. For OpenAPI 3.0, use this link:

https://swagger.io/docs/specification/describing-request-body/

Body:
I've API Spec specified in OAS 3.0

post:
  tags:
    - One Time Payment
  summary: One Time Payment API
  operationId: oneTimePaymentUsingPOST
  parameters:
    - in: body
      name: realTimePaymentRequest
      description: realTimePaymentRequest
      required: true
      schema:
        $ref: '#/components/schemas/RealTimePaymentRequest'

When I edit this spec file in https://editor.swagger.io/ - It's throwing errors as :

Structural error at paths./banks/payments.post.parameters.0.in
should be equal to one of the allowed values
allowedValues: path, query, header, cookie

I can see that describing in: body in parameters is supported as per https://swagger.io/docs/specification/2-0/describing-request-body/

thought Swagger Editor is throwing errors. What could be wrong here ? schema ?

Any help is appreciated. Thank you.

Body:
In OpenAPI 3.0, in: body and in: formData parameters were replaced with requestBody:

post:
  tags:
    - One Time Payment
  summary: One Time Payment API
  operationId: oneTimePaymentUsingPOST

  requestBody:
    description: realTimePaymentRequest
    required: true
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/RealTimePaymentRequest'

The documentation link you posted is for OpenAPI 2.0. For OpenAPI 3.0, use this link:

https://swagger.io/docs/specification/describing-request-body/


来源: stackexchange

问:
Laravel Cron Not Running at Same time
I had make severals commands for my application like this :

```<code>protected $commands = [
    'App\Console\Commands\GraphAll',
    'App\Console\Commands\theBar',
    'App\Console\Commands\theVar',
    'App\Console\Commands\theDay',
    'App\Console\Commands\theVarDay',
    'App\Console\Commands\MailSend',
    'App\Console\Commands\Daily',
    'App\Console\Commands\DailyGraph',
    'App\Console\Commands\CongloBar',
    'App\Console\Commands\CongloAll',
    'App\Console\Commands\CongloVar'
];
</code>```

They all work good.
I call the schedule run at midnight and i receive notifications for all the commands who are in this fonction :

```<code>protected function schedule(Schedule $schedule)
{
    //la cron de la barre
    $schedule->command('graph:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/BarreCron');

    //La Cron du premier
    $schedule->command('bar:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/OneCron');

    //La Cron du deuxième
    $schedule->command('var:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/TwoCron');

    //La Cron du troisème
    $schedule->command('day:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/ThreeCron');

    //La Cron du quatrième
    $schedule->command('varDay:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/FourCron');
}
</code>```

I wait one hour and run and an other script for launch a command who are not in this function , and i receive a notifications too.

But i have noticed , that when i call the schedule run , it run all the commands ; not only who they are in the fonction. And i want separate the execution between them.

Is there a way to run only the 5 commands ,and skip the others for an other script?

答:
Use method runInBackground
link

ContentLicense: CC BY-SA 3.0

Title: Laravel Cron Not Running at Same time

Body:
I had make severals commands for my application like this :

protected $commands = [
    'App\Console\Commands\GraphAll',
    'App\Console\Commands\theBar',
    'App\Console\Commands\theVar',
    'App\Console\Commands\theDay',
    'App\Console\Commands\theVarDay',
    'App\Console\Commands\MailSend',
    'App\Console\Commands\Daily',
    'App\Console\Commands\DailyGraph',
    'App\Console\Commands\CongloBar',
    'App\Console\Commands\CongloAll',
    'App\Console\Commands\CongloVar'
];

They all work good.
I call the schedule run at midnight and i receive notifications for all the commands who are in this fonction :

protected function schedule(Schedule $schedule)
{
    //la cron de la barre
    $schedule->command('graph:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/BarreCron');

    //La Cron du premier
    $schedule->command('bar:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/OneCron');

    //La Cron du deuxième
    $schedule->command('var:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/TwoCron');

    //La Cron du troisème
    $schedule->command('day:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/ThreeCron');

    //La Cron du quatrième
    $schedule->command('varDay:All')
        ->everyMinute()
        ->sendOutputTo('app/Http/Crons/FourCron');
}

I wait one hour and run and an other script for launch a command who are not in this function , and i receive a notifications too.

But i have noticed , that when i call the schedule run , it run all the commands ; not only who they are in the fonction. And i want separate the execution between them.

Is there a way to run only the 5 commands ,and skip the others for an other script?

Body:
Use method runInBackground
link

ContentLicense: CC BY-SA 4.0


问:
MultiSelect = FALSE Doesn't Work on LISTVIEW
Language :: Visual C++ Windows Form Application
Platform :: VS 2008 (.Net 4.0)

I am using the Checked ListView control.  I have the "MultiSelect" option set to FALSE.  This seems to work to only allow one row at a time to be highlighted.

What doesn't seem to be working though is the Check box associated with each item in the ListView.  Even with "MultiSelect" = FALSE it is still allowing the user to check more than one item in the list.

I understand the basic premis behind the CheckBox . . . That it allows more than one item to be selected.  But, is there any way around this "feature"?  Is there any way to limit only one item checked in a Checked ListView even with the "MultiSelect" option = FALSE?

I am desperate.

Thanks! :)

答: A quick fix could be to un-select all existing items before selecting the new one.</p>


问:
How to insert a character at a certain position in a number without converting it into a string?
I have to insert "/" between 2020 and 0001 in the number 20200001. I know how to do it by converting the number to string, but I am unable to do it by not converting it.</p>

答:
If you don't convert it to string, it just a number and the "/"is not a number so u need to convert it to a string.

please check this link https://www.w3schools.com/js/js_number_methods.asp

```<code>function fortmat(date, format) {
    return date.toString().replace(/(\d{4})(\d{2})(\d{2})/g, `$1${format}$2${format}$3`)
}

console.log(fortmat(20200001, "/"));
</code>```

This function helps you to convert the Date to another format.

Body:
If you don't convert it to string, it just a number and the "/"is not a number so u need to convert it to a string.

please check this link https://www.w3schools.com/js/js_number_methods.asp

function fortmat(date, format) {
    return date.toString().replace(/(\d{4})(\d{2})(\d{2})/g, `$1${format}$2${format}$3`)
}

console.log(fortmat(20200001, "/"));

This function helps you to convert the Date to another format.


问:
Angular form input with only 2 decimals?
I have an input like the following:

<mat-form-field>
    <input matInput type="number" [placeholder]="'Hours' | translate"
                formControlName="Work" (blur)="calculate()" />
</mat-form-field>
```

Right now, the input allows unlimited decimals. I would like to only allow 2 decimals on that input. It could be done with any of the following solutions:

Restrict the input to 2 decimals, so that I can't insert more

Allow unlimited decimals and round to 2 decimals when I click another component

Is there any included feature in Angular for doing that? Otherwise,
  how can I create that restriction/rounding?

Example of the second option:

The user enters the value 1,2582399512

When the input is unfocused, the value is rounded to 1,26

答:
I am not sure if this solution will round up but the "step" property can help your case:

```<code><mat-form-field>
<input matInput type="number" [placeholder]="'Hours' | translate"
            formControlName="Work" (blur)="calculate()" step=".01"/>
</mat-form-field>
</code>```

This will allow to enter more values but will give error if exceeded 2 decimal places.
I hope it helps.

Body:
I have an input like the following:

<mat-form-field>
    <input matInput type="number" [placeholder]="'Hours' | translate"
                formControlName="Work" (blur)="calculate()" />
</mat-form-field>

Right now, the input allows unlimited decimals. I would like to only allow 2 decimals on that input. It could be done with any of the following solutions:

Restrict the input to 2 decimals, so that I can't insert more

Allow unlimited decimals and round to 2 decimals when I click another component

Is there any included feature in Angular for doing that? Otherwise,
  how can I create that restriction/rounding?

Example of the second option:

The user enters the value 1,2582399512

When the input is unfocused, the value is rounded to 1,26

Body:
I am not sure if this solution will round up but the "step" property can help your case:

<mat-form-field>
<input matInput type="number" [placeholder]="'Hours' | translate"
            formControlName="Work" (blur)="calculate()" step=".01"/>
</mat-form-field>

This will allow to enter more values but will give error if exceeded 2 decimal places.
I hope it helps.


问:
Setting up tsconfig with spec/test folder
Say I put my code under src and tests under spec:

```<code>+ spec
+ --- classA.spec.ts
+ src
+ --- classA.ts
+ --- classB.ts
+ --- index.ts
+ tsconfig.json
</code>```

I want to only transpile src to the dist folder. Since index.ts is the entry point of my package, my tsconfig.json look like this:

```<code>{
  "compileOptions": {
    "module": "commonjs"
    "outDir": "dist"
  },
  "files": {
    "src/index.ts",
    "typings/main.d.ts"
  }
}
</code>```

However, this tsconfig.json does not include the test files so I could not resolve dependencies in them.

On the other hand, if I include the test files into tsconfig.json then they are also transpiled to dist folder.

How do I solve this problem?

答:
Here is a detailed solution to manage sources and tests:

compilation includes sources and tests folders/files

build includes only sources

IDE (VSCode, ...)

Config

The solution is based on 2 tsconfig.json files as mentioned in other answers.

The main ./tsconfig.json (used for compilation and IDE):

```<code>{
  "compileOptions": {
    "module": "commonjs"
    "outDir": "dist"
  },
  "include": [
    "spec/**/*.spec.ts"
  ],
  "files": [
    "src/index.ts"
  ]
}
</code>```

The second ./tsconfig-build.json (used for build):

```<code>{
  "extends": "./tsconfig.json",
  "exclude": [
    "spec/**/*.spec.ts"
  ]
}
</code>```

Note: we exclude test files that have been included previously

Build

Build command: tsc -p tsconfig-build.json

Or npm run build if script is added in package.json:

{
  "scripts": {
    "build": "tsc -p tsconfig-build.json",
}

```

Body:
Say I put my code under src and tests under spec:

+ spec
+ --- classA.spec.ts
+ src
+ --- classA.ts
+ --- classB.ts
+ --- index.ts
+ tsconfig.json

I want to only transpile src to the dist folder. Since index.ts is the entry point of my package, my tsconfig.json look like this:

{
  "compileOptions": {
    "module": "commonjs"
    "outDir": "dist"
  },
  "files": {
    "src/index.ts",
    "typings/main.d.ts"
  }
}

However, this tsconfig.json does not include the test files so I could not resolve dependencies in them.

On the other hand, if I include the test files into tsconfig.json then they are also transpiled to dist folder.

How do I solve this problem?

Body:
Here is a detailed solution to manage sources and tests:

compilation includes sources and tests folders/files

build includes only sources

IDE (VSCode, ...)

Config

The solution is based on 2 tsconfig.json files as mentioned in other answers.

The main ./tsconfig.json (used for compilation and IDE):

{
  "compileOptions": {
    "module": "commonjs"
    "outDir": "dist"
  },
  "include": [
    "spec/**/*.spec.ts"
  ],
  "files": [
    "src/index.ts"
  ]
}

The second ./tsconfig-build.json (used for build):

{
  "extends": "./tsconfig.json",
  "exclude": [
    "spec/**/*.spec.ts"
  ]
}

Note: we exclude test files that have been included previously

Build

Build command: tsc -p tsconfig-build.json

Or npm run build if script is added in package.json:

{
  "scripts": {
    "build": "tsc -p tsconfig-build.json",
}


问:
Converting List<List<object>> to List<List<string>>
I have a collection of List<List<object>>. I need to convert it to List<List<string>>.
This is what i tried,

```<code>List<List<object>> dataOne = GetDataOne();
var dataTwo = dataOne.Select(x => x.Select(y => y.ToString()).ToList()).ToList();
</code>```

Is this method fine? Or is there any other best way to do it?

Is there anyway to automatically convert the list without iterating over it, or having the framework iterate over it

答:
Your approach is fine, you need to visit all the elements to convert them

however, a cleaner way to do this would be:

```<code>var dataTwo = dataOne.ConvertAll(x => x.ConvertAll(obj => obj.ToString()));
</code>```

Body:
I have a collection of List<List<object>>. I need to convert it to List<List<string>>.
This is what i tried,

List<List<object>> dataOne = GetDataOne();
var dataTwo = dataOne.Select(x => x.Select(y => y.ToString()).ToList()).ToList();

Is this method fine? Or is there any other best way to do it?

Is there anyway to automatically convert the list without iterating over it, or having the framework iterate over it

Body:
Your approach is fine, you need to visit all the elements to convert them

however, a cleaner way to do this would be:

var dataTwo = dataOne.ConvertAll(x => x.ConvertAll(obj => obj.ToString()));


问:
Mockito: How to partially use @InjectMocks-Annotation for MockMvc testing?
I need to test an controller and for the most parts it is still enough to use MockMvc. But there are still some branches which are very hard to generate an test case for. So I use Mockito for stubbing methods and to throw exception for this special test cases.

My controller implements an service and the setup looks like the following:

MyController.class:

```<code>@RestController
@RequestMapping("/myTest")
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(value = "/", method = { RequestMethod.POST }, produces = "application/json")
    public final int controllerMethod() {
        return myService.serviceMethod();
    }
}
</code>```

MyService.class:

```<code>@Service
public class MyService {
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public int serviceMethod() {
        return 5;
    }
}
</code>```

So I have multiple test methods and in some methods I mock the MyService.class to throw an exception for example.
But in other methods I want to test the normal functionalities. So here occures the problem.
If the tests are not running in the right order, the normal functionality test won't work, because MyService.class is still mocked, I guess.
So in this example, the serviceMethod returns null instead of 5.

Is there a way to partially InjectMocks - so I mean only for special methods and not for the class?

Here is the example code:

MyControllerTest.class:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
@WebAppConfiguration
public class MyControllerTest {
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    MyService myService;

    @InjectMocks
    @Resource
    MyController myController;

    @Resource
    private FilterChainProxy springSecurityFilterChain;

    private MockMvc mockMvc;

    @Before
    public void setup() throws SQLException {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
    }

    @Test
    @WithMockUser(username = "validUser", roles = { "ADMIN" })
    public void testMyController() throws Exception {
        mockMvc.perform(post("/myTest/").with(csrf())).andDo(print()).andExpect(status().is2xxSuccessful()).andExpect(jsonPath("$", is(5)));
    }

    @Test
    @WithMockUser(username = "validUser", roles = { "ADMIN" })
    public void testMyControllerException() throws Exception {
        myService = Mockito.spy(MyService.class);

        MockitoAnnotations.initMocks(this);

        Mockito.doThrow(new IndexOutOfBoundsException()).when(myService).serviceMethod();

        mockMvc.perform(post("/myTest/").with(csrf())).andDo(print()).andExpect(status().is4xxClientError());

        Mockito.verify(myService, Mockito.times(1)).serviceMethod();
    }
}
</code>```

So if I run especially only one of these tests, both working well.
But if I run both together and testMyControllerException() will be executed first, the testMyController() fails because of the mocked myService-Instance, I guess.

Is there any way to fix this problem or must I split this tests into two different testclasses?

I tried to find a way for unmocking the myController.class over the @After-Annotation with Mockito.reset(myController);. But did't worked for me.

答:
For jUnit4 you can use @FixMethodOrder(MethodSorters.NAME_ASCENDING) https://github.com/junit-team/junit4/wiki/Test-execution-order

I'd personally prefer to have it in different classes anyway.

Body:
I need to test an controller and for the most parts it is still enough to use MockMvc. But there are still some branches which are very hard to generate an test case for. So I use Mockito for stubbing methods and to throw exception for this special test cases.

My controller implements an service and the setup looks like the following:

MyController.class:

@RestController
@RequestMapping("/myTest")
public class MyController {

    @Autowired
    private MyService myService;

    @RequestMapping(value = "/", method = { RequestMethod.POST }, produces = "application/json")
    public final int controllerMethod() {
        return myService.serviceMethod();
    }
}

MyService.class:

@Service
public class MyService {
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public int serviceMethod() {
        return 5;
    }
}

So I have multiple test methods and in some methods I mock the MyService.class to throw an exception for example.
But in other methods I want to test the normal functionalities. So here occures the problem.
If the tests are not running in the right order, the normal functionality test won't work, because MyService.class is still mocked, I guess.
So in this example, the serviceMethod returns null instead of 5.

Is there a way to partially InjectMocks - so I mean only for special methods and not for the class?

Here is the example code:

MyControllerTest.class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
@WebAppConfiguration
public class MyControllerTest {
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    MyService myService;

    @InjectMocks
    @Resource
    MyController myController;

    @Resource
    private FilterChainProxy springSecurityFilterChain;

    private MockMvc mockMvc;

    @Before
    public void setup() throws SQLException {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
    }

    @Test
    @WithMockUser(username = "validUser", roles = { "ADMIN" })
    public void testMyController() throws Exception {
        mockMvc.perform(post("/myTest/").with(csrf())).andDo(print()).andExpect(status().is2xxSuccessful()).andExpect(jsonPath("$", is(5)));
    }

    @Test
    @WithMockUser(username = "validUser", roles = { "ADMIN" })
    public void testMyControllerException() throws Exception {
        myService = Mockito.spy(MyService.class);

        MockitoAnnotations.initMocks(this);

        Mockito.doThrow(new IndexOutOfBoundsException()).when(myService).serviceMethod();

        mockMvc.perform(post("/myTest/").with(csrf())).andDo(print()).andExpect(status().is4xxClientError());

        Mockito.verify(myService, Mockito.times(1)).serviceMethod();
    }
}

So if I run especially only one of these tests, both working well.
But if I run both together and testMyControllerException() will be executed first, the testMyController() fails because of the mocked myService-Instance, I guess.

Is there any way to fix this problem or must I split this tests into two different testclasses?

I tried to find a way for unmocking the myController.class over the @After-Annotation with Mockito.reset(myController);. But did't worked for me.


问:
display non-English language text in a message box
i wrote the following code in my application which is in MS Access, to display a message box in Farsi language(non-English language), but while i am typing in Farsi(Persion) it types in some special/unknown/different characters, and also while i run the application the message box displays that special/different characters instead of "احمد" which i want to be display.

msgbox("احمد")

any help well be my pleasure, and i really need for any kind of reply and help pleaseeeee.

答:
Might check into unicode options for the controls you're using.

Edit: Based on a bit of googling I did, there doesn't seem to be any unicode support built in to msgbox (surprise to me), but other controls do support it by default apparently, leading to custom solutions.  See below for links.

A forum post I found mentions a custom msgbox creator:
http://www.pcreview.co.uk/forums/msgbox-wont-display-unicode-characters-t2766299.html

Another post discussing how to make forms that will display a unicode message:
http://groups.google.com/group/microsoft.public.access/browse_frm/thread/4f2cd646023e0054/892dfd73309ad76b


问:
OrangeHRM internal error ocurred Pls contact system administrator
I'm new to orangeHRM. Please help me figure out what's wrong with installation. When I try to access using my credentials, it is successful however I'm getting this error msg:

```<code> internal error ocurred Pls contact system administrator
</code>```

I tried the solution here: link

But it didn't help. Does anyone here know how to print complete error logs? I really need your help.

Thanks.

答:
Switch to the appropriate php verion

Disable apache module for PHP 7.4.1

```<code>sudo a2dismod php7.4
# Enable the apache module for PHP 5.6
sudo a2enmod php5.6
# Set PHP 5.6 as default for the CLI
sudo update-alternatives --set php /usr/bin/php5.6
# Restart apache
sudo service apache2 restart
</code>```

Body:
I'm new to orangeHRM. Please help me figure out what's wrong with installation. When I try to access using my credentials, it is successful however I'm getting this error msg:

 internal error ocurred Pls contact system administrator

I tried the solution here: link

But it didn't help. Does anyone here know how to print complete error logs? I really need your help.

Thanks.

Body:
Switch to the appropriate php verion

Disable apache module for PHP 7.4.1

sudo a2dismod php7.4
# Enable the apache module for PHP 5.6
sudo a2enmod php5.6
# Set PHP 5.6 as default for the CLI
sudo update-alternatives --set php /usr/bin/php5.6
# Restart apache
sudo service apache2 restart


问:
How can I perform an ICMP ping in react-native
I'd like to have pure network level verification that an IP is reachable, not the HTTP level, since I am trying to verify connectivity with devices that may not implement HTTP.

I already use react-native-udp, react-native-tcp and other native bindings, but does not seem a method to achieve this goal.

Thanks

答:
You can use react-native-ping package to perform ICMP ping on react-native.

To install package:

```<code>npm i react-native-ping
</code>```

Body:
You can use react-native-ping package to perform ICMP ping on react-native.

To install package:

npm i react-native-ping


问:
react-loadable - Objects are not valid as a React child
I'm trying to implement lazy-loading components with react-loadable. I've followed their guide but I can't get it to work.

I've got 3 loadable components

```<code>const LazyOne = Loadable({
  loader: () => import(/* webpackChunkName: 'lazy-1' */"./components/LazyOne"),
  loading: <h1>wait</h1>
});

const LazyTwo = Loadable({
  loader: () => import(/* webpackChunkName: 'lazy-2' */"./components/LazyTwo"),
  loading: <h1>wait</h1>
});

const LazyThree = Loadable({
  loader: () => import(/* webpackChunkName: 'lazy-3' */"./components/LazyThree"),
  loading: <h1>espera</h1>
});
</code>```

At first the webpack build would break because it threw an unexpected input error on the import. So I added this to my .babelrc

```<code>"plugins": [
    // all my other plugins...
    "syntax-dynamic-import"
  ]
</code>```

Now the build is successfull and if I use webpack-bundle-analyzer I see all lazy builds built correctly!

But when I access my page that is rendered like so:

```<code>render() {
  return (
    <ErrorBoundary>
      <LazyOne {...this.props} />
    </ErrorBoundary>
  );
}
</code>```

This throws:

Objects are not valid as a React child (found: [object Promise]). If
  you meant to render a collection of children, use an array instead.

I see nothing mentioning this anywhere in react-loadables github or even code-splitting sections in webpack. What am I doing wrong?

EDIT

I've changed things up a bit and noticed it fails to load the lazy chunk.

my url is like this: localhost:3000/some/rest/1/edit

and the app is trying to fetch: localhost:3000/some/rest/1/lazy-1.bundle.js

Where should I specify the path?

答:
Took me hours to figure out but it turns out that just adding 'async' can break all hell out in React.. and you don't get any good feedback why.

```<code>const renderB2bApp = (store, callback) => {
  ReactDOM.render(
    <Provider store={store}>
      <B2BApp store={store} />
    </Provider>,
    appElement,
    callback,
  );
};

const B2BApp = async (props) => { {/* <--- async here!! remove it */ }
    // ...
    // it doesn't matter if you don't use `await` even just adding the async destroys it
}
</code>```

If you need to do async stuff then you need to render something immediately and then use hooks or state to update the component. So do not add async inside the ReactDom.render subcomponent!

Body:
I'm trying to implement lazy-loading components with react-loadable. I've followed their guide but I can't get it to work.

I've got 3 loadable components

const LazyOne = Loadable({
  loader: () => import(/* webpackChunkName: 'lazy-1' */"./components/LazyOne"),
  loading:
wait

});

const LazyTwo = Loadable({
  loader: () => import(/* webpackChunkName: 'lazy-2' */"./components/LazyTwo"),
  loading:
wait

});

const LazyThree = Loadable({
  loader: () => import(/* webpackChunkName: 'lazy-3' */"./components/LazyThree"),
  loading:
espera

});

At first the webpack build would break because it threw an unexpected input error on the import. So I added this to my .babelrc

"plugins": [
    // all my other plugins...
    "syntax-dynamic-import"
  ]

Now the build is successfull and if I use webpack-bundle-analyzer I see all lazy builds built correctly!

But when I access my page that is rendered like so:

render() {
  return (
    <ErrorBoundary>
      <LazyOne {...this.props} />
    </ErrorBoundary>
  );
}

This throws:

Objects are not valid as a React child (found: [object Promise]). If
  you meant to render a collection of children, use an array instead.

I see nothing mentioning this anywhere in react-loadables github or even code-splitting sections in webpack. What am I doing wrong?

EDIT

I've changed things up a bit and noticed it fails to load the lazy chunk.

my url is like this: localhost:3000/some/rest/1/edit

and the app is trying to fetch: localhost:3000/some/rest/1/lazy-1.bundle.js

Where should I specify the path?

Body:
Took me hours to figure out but it turns out that just adding 'async' can break all hell out in React.. and you don't get any good feedback why.

const renderB2bApp = (store, callback) => {
  ReactDOM.render(
    <Provider store={store}>
      <B2BApp store={store} />
    </Provider>,
    appElement,
    callback,
  );
};

const B2BApp = async (props) => { {/* <--- async here!! remove it */ }
    // ...
    // it doesn't matter if you don't use `await` even just adding the async destroys it
}

If you need to do async stuff then you need to render something immediately and then use hooks or state to update the component. So do not add async inside the ReactDom.render subcomponent!


问:
How to calculate correlation between all columns and remove highly correlated ones using pandas?
I have a huge data set and prior to machine learning modeling it is always suggested that first you should remove highly correlated descriptors(columns) how can i calculate the column wice correlation and remove the column with a threshold value say remove all the columns or descriptors having  >0.8 correlation.  also it should retained the headers in reduce data..

Example data set

```<code> GA      PN       PC     MBP      GR     AP
0.033   6.652   6.681   0.194   0.874   3.177
0.034   9.039   6.224   0.194   1.137   3.4
0.035   10.936  10.304  1.015   0.911   4.9
0.022   10.11   9.603   1.374   0.848   4.566
0.035   2.963   17.156  0.599   0.823   9.406
0.033   10.872  10.244  1.015   0.574   4.871
0.035   21.694  22.389  1.015   0.859   9.259
0.035   10.936  10.304  1.015   0.911   4.5
</code>```

Please help....

答:
You can test this code below ?

Load libraries import

```<code>  pandas as pd
  import numpy as np
# Create feature matrix with two highly correlated features

X = np.array([[1, 1, 1],
          [2, 2, 0],
          [3, 3, 1],
          [4, 4, 0],
          [5, 5, 1],
          [6, 6, 0],
          [7, 7, 1],
          [8, 7, 0],
          [9, 7, 1]])

# Convert feature matrix into DataFrame
df = pd.DataFrame(X)

# View the data frame
df

# Create correlation matrix
corr_matrix = df.corr().abs()

# Select upper triangle of correlation matrix
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))

# Find index of feature columns with correlation greater than 0.95
to_drop = [column for column in upper.columns if any(upper[column] > 0.95)]
# Drop features
df.drop(df[to_drop], axis=1)
</code>```

Body:
I have a huge data set and prior to machine learning modeling it is always suggested that first you should remove highly correlated descriptors(columns) how can i calculate the column wice correlation and remove the column with a threshold value say remove all the columns or descriptors having  >0.8 correlation.  also it should retained the headers in reduce data..

Example data set

 GA      PN       PC     MBP      GR     AP
0.033   6.652   6.681   0.194   0.874   3.177
0.034   9.039   6.224   0.194   1.137   3.4
0.035   10.936  10.304  1.015   0.911   4.9
0.022   10.11   9.603   1.374   0.848   4.566
0.035   2.963   17.156  0.599   0.823   9.406
0.033   10.872  10.244  1.015   0.574   4.871
0.035   21.694  22.389  1.015   0.859   9.259
0.035   10.936  10.304  1.015   0.911   4.5

Please help....

Body:
You can test this code below ?

Load libraries import

  pandas as pd
  import numpy as np
# Create feature matrix with two highly correlated features

X = np.array([[1, 1, 1],
          [2, 2, 0],
          [3, 3, 1],
          [4, 4, 0],
          [5, 5, 1],
          [6, 6, 0],
          [7, 7, 1],
          [8, 7, 0],
          [9, 7, 1]])

# Convert feature matrix into DataFrame
df = pd.DataFrame(X)

# View the data frame
df

# Create correlation matrix
corr_matrix = df.corr().abs()

# Select upper triangle of correlation matrix
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))

# Find index of feature columns with correlation greater than 0.95
to_drop = [column for column in upper.columns if any(upper[column] > 0.95)]
# Drop features
df.drop(df[to_drop], axis=1)


问:
How do I grab an element with jQuery without a way to reference it via class, ID, etc
I have a table like so:

```<code><table>
<thead>
    <tr>
        <th>Hostname</th>
        <th>Action</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>127.0.0.1</td>
        <td><a name="delete" onclick="remove_host('127.0.0.1')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.2</td>
        <td><a name="delete" onclick="remove_host('127.0.0.2')">Remove</a></td>
    </tr>
    <tr>
        <td>127.0.0.3</td>
        <td><a name="delete" onclick="remove_host('127.0.0.3')">Remove</a></td>
    </tr>
</tbody>
</code>```

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

答:
I am not sure whether you are able to change the markup or not, but here's one option.</p>

```<code><tr>
  <td>120.0.0.2</td>
  <td><a name="delete" data-ip="120.0.0.2">Remove</a></td>
</tr>

$("a[name=delete]").one("click", function(e) {
  e.preventDefault();
  $("<span>Loading</span>").insertBefore(this);
  var ip = $(this).hide().data("ip");
  remove_host(ip);
});
</code>```

Body:
I have a table like so:

        Hostname
        Action

        127.0.0.1
        Remove

        127.0.0.2
        Remove

        127.0.0.3
        Remove

What I'm trying to do is, when a user clicks on Remove, that the link is replaced with one of those loading images so the user can't repeatedly hit the link.

How do I get the a element, so to speak, so I can set the HTML accordingly with jQuery?

On other parts of the site, I'm able to attach a rel="host-1" (or similar) to the link, so I can easily reference it to change out the HTML.

Body:
I am not sure whether you are able to change the markup or not, but here's one option.

<tr>
  <td>120.0.0.2</td>
  <td><a name="delete" data-ip="120.0.0.2">Remove</a></td>
</tr>

$("a[name=delete]").one("click", function(e) {
  e.preventDefault();
  $("<span>Loading</span>").insertBefore(this);
  var ip = $(this).hide().data("ip");
  remove_host(ip);
});


问:
How to concatenate two webelement, iterate it and get the text out of concatenated Xpath
I am working with Page object model

My Page objects are as below:

```<code>    @FindBy(xpath = "//kendo-grid-list//table/tbody/tr/td[9]//div/p")
    List<WebElement> milestoneListSize;

    private static final String milestoneEditButton1 = "//uif-checklist-complex-group[";

    private static final String milestoneEditButton2 = "]//uif-checklist-table/table/tbody/tr/td[6]//a";

    public void clickMilestoneUser(milestoneListSize, String milestoneEditButton1 , String milestoneEditButton2 ) {

        String Actual;
        int totalsize = milestoneListSize.size();

        for (int i = 1; i <= totalsize; i++) {
        Actual = driver.findElement(By.xpath(milestoneEditButton1 + i + milestoneEditButton2)).getText();
        System.out.println(Actual );
        }

    }
</code>```

Don't know why this piece of code is not working?
Thanks for help in advance

答:
Use the first code if you want the concatenated result and second for seperate result

```<code>@FindBy(xpath = "//kendo-grid-list//table/tbody/tr/td[9]//div/p")
List<WebElement> milestoneListSize;

String milestoneEditButton1 = "//uif-checklist-complex-group[%d]//uif-checklist-table/table/tbody/tr/td[6]//a";

public void clickMilestoneUser(String milestoneEditButton1) {

        String actual = "";

        int totalsize = milestoneListSize.size();

        for (int i = 1; i <= totalsize; i++) {

            actual = actual+driver.findElement(By.xpath(String.format(milestoneEditButton1, i))).getText();
        }

        System.out.println(actual);

    }
</code>```

2:

```<code>@FindBy(xpath = "//kendo-grid-list//table/tbody/tr/td[9]//div/p")
List<WebElement> milestoneListSize;

String milestoneEditButton1 = "//uif-checklist-complex-group[%d]//uif-checklist-table/table/tbody/tr/td[6]//a";

public void clickMilestoneUser(String milestoneEditButton1) {

        String actual = "";

        int totalsize = milestoneListSize.size();

        for (int i = 1; i <= totalsize; i++) {

            actual = driver.findElement(By.xpath(String.format(milestoneEditButton1, i))).getText();
            System.out.println(actual);
        }

    }
</code>```

Body:
I am working with Page object model

My Page objects are as below:

    @FindBy(xpath = "//kendo-grid-list//table/tbody/tr/td[9]//div/p")
    List<WebElement> milestoneListSize;

    private static final String milestoneEditButton1 = "//uif-checklist-complex-group[";

    private static final String milestoneEditButton2 = "]//uif-checklist-table/table/tbody/tr/td[6]//a";

    public void clickMilestoneUser(milestoneListSize, String milestoneEditButton1 , String milestoneEditButton2 ) {

        String Actual;
        int totalsize = milestoneListSize.size();

        for (int i = 1; i <= totalsize; i++) {
        Actual = driver.findElement(By.xpath(milestoneEditButton1 + i + milestoneEditButton2)).getText();
        System.out.println(Actual );
        }

    }

Don't know why this piece of code is not working?
Thanks for help in advance

Body:
Use the first code if you want the concatenated result and second for seperate result

@FindBy(xpath = "//kendo-grid-list//table/tbody/tr/td[9]//div/p")
List<WebElement> milestoneListSize;

String milestoneEditButton1 = "//uif-checklist-complex-group[%d]//uif-checklist-table/table/tbody/tr/td[6]//a";

public void clickMilestoneUser(String milestoneEditButton1) {

        String actual = "";

        int totalsize = milestoneListSize.size();

        for (int i = 1; i <= totalsize; i++) {

            actual = actual+driver.findElement(By.xpath(String.format(milestoneEditButton1, i))).getText();
        }

        System.out.println(actual);

    }

2:

@FindBy(xpath = "//kendo-grid-list//table/tbody/tr/td[9]//div/p")
List<WebElement> milestoneListSize;

String milestoneEditButton1 = "//uif-checklist-complex-group[%d]//uif-checklist-table/table/tbody/tr/td[6]//a";

public void clickMilestoneUser(String milestoneEditButton1) {

        String actual = "";

        int totalsize = milestoneListSize.size();

        for (int i = 1; i <= totalsize; i++) {

            actual = driver.findElement(By.xpath(String.format(milestoneEditButton1, i))).getText();
            System.out.println(actual);
        }

    }


问:
RouteEnhancer with aspects throws InvalidParameterException
I used the example verbatim from the Changelog:

The only thing I changed was the limitToPages.

```<code>routeEnhancers:
  NewsPlugin:
    type: Extbase
    limitToPages: [82]
    extension: News
    plugin: Pi1
    routes:
      - { routePath: '/{news_title}', _controller: 'News::detail', _arguments: {'news_title': 'news'} }
    defaultController: 'News::detail'
    aspects:
      news_title:
        type: PersistedAliasMapper
        tableName: 'tx_news_domain_model_news'
        routeFieldName: 'path_segment'
        routeValuePrefix: '/'
</code>```

This throws an exception in 9.5.4:

```<code>Symfony\Component\Routing\Exception\InvalidParameterException
Parameter "tx_news_pi1__news" for route "tx_news_pi1_0" must match "[^/]++" ("" given) to generate a corresponding URL.

in /var/www/example/htdocs/typo3_src-9.5.4/vendor/symfony/routing/Generator/UrlGenerator.php line 155

at Symfony\Component\Routing\Generator\UrlGenerator->doGenerate(array('tx_news_pi1__news' => 0), array('_controller' => 'News::detail'), array(), array(array('variable', '/', '[^/]++', 'tx_news_pi1__news', true), array('text', '/aktuelles/artikel')), array('tx_news_pi1__news' => ''), 'tx_news_pi1_0', 1, array(), array())
in /var/www/example/htdocs/typo3_src-9.5.4/vendor/symfony/routing/Generator/UrlGenerator.php line 128
</code>```

Currently, no other route enhancers exist. But I successfully used a simpler configuration on that exact same page and that worked:

```<code>NewsDetail:
  type: Extbase
  limitToPages: [82]
  extension: News
  plugin: Pi1
  routes:
    - { routePath: '/{news_id}', _controller: 'News::detail', _arguments: {'news_id': 'news'} }
</code>```

Not sure where to look and how best to troubleshoot. I was hoping someone had similar problem or could point me in the right direction.

答:
Same problem for me, the problem was because 'path_segment' generated with Install Tool Wizard had a slash, like : "the-path/another-segment"

The solution is to check for slash in 'path_segment' and replace them with another symbol, request like this :

```<code>SELECT uid, pid, path_segment, title FROM tx_news_domain_model_news WHERE path_segment LIKE "%/%";
</code>```

and change path_segment like that : "the-path_another-segment"

Body:
I used the example verbatim from the Changelog:

The only thing I changed was the limitToPages.

routeEnhancers:
  NewsPlugin:
    type: Extbase
    limitToPages: [82]
    extension: News
    plugin: Pi1
    routes:
      - { routePath: '/{news_title}', _controller: 'News::detail', _arguments: {'news_title': 'news'} }
    defaultController: 'News::detail'
    aspects:
      news_title:
        type: PersistedAliasMapper
        tableName: 'tx_news_domain_model_news'
        routeFieldName: 'path_segment'
        routeValuePrefix: '/'

This throws an exception in 9.5.4:

Symfony\Component\Routing\Exception\InvalidParameterException
Parameter "tx_news_pi1__news" for route "tx_news_pi1_0" must match "[^/]++" ("" given) to generate a corresponding URL.

in /var/www/example/htdocs/typo3_src-9.5.4/vendor/symfony/routing/Generator/UrlGenerator.php line 155

at Symfony\Component\Routing\Generator\UrlGenerator->doGenerate(array('tx_news_pi1__news' => 0), array('_controller' => 'News::detail'), array(), array(array('variable', '/', '[^/]++', 'tx_news_pi1__news', true), array('text', '/aktuelles/artikel')), array('tx_news_pi1__news' => ''), 'tx_news_pi1_0', 1, array(), array())
in /var/www/example/htdocs/typo3_src-9.5.4/vendor/symfony/routing/Generator/UrlGenerator.php line 128

Currently, no other route enhancers exist. But I successfully used a simpler configuration on that exact same page and that worked:

NewsDetail:
  type: Extbase
  limitToPages: [82]
  extension: News
  plugin: Pi1
  routes:
    - { routePath: '/{news_id}', _controller: 'News::detail', _arguments: {'news_id': 'news'} }

Not sure where to look and how best to troubleshoot. I was hoping someone had similar problem or could point me in the right direction.

Body:
Same problem for me, the problem was because 'path_segment' generated with Install Tool Wizard had a slash, like : "the-path/another-segment"

The solution is to check for slash in 'path_segment' and replace them with another symbol, request like this :

SELECT uid, pid, path_segment, title FROM tx_news_domain_model_news WHERE path_segment LIKE "%/%";

and change path_segment like that : "the-path_another-segment"


问:
Get the same instance of ViewModel in Fragment which is defined in Activity with parameter
So, I am using Koin for dependency injection, Here is what I did inside a activity

```<code>class ModuleDetailActivity : AppCompatActivity() {

    private lateinit var moduleId:String
    private lateinit var levelModule:Level.Module

    private val moduleViewModel: ModuleViewModel by viewModel { parameterOf(moduleId, levelModule) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ...
        ...

        moduleId = intent.getString("module_id")
        levelModule = intent.getParcelable("level_module")

        ...
        ...
    }
}
</code>```

Now, I have multiple fragment which ModuleDetailActivity can add or replace and I want the same instance of moduleViewModel in those fragments without passing any parameters inside Fragment.

```<code>class ModuleDetailFragment : Fragment() {

    private val moduleViewModel: ModuleViewModel by sharedViewModel()

    ...
    ...
}
</code>```

I know this will throw a error and as expected you can see this

```<code>Caused by: org.koin.core.error.InstanceCreationException: Could not create instance for [Factory:'****.ui.module.ModuleViewModel']
</code>```

This is how I have initialized the module

```<code>val viewModelModule = module {
    viewModel { (id : String, levelModule:Level.Module) -> ModuleViewModel(id, levelModule, get()) }
}
</code>```

Is there any solution on how I can get the same instance of ModuleViewModel defined inside activity without passing parameter inside a Fragment?

答:
You should initialise viewModel as below:

```<code>class ModuleDetailActivity : AppCompatActivity() {

    private val moduleId: String by lazy {
        intent.getString("module_id")
    }

    private val levelModule: Level.Module by lazy {
        intent.getParcelable("level_module")
    }

    private val moduleViewModel: ModuleViewModel by viewModel {
        parameterOf(moduleId, levelModule)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ...
        ...

        viewModel.doYourStuff()

        ...
        ...
    }
}
</code>```

We should use get() or inject() for plain Java objects only. To inject ViewModel, they provided separate way as viewModel()

Not sure why it isn't working for you.

Body:
So, I am using Koin for dependency injection, Here is what I did inside a activity

class ModuleDetailActivity : AppCompatActivity() {

    private lateinit var moduleId:String
    private lateinit var levelModule:Level.Module

    private val moduleViewModel: ModuleViewModel by viewModel { parameterOf(moduleId, levelModule) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ...
        ...

        moduleId = intent.getString("module_id")
        levelModule = intent.getParcelable("level_module")

        ...
        ...
    }
}

Now, I have multiple fragment which ModuleDetailActivity can add or replace and I want the same instance of moduleViewModel in those fragments without passing any parameters inside Fragment.

class ModuleDetailFragment : Fragment() {

    private val moduleViewModel: ModuleViewModel by sharedViewModel()

    ...
    ...
}

I know this will throw a error and as expected you can see this

Caused by: org.koin.core.error.InstanceCreationException: Could not create instance for [Factory:'****.ui.module.ModuleViewModel']

This is how I have initialized the module

val viewModelModule = module {
    viewModel { (id : String, levelModule:Level.Module) -> ModuleViewModel(id, levelModule, get()) }
}

Is there any solution on how I can get the same instance of ModuleViewModel defined inside activity without passing parameter inside a Fragment?

Body:
You should initialise viewModel as below:

class ModuleDetailActivity : AppCompatActivity() {

    private val moduleId: String by lazy {
        intent.getString("module_id")
    }

    private val levelModule: Level.Module by lazy {
        intent.getParcelable("level_module")
    }

    private val moduleViewModel: ModuleViewModel by viewModel {
        parameterOf(moduleId, levelModule)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        ...
        ...

        viewModel.doYourStuff()

        ...
        ...
    }
}

We should use get() or inject() for plain Java objects only. To inject ViewModel, they provided separate way as viewModel()

Not sure why it isn't working for you.


问:
how to check the SharedPreferences string is empty or null
I print the fotonew key and it sends a null value. But if urlfoto is empty or not, if (urlfoto! = Null &&! Urlfoto.equals (" ")) goes to this section. Normally he should go to else. The urlfoto value goes to the part with a full urlfoto value in the case of null but if else. I want to check if the key I pulled is empty or full.

```<code>SharedPreferences sharedPrefNew = getContext().getSharedPreferences("sharedPref",Context.MODE_PRIVATE);

urlfoto = sharedPrefNew.getString("fotonew", "");

if(urlfoto!= null && !urlfoto.equals(""))
{
    ...
}
else {
    System.out.println("boş");
    ...
}
</code>```

答:
Check below code     </p>

```<code>   if (sharedPrefNew.getString("fotonew", "") != null && !sharedPrefNew.getString("fotonew", "").isEmpty()){
       //your code here
    }
</code>```

Body:
I print the fotonew key and it sends a null value. But if urlfoto is empty or not, if (urlfoto! = Null &&! Urlfoto.equals (" ")) goes to this section. Normally he should go to else. The urlfoto value goes to the part with a full urlfoto value in the case of null but if else. I want to check if the key I pulled is empty or full.

SharedPreferences sharedPrefNew = getContext().getSharedPreferences("sharedPref",Context.MODE_PRIVATE);

urlfoto = sharedPrefNew.getString("fotonew", "");

if(urlfoto!= null && !urlfoto.equals(""))
{
    ...
}
else {
    System.out.println("boş");
    ...
}

Body:
Check below code

   if (sharedPrefNew.getString("fotonew", "") != null && !sharedPrefNew.getString("fotonew", "").isEmpty()){
       //your code here
    }


问:
Central Cache for Winforms applications network on multiple machines
I am using .NET Cache for WinForms application in C#. Application is directly connected to the remote database server (without any service layer) and the cache is maintained on client machine where application is installed.

Now I am making it to work on multiple machines on network and instances will be connected to the central database. Problem is that when one instance add record in database, other machines still contain the cache for old data.

I would need to know the possible solution to make this cache central for all application instances on network so when data is modified by one instance, cache will be refreshed for the rest of network nodes.

How can we implement the central cache for all application instances on network?

答:
we had same issue and we implement the cache into the database.

(If you don't have any service Layer, you can use DB Layer Procedure or Trigger Etc..)

Firstly we made Cashe Table. for example CACHE_DATA.

And After machine(more than one) executes DML(Update, Insert, Delete Data), the Service Layer(or DB) Updates a Cache Data based on the newest Information. so that other Machines also can refer to that Table.

If DML executed too often, you can add "Last Cashing Time" Filed in CHACHE_DATA.

If(Last Cashing Time < Casing_Interval )
{
  Do Not Chasing
}
else
{
  Cahsing
}


问:
VSIX plugin that builds a release, is it possible?
so I have been working on a VSIX plugin for visual studio that makes an release build.
The current plugin consists of a command box that gives a messages, the message is either yes or no deppending on the existence of a certain file.
but that doesnt have a lot to do with what I want.

I have done research and I am unable to find any documentation or other people who tried this.
My colleague pointed me to a SolutionBuild Interface but that doesnt seem to have helped me at all. It does have some functionality that I would like (the Deploy method for instance) but just doesnt seem to be working properly.

in short. i want my little command plugin to be able to build a release build (of a project that is curently open like a simple windows form) to a defined loacation.

Microsoft Visual Studio Community 2019
Version 16.4.4

答: The procedure given here may help you to Release/Debug to a defined location.


问:
convert 2020-02-17 to ddd, MMM Do YYYY in angular
Hi am trying to convert convert 2020-02-17 to (ddd, MMM Do YYYY) using moment.js

```<code> transform(value: any, args?: any): any {
    console.log(value)
    console.log(moment(value).format("ddd, MMM Do YYYY"))
    return moment(value).format("ddd, MMM Do YYYY");
  }
</code>```

i have created a pipe for it but it is returning me the value based on current date
can somebody help

答:
This should be working, as you can see on this example : JSFiddle

```<code>transform(value: any, args ?: any): any {
  return moment(value).format("ddd, MMM Do YYYY");
}
</code>```

So your transform pipe should return Mon, Feb 17th 2020.

See Angular Example.

Body:
Hi am trying to convert convert 2020-02-17 to (ddd, MMM Do YYYY) using moment.js

 transform(value: any, args?: any): any {
    console.log(value)
    console.log(moment(value).format("ddd, MMM Do YYYY"))
    return moment(value).format("ddd, MMM Do YYYY");
  }

i have created a pipe for it but it is returning me the value based on current date
can somebody help

Body:
This should be working, as you can see on this example : JSFiddle

transform(value: any, args ?: any): any {
  return moment(value).format("ddd, MMM Do YYYY");
}

So your transform pipe should return Mon, Feb 17th 2020.

See Angular Example.


问:
Missing text from Elasticsearch highlighted text when field contains exclamation mark
When searching for a text and requesting results query highlight, if the matched document field contains exclamation mark, then the returned highlighted text does not contain part of the text that contains the exclamation mark

Elasticsearch version 7.1.1

document: { "name" : "Yahoo! Inc [Please refer to Altaba Inc and Verizon Communications Inc]"}
searching with highlight for "inc" wildcard

expected:
highlighed text should be:

```<code>"Yahoo! <em>Inc</em> [Please refer to Altaba <em>Inc</em> and Verizon Communications <em>Inc</em>]"
</code>```

actual:
"Yahoo!" is missing from the response. Got:

```<code>"<em>Inc</em> [Please refer to Altaba <em>Inc</em> and Verizon Communications <em>Inc</em>]"
</code>```

I think this was something to do with the ! mark. If I remove that then everything is OK.

Steps to reproduce:

Add document to a new index

```<code>POST test/_doc/ { "name" : "Yahoo! Inc [Please refer to Altaba Inc and Verizon Communications Inc]" }
</code>```

no other settings / mapping

Run the query

```<code>GET test/_search { "query": { "bool": { "should": [ { "wildcard": { "name": { "wildcard": "inc*" } } } ] } }, "highlight": { "fields": { "name" : {} } } }
</code>```

Got following results:

```<code>"hits" : [ { "_index" : "test", "_type" : "_doc", "_id" : "511tP3ABoqekxkoUshVf", "_score" : 1.0, "_source" : { "name" : "Yahoo! Inc [Please refer to Altaba Inc and Verizon Communications Inc]" }, "highlight" : { "name" : [ "<em>Inc</em> [Please refer to Altaba <em>Inc</em> and Verizon Communications <em>Inc</em>]" ] } } ]
</code>```

expecting highlight:

```<code>"Yahoo! <em>Inc</em> [Please refer to Altaba <em>Inc</em> and Verizon Communications <em>Inc</em>]"
</code>```

答:
This is expected behavior because, by default, the Elasticsearch highlight returns a part of the searched text (fragments) see: https://www.elastic.co/guide/en/elasticsearch/reference/7.1/search-request-highlighting.html#unified-highlighter

! and . are considered end of previous sentence and the highlight does not return that fragment.

In my case, the searched text was representing a name which had a small text length and by adding "number_of_fragments" : 0 I am forcing the highlight to return the entire document field.

```<code>"highlight": {
  "fields": {
     "name" : {"number_of_fragments" : 0}
  }
}
</code>```

same as: https://github.com/elastic/elasticsearch/issues/52333

Body:
When searching for a text and requesting results query highlight, if the matched document field contains exclamation mark, then the returned highlighted text does not contain part of the text that contains the exclamation mark

Elasticsearch version 7.1.1

document: { "name" : "Yahoo! Inc [Please refer to Altaba Inc and Verizon Communications Inc]"}
searching with highlight for "inc" wildcard

expected:
highlighed text should be:

"Yahoo! Inc [Please refer to Altaba Inc and Verizon Communications Inc]"

actual:
"Yahoo!" is missing from the response. Got:

"Inc [Please refer to Altaba Inc and Verizon Communications Inc]"

I think this was something to do with the ! mark. If I remove that then everything is OK.

Steps to reproduce:

Add document to a new index

POST test/_doc/ { "name" : "Yahoo! Inc [Please refer to Altaba Inc and Verizon Communications Inc]" }

no other settings / mapping

Run the query

GET test/_search { "query": { "bool": { "should": [ { "wildcard": { "name": { "wildcard": "inc*" } } } ] } }, "highlight": { "fields": { "name" : {} } } }

Got following results:

"hits" : [ { "_index" : "test", "_type" : "_doc", "_id" : "511tP3ABoqekxkoUshVf", "_score" : 1.0, "_source" : { "name" : "Yahoo! Inc [Please refer to Altaba Inc and Verizon Communications Inc]" }, "highlight" : { "name" : [ "Inc [Please refer to Altaba Inc and Verizon Communications Inc]" ] } } ]

expecting highlight:

"Yahoo! Inc [Please refer to Altaba Inc and Verizon Communications Inc]"

Body:
This is expected behavior because, by default, the Elasticsearch highlight returns a part of the searched text (fragments) see: https://www.elastic.co/guide/en/elasticsearch/reference/7.1/search-request-highlighting.html#unified-highlighter

! and . are considered end of previous sentence and the highlight does not return that fragment.

In my case, the searched text was representing a name which had a small text length and by adding "number_of_fragments" : 0 I am forcing the highlight to return the entire document field.

"highlight": {
  "fields": {
     "name" : {"number_of_fragments" : 0}
  }
}

same as: https://github.com/elastic/elasticsearch/issues/52333


问:
Delete line in powershell file
I have a file with the following lines

```<code>Servicetag
P4M8K82
P4M8l582
O5M8K82
</code>```

I wish I had the serial numbers only and not the name ServiceTag.
I would like: Browse the .csv file if the line contains SerivceTag then you don't get the value and copy the rest.

As a result, I wish I had:

```<code>P4M8K82
P4M8l582
O5M8K82
</code>```

Do you think it's possible?

答:
Since it is a CSV header, you can just skip first line:</p>

```<code>#demo file
@"
Servicetag
P4M8K82
P4M8l582
O5M8K82
"@ | out-file Test.csv

#solution to get items
cat test.csv | select -Skip 1

#or write them to file
cat test.csv | select -Skip 1 | Out-file output.txt
</code>```

Title: Delete line in powershell file

Body:
I have a file with the following lines

Servicetag
P4M8K82
P4M8l582
O5M8K82

I wish I had the serial numbers only and not the name ServiceTag.
I would like: Browse the .csv file if the line contains SerivceTag then you don't get the value and copy the rest.

As a result, I wish I had:

P4M8K82
P4M8l582
O5M8K82

Do you think it's possible?

Body:
Since it is a CSV header, you can just skip first line:

#demo file
@"
Servicetag
P4M8K82
P4M8l582
O5M8K82
"@ | out-file Test.csv

#solution to get items
cat test.csv | select -Skip 1

#or write them to file
cat test.csv | select -Skip 1 | Out-file output.txt


问:
Getting errors in decoding json to swift model class
I am trying to decode a JSON Response and getting the error every time. I also tried to make a model class from online tool but it doesn't decode it to the swift model class. When I printed the localized description it tells that The given data is not in the correct format. Below is my model class. Where as the error says

Swift.DecodingError.typeMismatch(Swift.Dictionary,
  Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue:
  "ResponseDescription", intValue: nil)], debugDescription: "Expected to
  decode Dictionary but found a string/data instead.",
  underlyingError: nil))

Model Class

```<code>struct ResponseLogin: Decodable{
    let Status:Bool
    let Message: String
    let ResponseDescription: ResponseDescription
    let EncryptStatus: Bool

    struct ResponseDescription: Decodable{
        let ID:Int
        let CustomerWebID: Int
        let CustomerWalletID: Int
        let CellNo: String
        let FirstName: String
        let LastName: String
        let Email: String
        let SahulatWalletCard: String
        let City: String
        let Address: String
        let ProfilePicture: String
        let TokenNo: String
        let ResponseStatus: String
        let ResponseMessage: String
    }
}
</code>```

JSON response

```<code>{
"Status": true,
"Message":"Login Successfully",
"ResponseDescription":
{
"ID": 1459,
"CustomerWebID": 6275,
"CustomerWalletID": 321123,
"CellNo": "0332334001",
"FirstName": "Haris",
"LastName": "Khan",
"Email": "myemail@gmail.com",
"SahulatWalletCard": "3085040101018537",
"City": "Karachi",
"RegionID": 1,
"Address": "Test1",
"ProfilePicture": "http://images/mypic.png",
"TokenNo": "Xxxx==2121mcmvjmdx!",
"ResponseStatus": true,
"ResponseMessage": "Data Found"
},
"EncryptStatus": true
}

Decrypted JSON
{
  "Status": true,
  "Message": "Login Successfully",
  "ResponseDescription":"Qmw25wKdmOpbUxP3pMRGnVP9yHcsJhVISyA6s3oBHrkpGsAlbR27xsbcsZqXd0z3A6h1tB1i/sOZFuZaMTNMBTevq3N7xG8KBw50WauLDHFqJ4JbAkh6RKUPOLcpmdIrEZ2jgfJrA+dNrftbjIjnEohg4jF/oLDKs7sjE1Ozk/3C1JnFTHNnc5vSrQNNUUOzrB4+QOxMGqpdNrF4BCh7YQ9xT1w/8D3BNM/7LXhb5txqbCEdRI7yf6R+tw5Mey4NR6NXAYdfGCnWKLsrnU2FwTKKRG2PqBZ7hLa2Ee8Uva0OAStvkldMWs8Heh9oS8T3Z39goyxFJme3N7x9JRzZyHmTbc6JqPI2kwWDwYztxxK6bft4tXwumPjJHx91ScNm2JCLQworqvlyHeOa8oBoXK6xym/PrAPCJ3Mwa3MHXhrU8U8mONFmtp3zZdPyXmHayE6E9meZtxbABEihBkOra4257s5rF3Zyr8WtHbwXYMA1dDF/lESwjiyG9Q/KHHgem8QyB3P9xSVi5vKqfFnqZfBusYTMNqDF+V8C2L9YjEp2bdyq7lUPEu0jWMRqpYDyAO+Z864cwbnb0V1fEfE3xI7Z8/PqlQ5hp7mR5VwL4k6pekagZDNXKo4qOTy6PGsod0x7KY0bLddL6qv1MrcyzcH7K1016fy5R/3DemkAmXn0/d6OleVHDr8zpC9D4ZZrY8JghRCA7Vb/b5itX9VC41dL/3PcZBbXsiOFnnJmr/2zNj6QXBK4+b/S42Wh2vBK",
"EncryptStatus": true
}

</code>```

Any kind help can let me point my mistake in this problem.

答:
typealias Codable = Encodable & Decodable

which conforms to both Encodable and Decodable.

```<code>struct MovieDetail: Codable {
    var language: String
    var genre: String
    var releaseDate: String
    var bannerImageUrl: String
}

struct Movie: Codable {
    var movieId: Int
    var name: String
    var movieDetails: MovieDetail
}
</code>```

[For More Detail]

https://medium.com/@manojkarkie/encodable-and-decodable-in-swift-4-747328a7c7c5

Body:
I am trying to decode a JSON Response and getting the error every time. I also tried to make a model class from online tool but it doesn't decode it to the swift model class. When I printed the localized description it tells that The given data is not in the correct format. Below is my model class. Where as the error says

Swift.DecodingError.typeMismatch(Swift.Dictionary,
  Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue:
  "ResponseDescription", intValue: nil)], debugDescription: "Expected to
  decode Dictionary but found a string/data instead.",
  underlyingError: nil))

Model Class

struct ResponseLogin: Decodable{
    let Status:Bool
    let Message: String
    let ResponseDescription: ResponseDescription
    let EncryptStatus: Bool

    struct ResponseDescription: Decodable{
        let ID:Int
        let CustomerWebID: Int
        let CustomerWalletID: Int
        let CellNo: String
        let FirstName: String
        let LastName: String
        let Email: String
        let SahulatWalletCard: String
        let City: String
        let Address: String
        let ProfilePicture: String
        let TokenNo: String
        let ResponseStatus: String
        let ResponseMessage: String
    }
}

JSON response

{
"Status": true,
"Message":"Login Successfully",
"ResponseDescription":
{
"ID": 1459,
"CustomerWebID": 6275,
"CustomerWalletID": 321123,
"CellNo": "0332334001",
"FirstName": "Haris",
"LastName": "Khan",
"Email": "myemail@gmail.com",
"SahulatWalletCard": "3085040101018537",
"City": "Karachi",
"RegionID": 1,
"Address": "Test1",
"ProfilePicture": "http://images/mypic.png",
"TokenNo": "Xxxx==2121mcmvjmdx!",
"ResponseStatus": true,
"ResponseMessage": "Data Found"
},
"EncryptStatus": true
}

Decrypted JSON
{
  "Status": true,
  "Message": "Login Successfully",
  "ResponseDescription":"Qmw25wKdmOpbUxP3pMRGnVP9yHcsJhVISyA6s3oBHrkpGsAlbR27xsbcsZqXd0z3A6h1tB1i/sOZFuZaMTNMBTevq3N7xG8KBw50WauLDHFqJ4JbAkh6RKUPOLcpmdIrEZ2jgfJrA+dNrftbjIjnEohg4jF/oLDKs7sjE1Ozk/3C1JnFTHNnc5vSrQNNUUOzrB4+QOxMGqpdNrF4BCh7YQ9xT1w/8D3BNM/7LXhb5txqbCEdRI7yf6R+tw5Mey4NR6NXAYdfGCnWKLsrnU2FwTKKRG2PqBZ7hLa2Ee8Uva0OAStvkldMWs8Heh9oS8T3Z39goyxFJme3N7x9JRzZyHmTbc6JqPI2kwWDwYztxxK6bft4tXwumPjJHx91ScNm2JCLQworqvlyHeOa8oBoXK6xym/PrAPCJ3Mwa3MHXhrU8U8mONFmtp3zZdPyXmHayE6E9meZtxbABEihBkOra4257s5rF3Zyr8WtHbwXYMA1dDF/lESwjiyG9Q/KHHgem8QyB3P9xSVi5vKqfFnqZfBusYTMNqDF+V8C2L9YjEp2bdyq7lUPEu0jWMRqpYDyAO+Z864cwbnb0V1fEfE3xI7Z8/PqlQ5hp7mR5VwL4k6pekagZDNXKo4qOTy6PGsod0x7KY0bLddL6qv1MrcyzcH7K1016fy5R/3DemkAmXn0/d6OleVHDr8zpC9D4ZZrY8JghRCA7Vb/b5itX9VC41dL/3PcZBbXsiOFnnJmr/2zNj6QXBK4+b/S42Wh2vBK",
"EncryptStatus": true
}

Any kind help can let me point my mistake in this problem.

Body:
typealias Codable = Encodable & Decodable

which conforms to both Encodable and Decodable.

struct MovieDetail: Codable {
    var language: String
    var genre: String
    var releaseDate: String
    var bannerImageUrl: String
}

struct Movie: Codable {
    var movieId: Int
    var name: String
    var movieDetails: MovieDetail
}

[For More Detail]

https://medium.com/@manojkarkie/encodable-and-decodable-in-swift-4-747328a7c7c5


问:
How to iterate a big list to make it smaller for a REST call using Java streams?
I have logic something like this to process in chunks.

```<code>List<String> bigList = getList(); // Returns a big list of 1000 recs
int startIndex=0;
boolean entireListNotProcessed=false;
while(entireListNotProcessed) {
   int endIndex = startIndex + 100;
   if(endIndex > myList.size()-1) {
      endIndex=myList.size()-1;
   }
   List<String> subList= bigList.subList(startIndex, endIndex);
   //call Rest API with subList and update entireListNotProcessed flag...
}
</code>```

Is there a better way of doing this iteration using java streams?

答:
You could use ListUtils from apache commons to do the splitting for you (if you really need to since 1000 is not that muuch)</p>

```<code>List<List<Integer>> output = ListUtils.partition(largeList, targetSize);
</code>```

Body:
I have logic something like this to process in chunks.

List<String> bigList = getList(); // Returns a big list of 1000 recs
int startIndex=0;
boolean entireListNotProcessed=false;
while(entireListNotProcessed) {
   int endIndex = startIndex + 100;
   if(endIndex > myList.size()-1) {
      endIndex=myList.size()-1;
   }
   List<String> subList= bigList.subList(startIndex, endIndex);
   //call Rest API with subList and update entireListNotProcessed flag...
}

Is there a better way of doing this iteration using java streams?

Body:
You could use ListUtils from apache commons to do the splitting for you (if you really need to since 1000 is not that muuch)

List<List<Integer>> output = ListUtils.partition(largeList, targetSize);


问:
Using strings as arguments of a function
There is plenty of questions on this topic on SO, including this question on how to evaluate expressions, this one showing some disagreement about using eval, and this answer showing the eval(substitute(.)) trick.
A good reference to learn about non-standard evaluation (NSE) is the metaprogramming section of Advanced R, by Hadley Wickham.
I note a lot of disagreement in the answers, with some signalling the problems of using strings as something to be evaluated.

I am in this condition of using a character string as an argument for a child function.

Here is a reprex:

```<code># Consider a little toy function:
little_fun <- function(z = 2, y = 1) {
     (z + 2) / y
}
little_fun()
#> [1] 4

# I can call little_fun() on lists of arguments:
z_list <- c(1,2,3)
purrr::map_dbl(.x = z_list, ~ little_fun(z = (.x)))   # This is basically a tidyverse equivalent for lapply()
#> [1] 3 4 5

# or also:
z_list <- c(1,2,3)
y_list <- c(-1, 0, 1)
purrr::map2_dbl(.x = z_list, .y = y_list, ~ little_fun(z = (.x), y = (.y)))  # again, similar to mapply()
#> [1]  -3 Inf   5

# But I also want to assign the parameters from a more general parent function:
big_fun <- function(par = "y") {

     stopifnot(par %in% c("z", "y"))

     par_list <- c(1,2,3)
     purrr::map_dbl(.x = par_list, ~ little_fun(par = (.x)))   # <--- key line <---
}
big_fun()
#> Error in little_fun(par = (.x)): unused argument (par = (.x))
</code>```

My problem: I am still unable to get my code running.

My question: why is it bad to use characters as function arguments? Should I avoid this? and how? I would like to understand how to improve my reasoning and learn available alternatives.

答:
I don't disagree with chinsoon12's answer to your question of "Should I avoid this?"

"protect yourself against future stupidity" – chinsoon12

Having said that, dynamically-assigned parameter names is one place where do.call comes in handy.

big_fun <- function(par = "y") {
     stopifnot(par %in% c("z", "y"))
     par_list <- c(1,2,3)
     purrr::map_dbl(.x = par_list, ~do.call(little_fun, as.list(setNames(.x, par))))
}

big_fun()
# [1] 4.000000 2.000000 1.333333
big_fun("z")
# [1] 3 4 5
```

<p>I personally find programming like this at times mind-warping and problematic, and at others perhaps the only way to solve some problem elegantly. Sometimes it is the most terse, robust, and efficient solution available.</p>

<p>And just to check, I believe <code>big_fun()</code> by itself should match this:</p>

<pre class="lang-r prettyprint-override"><code>sapply(1:3, little_fun, z=2)
# [1] 4.000000 2.000000 1.333333
</code>```

Body:
There is plenty of questions on this topic on SO, including this question on how to evaluate expressions, this one showing some disagreement about using eval, and this answer showing the eval(substitute(.)) trick.
A good reference to learn about non-standard evaluation (NSE) is the metaprogramming section of Advanced R, by Hadley Wickham.
I note a lot of disagreement in the answers, with some signalling the problems of using strings as something to be evaluated.

I am in this condition of using a character string as an argument for a child function.

Here is a reprex:

# Consider a little toy function:
little_fun <- function(z = 2, y = 1) {
     (z + 2) / y
}
little_fun()
#> [1] 4

# I can call little_fun() on lists of arguments:
z_list <- c(1,2,3)
purrr::map_dbl(.x = z_list, ~ little_fun(z = (.x)))   # This is basically a tidyverse equivalent for lapply()
#> [1] 3 4 5

# or also:
z_list <- c(1,2,3)
y_list <- c(-1, 0, 1)
purrr::map2_dbl(.x = z_list, .y = y_list, ~ little_fun(z = (.x), y = (.y)))  # again, similar to mapply()
#> [1]  -3 Inf   5

# But I also want to assign the parameters from a more general parent function:
big_fun <- function(par = "y") {

     stopifnot(par %in% c("z", "y"))

     par_list <- c(1,2,3)
     purrr::map_dbl(.x = par_list, ~ little_fun(par = (.x)))   # <--- key line <---
}
big_fun()
#> Error in little_fun(par = (.x)): unused argument (par = (.x))

My problem: I am still unable to get my code running.

My question: why is it bad to use characters as function arguments? Should I avoid this? and how? I would like to understand how to improve my reasoning and learn available alternatives.

Body:
I don't disagree with chinsoon12's answer to your question of "Should I avoid this?"

"protect yourself against future stupidity" – chinsoon12

Having said that, dynamically-assigned parameter names is one place where do.call comes in handy.

big_fun <- function(par = "y") {
     stopifnot(par %in% c("z", "y"))
     par_list <- c(1,2,3)
     purrr::map_dbl(.x = par_list, ~do.call(little_fun, as.list(setNames(.x, par))))
}

big_fun()
# [1] 4.000000 2.000000 1.333333
big_fun("z")
# [1] 3 4 5

I personally find programming like this at times mind-warping and problematic, and at others perhaps the only way to solve some problem elegantly. Sometimes it is the most terse, robust, and efficient solution available.

And just to check, I believe big_fun() by itself should match this:

sapply(1:3, little_fun, z=2)
# [1] 4.000000 2.000000 1.333333


问:
Not calling fragment in activity using ViewPager for TableLayout
Hi in the below activity I have bottom navigation item named as opportunity .When I am click on the opportunity want to call TabLayout contains two tabs names as sales stage and support required.

From activity not calling my fragments .

Can any one help me

Acivity.java:

```<code>public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;

private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private ProgressDialog progressDialog = null;
String sessionId;
private ViewPager viewPager;
MenuItem refreshMenuItem;
TabLayout tabLayout;
Fragment fragment;
private RecyclerView.LayoutManager layoutManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sessionId = getIntent().getStringExtra("sessionId");
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    toolbar.setTitle("Home");

    loadFragment(new TaskFragement());
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setupWithViewPager(viewPager);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    recyclerView.setHasFixedSize(true);

    // use a linear layout manager
   // layoutManager = new LinearLayoutManager(this);
    //recyclerView.setLayoutManager(layoutManager);

    //recyclerView.setAdapter(mAdapter);
    initNavigationDrawer();
    initBottomNavigationItems();

}

public void initNavigationDrawer() {

    NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            int id = menuItem.getItemId();

            switch (id){
                case R.id.home:
                    Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
                    drawerLayout.closeDrawers();
                    break;
                case R.id.settings:
                    Toast.makeText(getApplicationContext(),"Settings",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.trash:
                    Toast.makeText(getApplicationContext(),"History",Toast.LENGTH_SHORT).show();
                    drawerLayout.closeDrawers();
                    break;
                case R.id.logout:
                    finish();

            }
            return true;
        }
    });
    View header = navigationView.getHeaderView(0);
    TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
    tv_email.setText("GenWorks Solutions");
    drawerLayout = (DrawerLayout)findViewById(R.id.drawer);

    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){

        @Override
        public void onDrawerClosed(View v){
            super.onDrawerClosed(v);
        }

        @Override
        public void onDrawerOpened(View v) {
            super.onDrawerOpened(v);
        }
    };
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();
}

public void initBottomNavigationItems() {

    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.task:
                    toolbar.setTitle("Task");
                    fragment = new TaskFragement();
                    loadFragment(fragment);
                    return true;
                case R.id.account:
                    toolbar.setTitle("Account");
                    fragment = new AccountFragement();
                    sessionId = getIntent().getStringExtra("sessionId");
                    loadFragment(fragment);
                    return true;
                case R.id.contact:
                    toolbar.setTitle("Contact");
                    fragment = new ContactFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.opportunity:
                    toolbar.setTitle("Opportunity");
                    tabLayout.setVisibility(View.VISIBLE);
                    viewPager.setVisibility(View.VISIBLE);
                    return true;
            }
            return false;
        }
    });
}
private void loadFragment(Fragment fragment) {
    // load fragment
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_container, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(),getApplicationContext());
    adapter.addFragment(new SalesStageFragment(), "Sales Stage");
    adapter.addFragment(new SupportFragment(), "Support Required");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager, Context applicationContext) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new SalesStageFragment();
        } else if (position == 1) {
            return new SupportFragment();
        }
        return new SalesStageFragment();

    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}
</code>```

}

SalesStageFragment.java:

```<code>public class SalesStageFragment extends Fragment {
    private String title;
    private int page;

    public SalesStageFragment(){

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Opportunities List");
        View rootView = inflater.inflate(R.layout.opportunity, container, false);
</code>```

SupportFragment.java:

```<code>public class SupportFragment extends Fragment {
        private String title;
        private int page;

        public SalesStageFragment(){

        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment

            ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Opportunities List");
            View rootView = inflater.inflate(R.layout.support, container, false);
</code>```

答:
This should be your ViewPagerAdapter class

```<code>public class ViewPagerAdapter extends FragmentStatePagerAdapter {

private final Context mContext;

    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.sales_stage, R.string.support_required};

    public ViewPagerAdapter(@NonNull FragmentManager fm, int behavior, Context context) {
        super(fm, behavior);
        this.mContext = context;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new SalesStageFragment();
        } else if (position == 1) {
            return new SupportFragment();
        }
        return new SalesStageFragment();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        return 2;
    }
}
</code>```

Considering you're using BottomNavigation, you'd want to use Fragments. Create HomeFragment as this is where you'll host the TabLayout.

```<code>public class HomeFragment extends Fragment {

    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;

    private Context mContext;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, getActivity());

        mViewPager.setAdapter(adapter);
        mTabLayout.setupWithViewPager(mViewPager);

        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
    }
}
</code>```

Body:
Hi in the below activity I have bottom navigation item named as opportunity .When I am click on the opportunity want to call TabLayout contains two tabs names as sales stage and support required.

From activity not calling my fragments .

Can any one help me

Acivity.java:

public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private Toolbar toolbar;

private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private ProgressDialog progressDialog = null;
String sessionId;
private ViewPager viewPager;
MenuItem refreshMenuItem;
TabLayout tabLayout;
Fragment fragment;
private RecyclerView.LayoutManager layoutManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    sessionId = getIntent().getStringExtra("sessionId");
    toolbar = (Toolbar) findViewById(R.id.toolbar);

    toolbar.setTitle("Home");

    loadFragment(new TaskFragement());
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
    tabLayout.setupWithViewPager(viewPager);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    recyclerView.setHasFixedSize(true);

    // use a linear layout manager
   // layoutManager = new LinearLayoutManager(this);
    //recyclerView.setLayoutManager(layoutManager);

    //recyclerView.setAdapter(mAdapter);
    initNavigationDrawer();
    initBottomNavigationItems();

}

public void initNavigationDrawer() {

    NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            int id = menuItem.getItemId();

            switch (id){
                case R.id.home:
                    Toast.makeText(getApplicationContext(),"Home",Toast.LENGTH_SHORT).show();
                    drawerLayout.closeDrawers();
                    break;
                case R.id.settings:
                    Toast.makeText(getApplicationContext(),"Settings",Toast.LENGTH_SHORT).show();
                    break;
                case R.id.trash:
                    Toast.makeText(getApplicationContext(),"History",Toast.LENGTH_SHORT).show();
                    drawerLayout.closeDrawers();
                    break;
                case R.id.logout:
                    finish();

            }
            return true;
        }
    });
    View header = navigationView.getHeaderView(0);
    TextView tv_email = (TextView)header.findViewById(R.id.tv_email);
    tv_email.setText("GenWorks Solutions");
    drawerLayout = (DrawerLayout)findViewById(R.id.drawer);

    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){

        @Override
        public void onDrawerClosed(View v){
            super.onDrawerClosed(v);
        }

        @Override
        public void onDrawerOpened(View v) {
            super.onDrawerOpened(v);
        }
    };
    drawerLayout.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();
}

public void initBottomNavigationItems() {

    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.task:
                    toolbar.setTitle("Task");
                    fragment = new TaskFragement();
                    loadFragment(fragment);
                    return true;
                case R.id.account:
                    toolbar.setTitle("Account");
                    fragment = new AccountFragement();
                    sessionId = getIntent().getStringExtra("sessionId");
                    loadFragment(fragment);
                    return true;
                case R.id.contact:
                    toolbar.setTitle("Contact");
                    fragment = new ContactFragment();
                    loadFragment(fragment);
                    return true;
                case R.id.opportunity:
                    toolbar.setTitle("Opportunity");
                    tabLayout.setVisibility(View.VISIBLE);
                    viewPager.setVisibility(View.VISIBLE);
                    return true;
            }
            return false;
        }
    });
}
private void loadFragment(Fragment fragment) {
    // load fragment
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_container, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(),getApplicationContext());
    adapter.addFragment(new SalesStageFragment(), "Sales Stage");
    adapter.addFragment(new SupportFragment(), "Support Required");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager, Context applicationContext) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new SalesStageFragment();
        } else if (position == 1) {
            return new SupportFragment();
        }
        return new SalesStageFragment();

    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

}

SalesStageFragment.java:

public class SalesStageFragment extends Fragment {
    private String title;
    private int page;

    public SalesStageFragment(){

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Opportunities List");
        View rootView = inflater.inflate(R.layout.opportunity, container, false);

SupportFragment.java:

public class SupportFragment extends Fragment {
        private String title;
        private int page;

        public SalesStageFragment(){

        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment

            ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Opportunities List");
            View rootView = inflater.inflate(R.layout.support, container, false);

Body:
This should be your ViewPagerAdapter class

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

private final Context mContext;

    @StringRes
    private static final int[] TAB_TITLES = new int[]{R.string.sales_stage, R.string.support_required};

    public ViewPagerAdapter(@NonNull FragmentManager fm, int behavior, Context context) {
        super(fm, behavior);
        this.mContext = context;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        if (position == 0) {
            return new SalesStageFragment();
        } else if (position == 1) {
            return new SupportFragment();
        }
        return new SalesStageFragment();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mContext.getResources().getString(TAB_TITLES[position]);
    }

    @Override
    public int getCount() {
        return 2;
    }
}

Considering you're using BottomNavigation, you'd want to use Fragments. Create HomeFragment as this is where you'll host the TabLayout.

public class HomeFragment extends Fragment {

    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;

    private Context mContext;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, getActivity());

        mViewPager.setAdapter(adapter);
        mTabLayout.setupWithViewPager(mViewPager);

        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mContext = context;
    }
}