问:
How to automate outlook when there is more than one account configured?
In my microsoft outlook...I have more than one account configured.. When I try to automate the customised  mailbox(account). It always points to the default inbox... How to change this to the customised inbox I want?

We tried to use the below code:

But always it points to the mailbox  XXXXX@medtronic.com and Inbox folder (The 2nd mailbox)

But we need to point to the Inbox of the RS mailbox and search for the email through VBscript as highlighted below in yellow colour.

```<code>enter code here

Set objApp = CreateObject("Outlook.Application")`enter code here`
Set objNameSpace = objApp.GetNamespace("MAPI")
Set objSyncs = objNameSpace.SyncObjects
Set myFolder = objNameSpace.GetDefaultFolder(6)
Set ObjMails = myFolder.Items
Set objFilter = ObjMails[![enter image description here][1]][1]
</code>```

答:
What points to the default mailbox? Namespace.GetDefaultFolder? You really need to provide the relevant snippets of your code.

If you want to work with a delegate folder, use either Namespace.GetSharedDefaultFolder, or, if the store is already opened in the active profile, retrieve the Store object from Namespace.Stores collection and use Store.GetDefaultFolder.

Body:
In my microsoft outlook...I have more than one account configured.. When I try to automate the customised  mailbox(account). It always points to the default inbox... How to change this to the customised inbox I want?

We tried to use the below code:

But always it points to the mailbox  XXXXX@medtronic.com and Inbox folder (The 2nd mailbox)

But we need to point to the Inbox of the RS mailbox and search for the email through VBscript as highlighted below in yellow colour.

enter code here

Set objApp = CreateObject("Outlook.Application")`enter code here`
Set objNameSpace = objApp.GetNamespace("MAPI")
Set objSyncs = objNameSpace.SyncObjects
Set myFolder = objNameSpace.GetDefaultFolder(6)
Set ObjMails = myFolder.Items
Set objFilter = ObjMails[![enter image description here][1]][1]


来源: stackexchange

问:
How do I use a row count in an @if in a Laravel view?
I am brand new to Laravel and I'm running Version 6.

I want my view to display a button if one of my MySQL tables has rows that meet a specific condition but I'm having trouble figuring out how to code it - and even WHERE to code it - within my Laravel application.

My MySQL table is called diary_entries and various users of the system will contribute zero to n  rows to it. Each row of the table contains a user id called client. When a given user goes to the Welcome view, I want the view to determine if that user currently has any rows in the diary_entries table. If he does, I want to display a button that will take him to another page where the entries can be displayed or edited or deleted.

I think I want to construct an @if that counts the number of records for that user; if the count is greater than zero, I want to display the button, otherwise the button is not displayed.

The problem is that I can't figure out how to code this. I've looked at the examples in the Eloquent section of the manual but they aren't particularly clear to me. I found a note near the top that said the count() function expects a Collection as an argument and that the result of an Eloquent statement is always a Collection so I guessed that I just have to execute an Eloquent query, then apply count() to the resulting Collection. But every variation of that idea which I've tried has thrown exceptions.

Here was the guess that seemed most logical to me:

```<code>@extends('layout');

@section('content');
<div class="content">
    <img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
    <div class="title m-b-md">
        <h1> Sleep Diary </h1>
    </div>
    <div>
        <h3>{{Auth::user()->name }}</h3>
    </div>
    <div>
        @if (count(App\DiaryEntry::select('*')->where('client', Auth::user()->name) > 0))
            <p>
                <a class="btn btn-primary"> View / edit existing sleep diary entries </a>
            </p>
        @endif
    </div>
    <div>
        <p>
            <a class="btn btn-primary" href="/diaryEntries"> Create a new sleep diary entry </a>
    </div>
</div>
@endsection
</code>```

This is obviously wrong because it throws an exception so how do I make it right? Does the building of the collection have to move into the Controller? If so, how do I invoke the method and see its result? Or can I do something like I have already done but just adjust the syntax a bit?

EDIT

I've imitated Sehdev's suggestion but I get this error:

```<code>$count is undefined

Make the variable optional in the blade template. Replace {{ $count }} with {{ $count ?? '' }}
</code>```

Here is my welcome view:

```<code> @extends('layout');

 @section('content');
   <div class="content">
    <img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
    <div class="title m-b-md">
        <h1>Sleep Diary</h1>
    </div>
    <div>
      <h3>{{ Auth::user()->name }}</h3>
    </div>
    <div>
        @if ($count) > 0))
        <p>
            <a class="btn btn-primary">View/edit existing sleep diary entries</a>
        </p>
        @endif
    </div>
    <div>
        <p><a class="btn btn-primary" href="/diaryEntries">Create a new sleep diary entry</a>
    </div>
    </div>
    @endsection
</code>```

And this is the relevant function from DiaryEntryController:

```<code> public function countEntriesOneUser()
 {
    $count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();
     view("welcome", compact("count"));
    }
</code>```

Should the compact function be returning $count instead of count? I can't find the compact function in the manual with the search function so I'm not clear what it does or what the proper syntax is. I just tried changing the last line of the function to

```<code>view("welcome", $count);
</code>```

but that produced the same error.

答:
Try this,</p>

```<code>@php
$count=\App\DiaryEntry::where('client', Auth::user()->name)->count();
@endphp
@if($count>1)
 <p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
@endif
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am brand new to Laravel and I'm running Version 6.

I want my view to display a button if one of my MySQL tables has rows that meet a specific condition but I'm having trouble figuring out how to code it - and even WHERE to code it - within my Laravel application.

My MySQL table is called diary_entries and various users of the system will contribute zero to n  rows to it. Each row of the table contains a user id called client. When a given user goes to the Welcome view, I want the view to determine if that user currently has any rows in the diary_entries table. If he does, I want to display a button that will take him to another page where the entries can be displayed or edited or deleted.

I think I want to construct an @if that counts the number of records for that user; if the count is greater than zero, I want to display the button, otherwise the button is not displayed.

The problem is that I can't figure out how to code this. I've looked at the examples in the Eloquent section of the manual but they aren't particularly clear to me. I found a note near the top that said the count() function expects a Collection as an argument and that the result of an Eloquent statement is always a Collection so I guessed that I just have to execute an Eloquent query, then apply count() to the resulting Collection. But every variation of that idea which I've tried has thrown exceptions.

Here was the guess that seemed most logical to me:

@extends('layout');

@section('content');

 Sleep Diary

{{Auth::user()->name }}

        @if (count(App\DiaryEntry::select('*')->where('client', Auth::user()->name) > 0))

                 View / edit existing sleep diary entries

        @endif

             Create a new sleep diary entry

@endsection

This is obviously wrong because it throws an exception so how do I make it right? Does the building of the collection have to move into the Controller? If so, how do I invoke the method and see its result? Or can I do something like I have already done but just adjust the syntax a bit?

EDIT

I've imitated Sehdev's suggestion but I get this error:

$count is undefined

Make the variable optional in the blade template. Replace {{ $count }} with {{ $count ?? '' }}

Here is my welcome view:

 @extends('layout');

 @section('content');

Sleep Diary

{{ Auth::user()->name }}

        @if ($count) > 0))

            View/edit existing sleep diary entries

        @endif

Create a new sleep diary entry

    @endsection

And this is the relevant function from DiaryEntryController:

 public function countEntriesOneUser()
 {
    $count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();
     view("welcome", compact("count"));
    }

Should the compact function be returning $count instead of count? I can't find the compact function in the manual with the search function so I'm not clear what it does or what the proper syntax is. I just tried changing the last line of the function to

view("welcome", $count);

but that produced the same error.

Body:
Try this,

@php
$count=\App\DiaryEntry::where('client', Auth::user()->name)->count();
@endphp
@if($count>1)
 <p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
@endif


问:
How to split a dataframe into two based on data from another dataframe (before and after some action) in pandas?
I need to split a dataframe with posts using data of date and time of registration into two dataframes, where I will have data of posts before and after registration.

A dataframe with posts:

```<code>posts = {'Login':['User1', 'User1', 'User2', 'User3', 'User3'], 'Posted':['13.12.2018 07:12', '13.05.2019 00:00', '13.05.2019 12:32', '13.06.2019 00:06', '01.07.2019 14:43']}
df_posts = pd.DataFrame(posts)
</code>```

A dataframe with dates of registration:

```<code>registr_date = {'Login':['User1', 'User2', 'User3'], 'Registered':['14.12.2018 12:07', '17.05.2019 14:01', '20.06.2019 15:00']}
df_registr = pd.DataFrame(registr_date)
</code>```

I changed the format of columns with time and date:

```<code>df_posts['Posted']= pd.to_datetime(df_posts['Posted'])
df_registr['Date_of_registration']= pd.to_datetime(df_registr['Date_of_registration'])
</code>```

I need to get the following output.
Posts before registration:

```<code>    Login   Posted_before
0   User1   13.12.2018 07:12
1   User2   13.05.2019 12:32
2   User3   13.06.2019 00:06
</code>```

Posts after registration:

```<code>    Login   Posted_after
0   User1   13.05.2019 00:00
1   User3   01.07.2019 14:43
</code>```

How I should split the dataframe with posts?

答:
Use pd.merge:

Please beware that using .to_datetime with out format argument can cause confusion on date and month.

```<code>df_posts['Posted']= pd.to_datetime(df_posts['Posted'], format = '%d.%m.%Y %H:%M')
df_registr['Date_of_registration']= pd.to_datetime(df_registr['Registered'], format = '%d.%m.%Y %H:%M')

df_merge = pd.merge(df_posts,df_registr, on = 'Login')
df_before = df_merge[['Login','Posted']][df_merge['Date_of_registration'] > df_merge['Posted']]
df_after = df_merge[['Login','Posted']][df_merge['Date_of_registration'] < df_merge['Posted']]
</code>```

Body:
I need to split a dataframe with posts using data of date and time of registration into two dataframes, where I will have data of posts before and after registration.

A dataframe with posts:

posts = {'Login':['User1', 'User1', 'User2', 'User3', 'User3'], 'Posted':['13.12.2018 07:12', '13.05.2019 00:00', '13.05.2019 12:32', '13.06.2019 00:06', '01.07.2019 14:43']}
df_posts = pd.DataFrame(posts)

A dataframe with dates of registration:

registr_date = {'Login':['User1', 'User2', 'User3'], 'Registered':['14.12.2018 12:07', '17.05.2019 14:01', '20.06.2019 15:00']}
df_registr = pd.DataFrame(registr_date)

I changed the format of columns with time and date:

df_posts['Posted']= pd.to_datetime(df_posts['Posted'])
df_registr['Date_of_registration']= pd.to_datetime(df_registr['Date_of_registration'])

I need to get the following output.
Posts before registration:

    Login   Posted_before
0   User1   13.12.2018 07:12
1   User2   13.05.2019 12:32
2   User3   13.06.2019 00:06

Posts after registration:

    Login   Posted_after
0   User1   13.05.2019 00:00
1   User3   01.07.2019 14:43

How I should split the dataframe with posts?

Body:
Use pd.merge:

Please beware that using .to_datetime with out format argument can cause confusion on date and month.

df_posts['Posted']= pd.to_datetime(df_posts['Posted'], format = '%d.%m.%Y %H:%M')
df_registr['Date_of_registration']= pd.to_datetime(df_registr['Registered'], format = '%d.%m.%Y %H:%M')

df_merge = pd.merge(df_posts,df_registr, on = 'Login')
df_before = df_merge[['Login','Posted']][df_merge['Date_of_registration'] > df_merge['Posted']]
df_after = df_merge[['Login','Posted']][df_merge['Date_of_registration'] < df_merge['Posted']]


问:
How can I split a string and get just key part with regexp?
I have a string like <code>"A < -5.9 AND B >= 6 OR (C < 3)"</code> I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=  </p>

答:
We can try doing a regex search for all matches on the pattern:

```<code>\b([A-Z]+) \S+ -?\d+(?:\.\d+)?\b
</code>```

Sample script:

var regex = /\b([A-Z]+) \S+ -?\d+(?:\.\d+)?\b/g;
var input = "A < -5.9 AND B >= 6 OR (C < 3)";
var m;

do {
    m = regex.exec(input);
    if (m) {
        console.log(m[1]);
    }
} while (m);```
</div>
</div>
</p>

<p>Here is an explanation of the regex pattern being used:</p>

```\b([A-Z]+)    match and capture a key as one or more capital letters
 \S+          match space followed by a symbol and another space
-?\d+         match a number with optional negative sign
(?:\.\d+)?\b  match an optional decimal component
```

Body:
I have a string like "A < -5.9 AND B >= 6 OR (C < 3)" I have to get keys part.(A,B,C). So I thought I should split first AND and OR then I should get key part? Could you help me? I wrote just A,B,C but in my real example A can be any string. The important thing is that is value on the right side of
<,>,<=,>=

Body:
We can try doing a regex search for all matches on the pattern:

\b([A-Z]+) \S+ -?\d+(?:\.\d+)?\b

Sample script:

var regex = /\b([A-Z]+) \S+ -?\d+(?:\.\d+)?\b/g;
var input = "A < -5.9 AND B >= 6 OR (C < 3)";
var m;

do {
    m = regex.exec(input);
    if (m) {
        console.log(m[1]);
    }
} while (m);

Here is an explanation of the regex pattern being used:

\b([A-Z]+)    match and capture a key as one or more capital letters
 \S+          match space followed by a symbol and another space
-?\d+         match a number with optional negative sign
(?:\.\d+)?\b  match an optional decimal component


问:
Error while using h2o.init() in R - Java related
I am getting this error while initializing h2o

h2o.init()
H2O is not running yet, starting it now...

```<code>Error in .h2o.startJar(ip = ip, port = port, name = name, nthreads = nthreads,  :
  Your java is not supported: java version "1.7.0_80"
Please download the latest Java SE JDK from the following URL:
https://www.oracle.com/technetwork/java/javase/downloads/index.html
</code>```

I have tried installing latest version of Java, but still the problem persists. Kindly help.

答:
From error it clearly saying "Your java is not supported: java version "1.7.0_80""

Install new version of java from oracle site ex: java 8

then set that jre path from PATH and CLASSPATH

Windows 7:

   1. From the desktop, right click the Computer icon.

   2. Choose Properties from the context menu.

   3. Click the Advanced system settings link.

   4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.

   5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.

Body:
I am getting this error while initializing h2o

h2o.init()
H2O is not running yet, starting it now...

Error in .h2o.startJar(ip = ip, port = port, name = name, nthreads = nthreads,  :
  Your java is not supported: java version "1.7.0_80"
Please download the latest Java SE JDK from the following URL:
https://www.oracle.com/technetwork/java/javase/downloads/index.html

I have tried installing latest version of Java, but still the problem persists. Kindly help.


问:
Is there a free GUI tool for data sync between DB in which it is possible to script rules?
What I need to do is some data between 2 databases. The source can be anything (comma separated file, xls file, any database, ...), the destination is MS SQL Server.

I do not need to sync all data, I just need to sync particular tables.

Example:

I need to sync accounting Software (runs on PostgreSQL) CUSTOMERS table with CRM (runs on SQL Server).

Some problems this tool should be able to face:

1) Accounting software customers table has 1 field that is not mapped in crm customers table. (In this way I want to map this extra field to the field CUSTOMERS_CUSTOM_DATA.EXTRA_FIELD)

2) Having some rules (like sync only customers whose code is between 10000 and 99999)

3) Allowing to perform some post insert tasks (for example I am using manually managed seuqences for the tanble IDs, so after inserting 10 records I need to add 10 to the sequence)

4) Having an exception handling mechanism so if something is wrong it can wither call a sql server stored procedure (that I already have and it will send an e-mail to me) or simply send a message to notify that something was wrong in the nightly sync.

5) Be easy to schedule when to perform data sync (hourly, daily, INCLUDING MANUAL)

6) Perform data conversion: if Surname field in source table is varchar(20) and in destination table is varchar(15)  I want to explicitly say "perform a truncation".

7) Have different rules for insert or update. For example in the source e-mail field is not present, but I want to populate it in the destination I decide to perform this operation on insert only, not on update. (for example as I insert a new customer I want to populate the e-mail field concatenating name and surname, but then I want to let the users to modify it, this first insertion is just to simplify data entry, but then this particular case will be handled manually. So I want to say (on insert populate e-mail field, on update don't do anything with email field)

8) In case of delete in the source db don't delete on the destination but only change the varchar(10) STATUS to DELETED.

Note: I know that Integration Services will be perfect for this, but I must support the Express Edition, so SSIS is not an option.

I created a bunch of scripts and scheduled stored procedure that at present do what I need, but it is very hard to maintain and the total lack of a GUI makes the work much slower. I remember having seeing TALEND time ago, maybe that tool is also the answr I need, anyway I need to provide a quick answer to management, so I have now no time to investigate all the tools on the market, and I would prefer to have a suggestion from an expert.

答: Finally I went for TALEND, I never really used SSIS, I just saw a live demo of it at a SQL Server conference. Anyway Talend is a free alternative (and quite rich) to SSIS, so it will suite the needs of all customers, including the ones (95%) that has SQL Server Express.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Is there a way to make a field in Dynamics CRM as one time entry field?
Basically, what I want is that the user should be able to select the dropdown and not be able to change it after making and saving the selection. So it will be a one-time entry field.

Below is a screenshot of the field I want to apply this property.

So this field has a Yes or No selection. And to make the business logic from failing I have to make it a one-time entry field only.

I looked up the form editor for possible things but couldn't find anything that would let me achieve this.

UPDATE #1

Below is my onload function:

```<code>function Form_onload() {
    var formType = Xrm.Page.ui.getFormType();
    var p = Xrm.Page.getAttribute("opportunityid");
--------------NEW CODE--------------------------------

    if(formType ==2){ //form type 2 means the form is a saved form. form type 1 is new form.

    alert(formType);
    var myattribute = Xrm.Page.getAttribute("var_internal");
    var myname = myattribute.getName();
    if (Xrm.Page.getControl(myname) != null) {
        //alert(myname);
        Xrm.Page.getControl(myname).setDisabled(true);
    }
    }
--------------NEW CODE---------------------------
    if (formType == 1 && p != null && p.getValue() != null) {
        alert('Child Opportunities can only be created by clicking the Create Child Opportunity button in the Opportunity ribbon.');
        window.top.close();
    }

}
</code>```

答:
Due to environment-specific settings in my DEV, I was not able to reproduce what was suggested by @Eccountable.  Although, his solution worked in other environments.

@AnkUser has a good answer as well but I was looking to shorten the code and make things as simple as possible.

My solution

I was able to handle this using Javascript on client-side. using the XRM toolbox.

In the XRM toolbox, I located the javascript for the opportunity and observed field changes in formType when the Opportunity was New and when the Opportunity was Existing. This variable (formType) was =1 when the Opportunity was New and =2 when it was Existing/Saved.

Using this piece of information I was able to leverage my Javascript as follows in Form_onload()

```<code>function Form_onload() {
    if (formType == 2) {
        var myattribute = Xrm.Page.getAttribute("internal");
        var myname = myattribute.getName();
        if (Xrm.Page.getControl(myname) != null) {
            Xrm.Page.getControl(myname).setDisabled(true);
        }
    }
}
</code>```

Body:
Basically, what I want is that the user should be able to select the dropdown and not be able to change it after making and saving the selection. So it will be a one-time entry field.

Below is a screenshot of the field I want to apply this property.

So this field has a Yes or No selection. And to make the business logic from failing I have to make it a one-time entry field only.

I looked up the form editor for possible things but couldn't find anything that would let me achieve this.

UPDATE #1

Below is my onload function:

function Form_onload() {
    var formType = Xrm.Page.ui.getFormType();
    var p = Xrm.Page.getAttribute("opportunityid");
--------------NEW CODE--------------------------------

    if(formType ==2){ //form type 2 means the form is a saved form. form type 1 is new form.

    alert(formType);
    var myattribute = Xrm.Page.getAttribute("var_internal");
    var myname = myattribute.getName();
    if (Xrm.Page.getControl(myname) != null) {
        //alert(myname);
        Xrm.Page.getControl(myname).setDisabled(true);
    }
    }
--------------NEW CODE---------------------------
    if (formType == 1 && p != null && p.getValue() != null) {
        alert('Child Opportunities can only be created by clicking the Create Child Opportunity button in the Opportunity ribbon.');
        window.top.close();
    }

}

Body:
Due to environment-specific settings in my DEV, I was not able to reproduce what was suggested by @Eccountable.  Although, his solution worked in other environments.

@AnkUser has a good answer as well but I was looking to shorten the code and make things as simple as possible.

My solution

I was able to handle this using Javascript on client-side. using the XRM toolbox.

In the XRM toolbox, I located the javascript for the opportunity and observed field changes in formType when the Opportunity was New and when the Opportunity was Existing. This variable (formType) was =1 when the Opportunity was New and =2 when it was Existing/Saved.

Using this piece of information I was able to leverage my Javascript as follows in Form_onload()

function Form_onload() {
    if (formType == 2) {
        var myattribute = Xrm.Page.getAttribute("internal");
        var myname = myattribute.getName();
        if (Xrm.Page.getControl(myname) != null) {
            Xrm.Page.getControl(myname).setDisabled(true);
        }
    }
}


问:
Using docker-compose to set containers timezones
I have a docker-compose file running a few Dockerfiles to create my containers. I don't want to edit my Dockerfiles to set timezones because they could change at any time by members of my team and I have a docker-compose.override.yml file to make local environment changes. However, one of my containers (a Selenium based one) seems to not pull host time zone and that causes problems for me. Based on that I want to enforce timezones on all my containers. In my Dockerfiles right now I do

```<code>ENV TZ=America/Denver
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
</code>```

And everything works fine. How do I replicate the same command in docker-compose syntax?

答:
```<code>version: '3.6'
services:
  mysql:
    image: mysql:5.6
    restart: always
    container_name: dev-mysql
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    restart: always
    environment:
     - TZ=Asia/Shanghai
     - MYSQL_ROOT_PASSWORD=password # set the root password
    ports:
      - '3306:3306'
    volumes:
      - "/etc/localtime:/etc/localtime:ro"
      - "/etc/timezone:/etc/timezone:ro"

</code>```

This my docker-compose.yaml of mysql

Reminder,you need recreate container,other than restart.
if you change the yaml need to recreate

docker-compose -f docker-compose.yaml stop
docker-compose -f docker-compose.yaml rm
docker-compose -f docker-compose.yaml start
```

Body:
I have a docker-compose file running a few Dockerfiles to create my containers. I don't want to edit my Dockerfiles to set timezones because they could change at any time by members of my team and I have a docker-compose.override.yml file to make local environment changes. However, one of my containers (a Selenium based one) seems to not pull host time zone and that causes problems for me. Based on that I want to enforce timezones on all my containers. In my Dockerfiles right now I do

ENV TZ=America/Denver
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

And everything works fine. How do I replicate the same command in docker-compose syntax?

Body:
version: '3.6'
services:
  mysql:
    image: mysql:5.6
    restart: always
    container_name: dev-mysql
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    restart: always
    environment:
     - TZ=Asia/Shanghai
     - MYSQL_ROOT_PASSWORD=password # set the root password
    ports:
      - '3306:3306'
    volumes:
      - "/etc/localtime:/etc/localtime:ro"
      - "/etc/timezone:/etc/timezone:ro"

This my docker-compose.yaml of mysql

Reminder,you need recreate container,other than restart.
if you change the yaml need to recreate

docker-compose -f docker-compose.yaml stop
docker-compose -f docker-compose.yaml rm
docker-compose -f docker-compose.yaml start


问:
Numerical evaluation of the exponential integral function using trapezoidal rule
I want to evaluate the exponential integral function numerically using trapezoidal rule.This function is defined as:

The reference is available here.
This function is already available in some libraries for example scipy.special. For some reasons I do not want to use these libraries. Instead, I need to evaluate this function directly by the trapezoidal rule. I wrote the trapezoidal rule and checked it to make sure it works fine.
Then I used it for numerical evaluation of the Ei function. Unfortunately the results  is not correct for example I want to evaluate Ei(1) which is equal to 1.89511 but the code I have written returns infinity which is wrong. Here is the code:

```<code>import numpy as np

# Integration using Trapezoidal rule
def trapezoidal(f, a, b, n):

    h = float(b - a) / n
    s = 0.0
    s += f(a)/2.0
    for i in range(1, n):
        s += f(a + i*h)
    s += f(b)/2.0
    return s * h

# Define integrand
def Ei(t):

    return - np.exp(-t) / t

# Define Ei(1)
A = trapezoidal(Ei, -1, np.inf, 20)

print (A)

# Checking Ei(1)
from scipy.special import expi
print (expi(1))
</code>```

Do you know how I can modify the above code so I can get correct results?
Thanks!

答:
1) You cannot define range ending woth +inf and divide it onto 20 parts.

Instead you can choose arbitrary right limit and increase it until difference abs(integral(limit(i+1))-integral(limit(i))) becomes negligible

2) Consider function evaluation in zero point (if occurs). It causes division by zero

If argument is too close to zero, try to shift it a bit.

Body:
I want to evaluate the exponential integral function numerically using trapezoidal rule.This function is defined as:

The reference is available here.
This function is already available in some libraries for example scipy.special. For some reasons I do not want to use these libraries. Instead, I need to evaluate this function directly by the trapezoidal rule. I wrote the trapezoidal rule and checked it to make sure it works fine.
Then I used it for numerical evaluation of the Ei function. Unfortunately the results  is not correct for example I want to evaluate Ei(1) which is equal to 1.89511 but the code I have written returns infinity which is wrong. Here is the code:

import numpy as np

# Integration using Trapezoidal rule
def trapezoidal(f, a, b, n):

    h = float(b - a) / n
    s = 0.0
    s += f(a)/2.0
    for i in range(1, n):
        s += f(a + i*h)
    s += f(b)/2.0
    return s * h

# Define integrand
def Ei(t):

    return - np.exp(-t) / t

# Define Ei(1)
A = trapezoidal(Ei, -1, np.inf, 20)

print (A)

# Checking Ei(1)
from scipy.special import expi
print (expi(1))

Do you know how I can modify the above code so I can get correct results?
Thanks!


问:
In new version azure eventhub, how to close consumer_client after timeout
I am receiving data through azure eventhub and trying to close if I am receiving no more data for like 10 or 15 seconds.

I tried to implement arguments auth_timeout and idel_timeout in _consumer_client, but neither worked.

I am also referring to this example.

There's "on_error" function that may function to close the client when there's no further message being consumed.

```<code>def on_event(partition_context, event):

    ## My Code##

    # Put your code here. to do some operations on the event.

    print("Received event from partition {}.".format(partition_context.partition_id))
    print("Last enqueued event properties from partition: {} is: {}.".format(
        partition_context.partition_id,t))
</code>```

```<code>def on_error(partition_context, error):
    # Put your code here. partition_context can be None in the on_error callback.
    if partition_context:
        print("An exception: {} occurred during receiving from Partition: {}.".format(
            partition_context.partition_id,
            error
        ))
    else:
        print("An exception: {} occurred during the load balance process.".format(error))
</code>```

```<code>consumer_client = EventHubConsumerClient.from_connection_string(conn_str=CONNECTION_STR,consumer_group='forceconsummer',eventhub_name=EVENTHUB_NAME, idle_timeout = 30, auth_timeout = 10)
consumer_client.receive(on_event=on_event, partition_id = "2", track_last_enqueued_event_properties=False, on_error=on_error, starting_position="@latest")

</code>```

How can I make it work to be closed automatically after a timeout?

答:
wont let me comment, but I had the same issue. The builin azure idle timeout seems to do nothing.

Serkant's example worked for me. Just replace (RECEIVE_DURATION) with an int... i.e 15 seconds. oh and import threading

Body:
I am receiving data through azure eventhub and trying to close if I am receiving no more data for like 10 or 15 seconds.

I tried to implement arguments auth_timeout and idel_timeout in _consumer_client, but neither worked.

I am also referring to this example.

There's "on_error" function that may function to close the client when there's no further message being consumed.

def on_event(partition_context, event):

    ## My Code##

    # Put your code here. to do some operations on the event.

    print("Received event from partition {}.".format(partition_context.partition_id))
    print("Last enqueued event properties from partition: {} is: {}.".format(
        partition_context.partition_id,t))

def on_error(partition_context, error):
    # Put your code here. partition_context can be None in the on_error callback.
    if partition_context:
        print("An exception: {} occurred during receiving from Partition: {}.".format(
            partition_context.partition_id,
            error
        ))
    else:
        print("An exception: {} occurred during the load balance process.".format(error))

consumer_client = EventHubConsumerClient.from_connection_string(conn_str=CONNECTION_STR,consumer_group='forceconsummer',eventhub_name=EVENTHUB_NAME, idle_timeout = 30, auth_timeout = 10)
consumer_client.receive(on_event=on_event, partition_id = "2", track_last_enqueued_event_properties=False, on_error=on_error, starting_position="@latest")

How can I make it work to be closed automatically after a timeout?


问:
how to rewrite this Scala withColumn when condition
I have some Scala code that works when I run manually in Spark EMR, but I get errors when I try to compile in Eclipse.

```<code>val tmp_df2 = tmp_df1.withColumn("col_one", when($"col_two" === "good", "bad").otherwise($"col_one"))
</code>```

When I run "Maven install" it says "error: not found: value when". But I know the code works in EMR.

So, is there another to specify that condition without using "when"?

答:
You may need to import the spark function as follows:

```<code>import org.apache.spark.sql.functions.when
</code>```

or

```<code>import org.apache.spark.sql.functions._
</code>```

Body:
I have some Scala code that works when I run manually in Spark EMR, but I get errors when I try to compile in Eclipse.

val tmp_df2 = tmp_df1.withColumn("col_one", when($"col_two" === "good", "bad").otherwise($"col_one"))

When I run "Maven install" it says "error: not found: value when". But I know the code works in EMR.

So, is there another to specify that condition without using "when"?

Body:
You may need to import the spark function as follows:

import org.apache.spark.sql.functions.when

or

import org.apache.spark.sql.functions._


问:
In project 'app' a resolved Google Play services library dependency depends on another at an exact version
Trying to create a simple app with FireStore and Google Authentication. Having problem with the gradle:

In project 'app' a resolved Google Play services library dependency
  depends on another at an exact version (e.g. "[15.0. 1]", but isn't
  being resolved to that version. Behavior exhibited by the library will
  be unknown.

Dependency failing: com.google.android.gms:play-services-flags:15.0.1
  -> com.google.android.gms:play-services-basement@[
  15.0.1], but play-services-basement version was 16.0.1.

The following dependencies are project dependencies that are direct or
  have transitive dependencies that lead to the art ifact with the
  issue.
  -- Project 'app' depends onto com.google.firebase:firebase-firestore@17.1.5
  -- Project 'app' depends onto com.firebaseui:firebase-ui-auth@4.2.0

For extended debugging info execute Gradle from the command line with
  ./gradlew --info :app:assembleDebug to see the dep endency paths to
  the artifact. This error message came from the google-services Gradle
  plugin, report issues at https://
  github.com/google/play-services-plugins and disable by adding
  "googleServices { disableVersionCheck = false }" to your b uild.gradle
  file.

```<code>    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 27
        defaultConfig {
            applicationId "myapp.com"
            minSdkVersion 19
            targetSdkVersion 27
            versionCode 11
            versionName "1.1"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            multiDexEnabled true
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:27.1.1'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        implementation 'com.google.firebase:firebase-firestore:17.1.5'

        implementation 'com.firebaseui:firebase-ui-auth:4.2.0'

    }

    apply plugin: 'com.google.gms.google-services'
    com.google.gms.googleservices.GoogleServicesPlugin
</code>```

Project gradle:

```<code>buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'

        classpath 'com.google.gms:google-services:4.2.0'

    }
}
</code>```

Can somebody help me?

答:
Your app/build.gradle might have these lemon color blocked on dependencies part in Android Studio like on the picture below,

These (lemon color blocks) mean it's not latest version of dependency. just put mouse on each block, then IDE (Android Studio) tells the numbers that have to be changed.

Body:
Trying to create a simple app with FireStore and Google Authentication. Having problem with the gradle:

In project 'app' a resolved Google Play services library dependency
  depends on another at an exact version (e.g. "[15.0. 1]", but isn't
  being resolved to that version. Behavior exhibited by the library will
  be unknown.

Dependency failing: com.google.android.gms:play-services-flags:15.0.1
  -> com.google.android.gms:play-services-basement@[
  15.0.1], but play-services-basement version was 16.0.1.

The following dependencies are project dependencies that are direct or
  have transitive dependencies that lead to the art ifact with the
  issue.
  -- Project 'app' depends onto com.google.firebase:firebase-firestore@17.1.5
  -- Project 'app' depends onto com.firebaseui:firebase-ui-auth@4.2.0

For extended debugging info execute Gradle from the command line with
  ./gradlew --info :app:assembleDebug to see the dep endency paths to
  the artifact. This error message came from the google-services Gradle
  plugin, report issues at https://
  github.com/google/play-services-plugins and disable by adding
  "googleServices { disableVersionCheck = false }" to your b uild.gradle
  file.

    apply plugin: 'com.android.application'

    android {
        compileSdkVersion 27
        defaultConfig {
            applicationId "myapp.com"
            minSdkVersion 19
            targetSdkVersion 27
            versionCode 11
            versionName "1.1"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            multiDexEnabled true
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation 'com.android.support:appcompat-v7:27.1.1'
        implementation 'com.android.support.constraint:constraint-layout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'com.android.support.test:runner:1.0.2'
        androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
        implementation 'com.google.firebase:firebase-firestore:17.1.5'

        implementation 'com.firebaseui:firebase-ui-auth:4.2.0'

    }

    apply plugin: 'com.google.gms.google-services'
    com.google.gms.googleservices.GoogleServicesPlugin

Project gradle:

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'

        classpath 'com.google.gms:google-services:4.2.0'

    }
}

Can somebody help me?


问:
Nesting  list items within list items of an Ordered List ?
I am attempting to figure out how to create an incremented ordered list currently aimed towards IE6 and IE7.

E.G. It should render something like below:

```<code>1.0
    1.1
    1.2
    1.3
2.0
    2.1
    2.2
</code>```

From what I understand, this is possible to create in CSS with something like this:

```<code>UL, OL { counter-reset: item; }
LI { display: block }
LI:before { content: counters(item, "."); counter-increment: item }
</code>```

However, of course, IE6 and IE7 don't support this.

What options are available to create a proper incremented list in IE6/7? Am I stuck having to hard code this.? Unfortunately, using JavaScript is not an option.

Are there any updated methodologies for newer browsers?

答: XSLT (including XSLT 1.0) can generate multi-level numbering sequences with <xsl:number>.

OwnerDisplayName: Martin M

Body:
I am attempting to figure out how to create an incremented ordered list currently aimed towards IE6 and IE7.

E.G. It should render something like below:

1.0
    1.1
    1.2
    1.3
2.0
    2.1
    2.2

From what I understand, this is possible to create in CSS with something like this:

UL, OL { counter-reset: item; }
LI { display: block }
LI:before { content: counters(item, "."); counter-increment: item }

However, of course, IE6 and IE7 don't support this.

What options are available to create a proper incremented list in IE6/7? Am I stuck having to hard code this.? Unfortunately, using JavaScript is not an option.

Are there any updated methodologies for newer browsers?

LastEditorDisplayName: Andrew Hare

OwnerDisplayName: Richard


问:
inserting the records in the c# form
I am working with C#.

I want to insert record in the table. I m using the MS Access database. I have the following code:

```<code>private void button1_Click(object sender, EventArgs e)
{
    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\\Documents and Settings\\mayur patil\\
                       My Documents\\Dairy_db\\tblCompany.mdb";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES("+textBox1.Text+","+textBox4.Text+")", con);
    cmd.ExecuteNonQuery();
    con.Close();

    this.Hide();
    Form1 f = new Form1();
    f.ShowDialog();
}
</code>```

I am not getting the answer..

答:
If the column CoName_mar is of string type you would need to change the INSERT statement as follows:

```<code>INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES(" + textBox1.Text + ", '" + textBox4.Text + "')"
</code>```

Just notice the singe quote character before and after the textBox4 value.

I am presuming CoCode is of numeric type.

Hope that helps.

Title: inserting the records in the c# form

Body:
I am working with C#.

I want to insert record in the table. I m using the MS Access database. I have the following code:

private void button1_Click(object sender, EventArgs e)
{
    con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;
        Data Source=C:\\Documents and Settings\\mayur patil\\
                       My Documents\\Dairy_db\\tblCompany.mdb";
    con.Open();
    OleDbCommand cmd = new OleDbCommand(
       "INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES("+textBox1.Text+","+textBox4.Text+")", con);
    cmd.ExecuteNonQuery();
    con.Close();

    this.Hide();
    Form1 f = new Form1();
    f.ShowDialog();
}

I am not getting the answer..

Body:
If the column CoName_mar is of string type you would need to change the INSERT statement as follows:

INSERT INTO tblCompany (CoCode,CoName_mar)
       VALUES(" + textBox1.Text + ", '" + textBox4.Text + "')"

Just notice the singe quote character before and after the textBox4 value.

I am presuming CoCode is of numeric type.

Hope that helps.


问:
Flutter Outline Shows "Nothing to show" in android studio
I am trying to extract a Widget via Flutter Outline, but I am facing below problem in Android Studio.

Flutter Outline Shows  "Nothing to show"

After running

```<code>flutter doctor -v
</code>```

It shows:

How to overcome this problem?

答:
Move the mouse to any widget and Press Ctrl (or ⌘ command on macOS)  and click on that widget.

After this step, your Flutter Outline will be enabled and showing widget tree

Body:
I am trying to extract a Widget via Flutter Outline, but I am facing below problem in Android Studio.

Flutter Outline Shows  "Nothing to show"

After running

flutter doctor -v

It shows:

How to overcome this problem?


问:
Obtaining XPATH for Selenium
In a previous question
a user provides the following solution to the problem.

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='title
login_title' and text()='Login']//following::div[1]//input[@class='text header_login_text_box
ignore_interaction']"))).send_keys("someemail@email.com")

</code>```

However, when I go into my chrome inspect element, I get the following XPATH by going copy>XPATH, which when added like the following, no longer works. It also doesn't give an error, just no email is typed into the box.

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='__w2_wHsckeIm21_email']"))).send_keys("someemail@email.com")
</code>```

What's the difference between the two? Why does only the first one work and how do I obtain this long working version of xpath.

答:
Well, not a concrete solution as such but do try out ChroPath Plugin.
Also available on Chrome Web Store.
https://autonomiq.io/chropath/</p>

Title: Obtaining XPATH for Selenium

Body:
In a previous question
a user provides the following solution to the problem.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='title
login_title' and text()='Login']//following::div[1]//input[@class='text header_login_text_box
ignore_interaction']"))).send_keys("someemail@email.com")

However, when I go into my chrome inspect element, I get the following XPATH by going copy>XPATH, which when added like the following, no longer works. It also doesn't give an error, just no email is typed into the box.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='__w2_wHsckeIm21_email']"))).send_keys("someemail@email.com")

What's the difference between the two? Why does only the first one work and how do I obtain this long working version of xpath.


问:
Laravel validation rule fails when trying to update the same record with no changes
I've got a table called Sides which consists of id, name, side_category_id and some other fields not important at the moment.

I wanted to validate that when creating a new side record, the record doesn't exist already. So, let's say I've got in the database a record such as:

```<code>id: 1
name: Salad
side_category_id: 3
</code>```

If I try to insert a new record with name = 'salad' and side_category_id = 3 then the creation must fail and return an error.

I've achieved this by using the following rule:

```<code>$rules = [
   'name'             => 'required',
   'side_category_id' => 'required|exists:side_categories,id|unique:sides,side_category_id,NULL,id,name,' . $this->request->get('name')
]
</code>```

So far so good. It works as it's supposed to. But now it's returning an error if I want to edit a record and save it without any modifications and this is not my desired outcome.

If I try to update the record with no modifications it should succeed. How can I update my rule to achieve this?

答:
you can use Rule::unique()

for create use like this

```<code>$rules = [
   'name'             => ['required'],
   'side_category_id' => ['required',Rule::unique('sides', 'name')->where(function ($query) use($category_id) {
    return $query->where('side_category_id', $category_id);
}),Rule::exists('side_categories')]
]
</code>```

for update

```<code>$rules = [
       'name'             => ['required'],
       'side_category_id' => ['required',Rule::unique('sides', 'name')->where(function ($query) use($category_id) {
        return $query->where('side_category_id', $category_id);
    })->ignore($id),Rule::exists('side_categories')]
    ]
//$id should be you parameter
</code>```

Body:
I've got a table called Sides which consists of id, name, side_category_id and some other fields not important at the moment.

I wanted to validate that when creating a new side record, the record doesn't exist already. So, let's say I've got in the database a record such as:

id: 1
name: Salad
side_category_id: 3

If I try to insert a new record with name = 'salad' and side_category_id = 3 then the creation must fail and return an error.

I've achieved this by using the following rule:

$rules = [
   'name'             => 'required',
   'side_category_id' => 'required|exists:side_categories,id|unique:sides,side_category_id,NULL,id,name,' . $this->request->get('name')
]

So far so good. It works as it's supposed to. But now it's returning an error if I want to edit a record and save it without any modifications and this is not my desired outcome.

If I try to update the record with no modifications it should succeed. How can I update my rule to achieve this?

Body:
you can use Rule::unique()

for create use like this

$rules = [
   'name'             => ['required'],
   'side_category_id' => ['required',Rule::unique('sides', 'name')->where(function ($query) use($category_id) {
    return $query->where('side_category_id', $category_id);
}),Rule::exists('side_categories')]
]

for update

$rules = [
       'name'             => ['required'],
       'side_category_id' => ['required',Rule::unique('sides', 'name')->where(function ($query) use($category_id) {
        return $query->where('side_category_id', $category_id);
    })->ignore($id),Rule::exists('side_categories')]
    ]
//$id should be you parameter


问:
Why does it return 1?
Goal of program: return 1 if two arrays are identical. if not return 0.
What I did:

```<code>#include <stdio.h>

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            return 1;
        }
    }

}

int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}
</code>```

It always returns 1 and I cannot find the reason why.
What's wrong?

答:
You have just messed up the if-else statements, as in the first iteration you are checking and also terminating the loop by using the return statement, so it never goes on the next index.

Just replace the else return statement with continue and at the end of the function add a return statement as, return 1

```<code>    int identical ( int arr1[], int arr2[], unsigned int len ){
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            continue;
        }
    }

    return 1;

}

</code>```

OR

You need to rewrite function declaration as follows (in efficent way):

```<code>int identical ( int arr1[], int arr2[], unsigned int len ){

   if (len == 0)    return 1;

    for (int i = 0; i < len; i++)
        if (arr1[i] != arr2[i])     return 0;

   return 1;
}
</code>```

Thanks.

Title: Why does it return 1?

Body:
Goal of program: return 1 if two arrays are identical. if not return 0.
What I did:

#include <stdio.h>

int identical ( int arr1[], int arr2[], unsigned int len )
{
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            return 1;
        }
    }

}

int main ()
{
    int arr1[3] = {10,15,20};
    int arr2[3] = {10,15,21};
    printf("%d\n", identical(arr1, arr2, 3));

    return 0;
}

It always returns 1 and I cannot find the reason why.
What's wrong?

Body:
You have just messed up the if-else statements, as in the first iteration you are checking and also terminating the loop by using the return statement, so it never goes on the next index.

Just replace the else return statement with continue and at the end of the function add a return statement as, return 1

    int identical ( int arr1[], int arr2[], unsigned int len ){
    for (int i = 0; i < len; i++){
        if (len == 0){
            return 1;
        } else if (arr1[i] != arr2[i]) {
            return 0;
        } else {
            continue;
        }
    }

    return 1;

}

OR

You need to rewrite function declaration as follows (in efficent way):

int identical ( int arr1[], int arr2[], unsigned int len ){

   if (len == 0)    return 1;

    for (int i = 0; i < len; i++)
        if (arr1[i] != arr2[i])     return 0;

   return 1;
}

Thanks.


问:
IBM MQ - SSL Encrypted Message Browsable in MQ Explorer
I have done an SSL configuration for my IBM MQ v9, created a Java client, and added the certificates both sides. A Put and Get messages works fine. My issue is I'm able to browse the message using the MQ Explorer in the server. Is it because the message is decrypted and shown? Can I keep this message encrypted to a MQ Admin user who has access to the MQ explorer.

Any advice is very much appreciated.

Thanks in advance,

Yasothar

答:
Configuring encryption at the channel level only encrypts data in motion (on the network).

Messages on a queue are not encrypted unless you do this at the application layer or use the IBM MQ Advanced Message Security (AMS) extension of the product, this requires additional configuration with different certs to represent the putting and getting applications as well as policies to tell MQ AMS what to encrypt and who can receive.

Even with IBM MQ AMS configured, someone with MQ admin authority can still override configurations to allow viewing of messages sent, since the the MQ admin controls the policy, so can easily add themselfs as a new recipient so they can also view message that are sent.


问:
Wildfly @Remote interface JNDI lookup between 2 ears in the same server
I am migrating Java EE 6 application from glassfish 3.1.1.2 to WildFly 18.

There are two ears deployed to server:

```<code>+ CoreEar
    + CoreEjb.jar
+ AppEar
    + AppEjb.jar
    + somewar1.war
    + somewar2.war
</code>```

In CoreEjbs I've got a remote interface:

```<code>@Remote
public interface ExampleInterface {
    // methods
}
</code>```

And implementing bean:

```<code>@Stateless
@LocalBean
public class Example implements ExampleInterface {
    // methods implementation
}
</code>```

And it is used in AppEjb:

```<code>public class SomeManager {
    @EJB
    ExampleInterface injectedBean;
}
</code>```

This code was deploying and working fine on glassfish. But it doesn't work on WildFly 18.

CoreEar deploys fine and in logs I can find information about JNDI bindings for session bean named 'Example':

```<code>[org.jboss.as.ejb3.deployment] (MSC service thread 1-2) WFLYEJB0473: JNDI bindings for session bean named 'Example' in deployment unit 'subdeployment "CoreEjb.jar" of deployment "CoreEar.ear"' are as follows:
    java:global/CoreEar/CoreEjb/Example!com.company.example.ExampleInterface
    java:app/CoreEjb/Example!com.company.core.ExampleInterface
    java:module/Example!com.company.core.ExampleInterface
    java:jboss/exported/CoreEar/CoreEjb/Example!com.company.core.ExampleInterface
    ejb:CoreEar/CoreEjb/Example!com.company.core.ExampleInterface
    java:global/CoreEar/CoreEjb/Example!com.company.core.Example
    java:app/CoreEjb/Example!com.company.core.Example
    java:module/Example!com.company.core.Example
    ejb:CoreEar/CoreEjb/Example!com.company.core.Example
</code>```

But then when I deploy AppEar I get exceptions:

```<code>13:45:38,344 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.deployment.subunit."AppEar.ear"."AppEjb.jar".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.subunit."AppEar.ear"."AppEjb.jar".INSTALL: WFLYSRV0153: Failed to process phase INSTALL of subdeployment "AppEjb.jar" of deployment "AppEar.ear"
        at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:183)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1739)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1701)
        at org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1559)
        at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1363)
        at java.lang.Thread.run(Thread.java:748)
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0052: Failed to install component SomeManager
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.deploy(ComponentInstallProcessor.java:109)
        at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:176)
        ... 8 more
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEJB0406: No EJB found with interface of type 'com.company.core.ExampleInterface' for binding com.company.managers.SomeManager/injectedBean
        at org.jboss.as.ejb3.deployment.processors.EjbInjectionSource.getResourceValue(EjbInjectionSource.java:90)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.processBindings(ComponentInstallProcessor.java:261)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.access$000(ComponentInstallProcessor.java:80)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor$1.handle(ComponentInstallProcessor.java:213)
        at org.jboss.as.ee.component.ClassDescriptionTraversal.run(ClassDescriptionTraversal.java:54)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.deployComponent(ComponentInstallProcessor.java:216)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.deploy(ComponentInstallProcessor.java:101)
        ... 9 more
</code>```

I am able to solve this exception when I add lookup string to @EJB annotation

```<code>@EJB(lookup = "java:app/CoreEjbs/Example!com.company.core.ExampleInterface")
ExampleInterface injectedBean;
</code>```

I don't know if it will deploy because there are exceptions for look-up of other interfaces in CoreEjbs.

The problem is that ExampleInterface is injected in many more beans and there are interfaces other than ExampleInterface in CoreEjbs that are also injected in many beans.

Declaring lookup in every place where a remote @EJB is injected is a lot of work and would make it hard to change implementations later etc.

Is there any way to declare globally JNDI look-up name for every @EJB ExampleInterface occurence?

I've tried somethings with ejb-jar.xml and jboss-ejb3.xml but none of it worked.

答:
We solve this problem by creating producer and then just do simple injection. Is allow place jndi path in one place.</p>

```<code>@Remote
public interface ExampleRemote extends Example {
}

public class ExampleProducer {
    @Produces
    @EJB(lookup = "java:global/example/ejb/ExampleEJB!com.example.ExampleRemote")
    private static ExampleRemote exampleRemote;

}

@Inject
private Example example;
</code>```

Body:
I am migrating Java EE 6 application from glassfish 3.1.1.2 to WildFly 18.

There are two ears deployed to server:

+ CoreEar
    + CoreEjb.jar
+ AppEar
    + AppEjb.jar
    + somewar1.war
    + somewar2.war

In CoreEjbs I've got a remote interface:

@Remote
public interface ExampleInterface {
    // methods
}

And implementing bean:

@Stateless
@LocalBean
public class Example implements ExampleInterface {
    // methods implementation
}

And it is used in AppEjb:

public class SomeManager {
    @EJB
    ExampleInterface injectedBean;
}

This code was deploying and working fine on glassfish. But it doesn't work on WildFly 18.

CoreEar deploys fine and in logs I can find information about JNDI bindings for session bean named 'Example':

[org.jboss.as.ejb3.deployment] (MSC service thread 1-2) WFLYEJB0473: JNDI bindings for session bean named 'Example' in deployment unit 'subdeployment "CoreEjb.jar" of deployment "CoreEar.ear"' are as follows:
    java:global/CoreEar/CoreEjb/Example!com.company.example.ExampleInterface
    java:app/CoreEjb/Example!com.company.core.ExampleInterface
    java:module/Example!com.company.core.ExampleInterface
    java:jboss/exported/CoreEar/CoreEjb/Example!com.company.core.ExampleInterface
    ejb:CoreEar/CoreEjb/Example!com.company.core.ExampleInterface
    java:global/CoreEar/CoreEjb/Example!com.company.core.Example
    java:app/CoreEjb/Example!com.company.core.Example
    java:module/Example!com.company.core.Example
    ejb:CoreEar/CoreEjb/Example!com.company.core.Example

But then when I deploy AppEar I get exceptions:

13:45:38,344 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-8) MSC000001: Failed to start service jboss.deployment.subunit."AppEar.ear"."AppEjb.jar".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.subunit."AppEar.ear"."AppEjb.jar".INSTALL: WFLYSRV0153: Failed to process phase INSTALL of subdeployment "AppEjb.jar" of deployment "AppEar.ear"
        at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:183)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1739)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1701)
        at org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1559)
        at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1363)
        at java.lang.Thread.run(Thread.java:748)
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEE0052: Failed to install component SomeManager
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.deploy(ComponentInstallProcessor.java:109)
        at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:176)
        ... 8 more
    Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: WFLYEJB0406: No EJB found with interface of type 'com.company.core.ExampleInterface' for binding com.company.managers.SomeManager/injectedBean
        at org.jboss.as.ejb3.deployment.processors.EjbInjectionSource.getResourceValue(EjbInjectionSource.java:90)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.processBindings(ComponentInstallProcessor.java:261)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.access$000(ComponentInstallProcessor.java:80)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor$1.handle(ComponentInstallProcessor.java:213)
        at org.jboss.as.ee.component.ClassDescriptionTraversal.run(ClassDescriptionTraversal.java:54)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.deployComponent(ComponentInstallProcessor.java:216)
        at org.jboss.as.ee.component.deployers.ComponentInstallProcessor.deploy(ComponentInstallProcessor.java:101)
        ... 9 more

I am able to solve this exception when I add lookup string to @EJB annotation

@EJB(lookup = "java:app/CoreEjbs/Example!com.company.core.ExampleInterface")
ExampleInterface injectedBean;

I don't know if it will deploy because there are exceptions for look-up of other interfaces in CoreEjbs.

The problem is that ExampleInterface is injected in many more beans and there are interfaces other than ExampleInterface in CoreEjbs that are also injected in many beans.

Declaring lookup in every place where a remote @EJB is injected is a lot of work and would make it hard to change implementations later etc.

Is there any way to declare globally JNDI look-up name for every @EJB ExampleInterface occurence?

I've tried somethings with ejb-jar.xml and jboss-ejb3.xml but none of it worked.

Body:
We solve this problem by creating producer and then just do simple injection. Is allow place jndi path in one place.

@Remote
public interface ExampleRemote extends Example {
}

public class ExampleProducer {
    @Produces
    @EJB(lookup = "java:global/example/ejb/ExampleEJB!com.example.ExampleRemote")
    private static ExampleRemote exampleRemote;

}

@Inject
private Example example;


问:
How to get selected item of a singlechoice Alert Dialog?
I have this code to show a dialog with singlechoice(radio) options.

```<code>AlertDialog ad = new AlertDialog.Builder(this)
.setCancelable(false)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.choose_one)
.setSingleChoiceItems(seq, pos,null)
.setPositiveButton( R.string.ok, new DialogInterface.OnClickListener() {
  public void onClick( DialogInterface dialog, int whichButton)
  {
    // dialog dismissed
  }
 }).create();
</code>```

How do I get the choice that has been selected?

答:
```<code>EditText et = (EditText)findViewById(R.id.editText9);

int a = Integer.valueOf(item);

et.setText(items[a]);
</code>```

Body:
I have this code to show a dialog with singlechoice(radio) options.

AlertDialog ad = new AlertDialog.Builder(this)
.setCancelable(false)
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.choose_one)
.setSingleChoiceItems(seq, pos,null)
.setPositiveButton( R.string.ok, new DialogInterface.OnClickListener() {
  public void onClick( DialogInterface dialog, int whichButton)
  {
    // dialog dismissed
  }
 }).create();

How do I get the choice that has been selected?


问:
Plotting 3D vector field with quiver3d() in Mayavi
I'm having a hard time to figure out why the following code isn't working inside the Jupyter Notebook! Any help is really appreciated

```<code>%gui qt
import matplotlib.pyplot as plt
import numpy as np
from sympy import symbols
from mayavi import mlab

x,y,z = symbols('x y z')
def gradient(f):
    return (f.diff(x), f.diff(y),f.diff(z))

f = x*y**2+z**2
g = gradient(f)

xrange = np.linspace(-3,3,15)
yrange = np.linspace(-3,3,15)
zrange = np.linspace(-3,3,15)
X,Y,Z = np.meshgrid(xrange, yrange, zrange)

U = np.zeros((15,15,15))
V = np.zeros((15,15,15))
W = np.zeros((15,15,15))

for i in range(len(xrange)):
    for j in range(len(yrange)):
        for k in range(len(zrange)):
            x1 = X[i,j,k]
            y1 = Y[i,j,k]
            z1 = Z[i,j,k]
            U[i,j,k] = g[0].subs({x:x1, y:y1, z:z1})
            V[i,j,k] = g[1].subs({x:x1, y:y1, z:z1})
            W[i,j,k] = g[2].subs({x:x1, y:y1, z:z1})

mlab.quiver3d(X,Y,Z,U,V,W)
</code>```

In fact, I don't receive any error message just a black window of Mayavi. I have waited more than 10min but the windows permanents black. I'm running this code on a machine with Ubuntu 19.10. As a matter of completeness, I would like to mention that the below code works normally.

```<code>%gui qt
from mayavi import mlab
import numpy as np

def V(x, y, z):
    """ A 3D sinusoidal lattice with a parabolic confinement. """
    return np.cos(10*x) + np.cos(10*y) + np.cos(10*z) + 2*(x**2 + y**2 + z**2)
X, Y, Z = np.mgrid[-2:2:100j, -2:2:100j, -2:2:100j]
mlab.contour3d(X, Y, Z, V)
</code>```

答:
I could solve the problem by adding

```<code>mlab.init_notebook()
mlab.clf()
</code>```

after importing the mlab module. In this way the plot appears inside Jupyter Notebook.

Body:
I'm having a hard time to figure out why the following code isn't working inside the Jupyter Notebook! Any help is really appreciated

%gui qt
import matplotlib.pyplot as plt
import numpy as np
from sympy import symbols
from mayavi import mlab

x,y,z = symbols('x y z')
def gradient(f):
    return (f.diff(x), f.diff(y),f.diff(z))

f = x*y**2+z**2
g = gradient(f)

xrange = np.linspace(-3,3,15)
yrange = np.linspace(-3,3,15)
zrange = np.linspace(-3,3,15)
X,Y,Z = np.meshgrid(xrange, yrange, zrange)

U = np.zeros((15,15,15))
V = np.zeros((15,15,15))
W = np.zeros((15,15,15))

for i in range(len(xrange)):
    for j in range(len(yrange)):
        for k in range(len(zrange)):
            x1 = X[i,j,k]
            y1 = Y[i,j,k]
            z1 = Z[i,j,k]
            U[i,j,k] = g[0].subs({x:x1, y:y1, z:z1})
            V[i,j,k] = g[1].subs({x:x1, y:y1, z:z1})
            W[i,j,k] = g[2].subs({x:x1, y:y1, z:z1})

mlab.quiver3d(X,Y,Z,U,V,W)

In fact, I don't receive any error message just a black window of Mayavi. I have waited more than 10min but the windows permanents black. I'm running this code on a machine with Ubuntu 19.10. As a matter of completeness, I would like to mention that the below code works normally.

%gui qt
from mayavi import mlab
import numpy as np

def V(x, y, z):
    """ A 3D sinusoidal lattice with a parabolic confinement. """
    return np.cos(10*x) + np.cos(10*y) + np.cos(10*z) + 2*(x**2 + y**2 + z**2)
X, Y, Z = np.mgrid[-2:2:100j, -2:2:100j, -2:2:100j]
mlab.contour3d(X, Y, Z, V)

Body:
I could solve the problem by adding

mlab.init_notebook()
mlab.clf()

after importing the mlab module. In this way the plot appears inside Jupyter Notebook.


问:
Mixed content warning for insecure resources from Odoo
I am running Odoo and would like to add some caching mechanism.

In order to do so, I simply added a service worker and the following rout:

workbox.routing.registerNavigationRoute(
'/web/',
workbox.strategies.staleWhileRevalidate(),

);

Unfortunately i now always receive the following error message:
"Mixed Content: The page at 'https://test.emanju.de/sw.js' was loaded over HTTPS, but requested an insecure resource 'http://test.emanju.de/web/login'. This request has been blocked; the content must be served over HTTPS."

Obviously Odoo references to some insecure sources. Now I have the following questions:
1) How am I able to identify these sources (all of them)? Can I somehow scan the whole page?
2) Can I some how still run my service worker and just ignore the insecure files? Is the a way to still follow my goal without adjusting the existing application code and fixing all insecure files?

Thanks in advance!

答:
I had a similar problem: Loading PDF presentation in the eLearning module ("slides") would request the resource over http rather than https. What worked in my case:

adding proxy_mode = True into the [options] section of odoo.conf (if you deployed using docker, put odoo.conf into /etc/odoo/odoo.conf, which in their docker-compose.yml example is a shared folder (./config:/etc/odoo)

nginx config I'm using (I was missing the X-Forwarded-Host header):

```<code>location / {
proxy_pass http://localhost:8069;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Host $host;
proxy_redirect off;
proxy_request_buffering off;
proxy_connect_timeout  36000s;
proxy_read_timeout  36000s;
proxy_send_timeout  36000s;
send_timeout  36000s;
client_max_body_size 10240m;
}
</code>```

when in developer mode, go to Settings -> Technical -> System Parameters, and make sure your web.base.url contains https:// (some people also add web.base.url.freeze set to True -- this doesn't seem to have an effect on my installation)

Restart nginx, restart odoo, and voila, PDFs in Slides are being requested over https://.

Body:
I had a similar problem: Loading PDF presentation in the eLearning module ("slides") would request the resource over http rather than https. What worked in my case:

adding proxy_mode = True into the [options] section of odoo.conf (if you deployed using docker, put odoo.conf into /etc/odoo/odoo.conf, which in their docker-compose.yml example is a shared folder (./config:/etc/odoo)

nginx config I'm using (I was missing the X-Forwarded-Host header):

location / {
proxy_pass http://localhost:8069;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Host $host;
proxy_redirect off;
proxy_request_buffering off;
proxy_connect_timeout  36000s;
proxy_read_timeout  36000s;
proxy_send_timeout  36000s;
send_timeout  36000s;
client_max_body_size 10240m;
}

when in developer mode, go to Settings -> Technical -> System Parameters, and make sure your web.base.url contains https:// (some people also add web.base.url.freeze set to True -- this doesn't seem to have an effect on my installation)

Restart nginx, restart odoo, and voila, PDFs in Slides are being requested over https://.


问:
How do you implement a "raceToSuccess" helper, given a list of promises?
I'm puzzled by something in the ES6 Promise API. I can see a clear use case for submitting multiple async jobs concurrently, and "resolving" on the first success. This would, for example, serve a situation where multiple equivalent servers are available, but some are perhaps down, and others heavily loaded and slow, so my goal would be to get a response from the first one to succeed, and ignore the rest (yes, I know this is an obnoxious way for a client to behave from a server's perspective, but it's great for the end user ;)

However, as far as I can see, I have either "all" or "race" behaviors to play with. The "all" behavior seems to wait until all the requests have completed, which means that I have to wait for the slowest, even if a server has already completed (indeed, I might have to wait for a timeout, with would be a disaster for this scenario.) The "race" behavior, however, seems to give me the first to complete, which if that happens to be a failure, is also a disaster.

Is there something in the API that permits a "raceToSuccess" kind of behavior, or do I have to build it by hand. For that matter, how would I build it by hand?

As a side note, I found the same puzzle in the Java 8 CompletableFuture, which seems to be a closely parallel API. So, am I missing something at a philosophical level?

答:
Is there something in the API that permits a "raceToSuccess" kind of behavior

There is now. There is a finished Stage 4 proposal for Promise.any:

Promise.any() takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.

So, the following syntax can be used:

```<code>// assume getApi returns a Promise

const promises = [
  getApi('url1'),
  getApi('url2'),
  getApi('url3'),
  getApi('url4'),
];
Promise.any(promises)
  .then((result) => {
    // result will contain the resolve value of the first Promise to resolve
  })
  .catch((err) => {
    // Every Promise rejected
  });
</code>```

Promise.any has been implemented in all modern browsers. There are some polyfills available too.

Body:
Is there something in the API that permits a "raceToSuccess" kind of behavior

There is now. There is a finished Stage 4 proposal for Promise.any:

Promise.any() takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.

So, the following syntax can be used:

// assume getApi returns a Promise

const promises = [
  getApi('url1'),
  getApi('url2'),
  getApi('url3'),
  getApi('url4'),
];
Promise.any(promises)
  .then((result) => {
    // result will contain the resolve value of the first Promise to resolve
  })
  .catch((err) => {
    // Every Promise rejected
  });

Promise.any has been implemented in all modern browsers. There are some polyfills available too.


问:
Append Multiple Objects into Existing Array Using JSON_MODIFY
The problem was in appending new JSON array to the existing JSON array:

Suppose I have the following JSON Array
[{"id": 1, "data": "One"}, {"id": 2, "data": "Two"}]

How do I append [{"id": 3, "data": "Three"}, {"id": 4, "data": "Four"}] to it using JSON_MODIFY?

resulting value for updated column:
[{"id": 1, "data": "One"}, {"id": 2, "data": "Two"}, {"id": 3, "data": "Three"}, {"id": 4, "data": "Four"}]

答:
You can use "JSON_MODIFY" function and append key to modify JSON object like below:

SQL-FIDDLE

It's for individual JSON array:

```<code>DECLARE @json1 NVARCHAR(500)='[{"id": 1, "data": "One"}, {"id": 2, "data": "Two"}]';
DECLARE @json2 NVARCHAR(500)='[{"id": 3, "data": "Three"}, {"id": 4, "data": "Four"}]';

SELECT t.id, t.[data]
FROM
(
    SELECT * FROM OPENJSON(@json1) WITH(id int,[data] NVARCHAR(MAX))
    UNION ALL
    SELECT * FROM OPENJSON(@json2) WITH(id int,[data] NVARCHAR(MAX))
) t
FOR JSON PATH;
</code>```

It's for individual JSON hash:

```<code>DECLARE @info NVARCHAR(500)='[{"id": 1, "data": "One"}, {"id": 2, "data": "Two"}]';

PRINT @info;

SET @info = JSON_MODIFY(@info, 'append $', JSON_QUERY('{"id": 3, "data": "Three"}'))
SET @info = JSON_MODIFY(@info, 'append $', JSON_QUERY('{"id": 4, "data": "Four"}'))

PRINT @info;
</code>```

Body:
You can use "JSON_MODIFY" function and append key to modify JSON object like below:

SQL-FIDDLE

It's for individual JSON array:

DECLARE @json1 NVARCHAR(500)='[{"id": 1, "data": "One"}, {"id": 2, "data": "Two"}]';
DECLARE @json2 NVARCHAR(500)='[{"id": 3, "data": "Three"}, {"id": 4, "data": "Four"}]';

SELECT t.id, t.[data]
FROM
(
    SELECT * FROM OPENJSON(@json1) WITH(id int,[data] NVARCHAR(MAX))
    UNION ALL
    SELECT * FROM OPENJSON(@json2) WITH(id int,[data] NVARCHAR(MAX))
) t
FOR JSON PATH;

It's for individual JSON hash:

DECLARE @info NVARCHAR(500)='[{"id": 1, "data": "One"}, {"id": 2, "data": "Two"}]';

PRINT @info;

SET @info = JSON_MODIFY(@info, 'append $', JSON_QUERY('{"id": 3, "data": "Three"}'))
SET @info = JSON_MODIFY(@info, 'append $', JSON_QUERY('{"id": 4, "data": "Four"}'))

PRINT @info;


问:
Excel Formula comparing dates
I am trying to write an excel formula that checks to see if a finished date is the same as an expected finish date. If they are the same or the expected finish date is within 14 days of the finish date then 'Green' gets written in the cell, if not then the cell writes 'yellow'

This is my formula so far, but I am not getting the result that I am looking for.

```<code>=IF((OR(M21 = N21,M21 <= M21 +14))"Green","Yellow")
</code>```

M21 is a date written like: 2/4/2020 the same goes for N21

答:
```<code>=IF(N21 <= M21 +14,"Green","Yellow")
</code>```

Should work fine.

If formulas with dates aren't working, its often because the dates have been stored as text.  You can try editing them, or if too many or unclear, you can use the following:

```<code>=IF(DATEVALUE(N21) <= DATEVALUE(M21) +14,"Green","Yellow")
</code>```

Title: Excel Formula comparing dates

Body:
I am trying to write an excel formula that checks to see if a finished date is the same as an expected finish date. If they are the same or the expected finish date is within 14 days of the finish date then 'Green' gets written in the cell, if not then the cell writes 'yellow'

This is my formula so far, but I am not getting the result that I am looking for.

=IF((OR(M21 = N21,M21 <= M21 +14))"Green","Yellow")

M21 is a date written like: 2/4/2020 the same goes for N21

Body:
=IF(N21 <= M21 +14,"Green","Yellow")

Should work fine.

If formulas with dates aren't working, its often because the dates have been stored as text.  You can try editing them, or if too many or unclear, you can use the following:

=IF(DATEVALUE(N21) <= DATEVALUE(M21) +14,"Green","Yellow")


问:
Spring-boot restapi page call
I got a simple spring boot application. I am trying load the html file through a rest controller. Below is my folder structure. I am unable to load test.html (just as helloworld code inside it)

```<code>@RequestMapping("/show1")
public ModelAndView showpage1() {
    System.out.println("## show1");
    ModelAndView modelAndView = new ModelAndView();
     modelAndView.setViewName("test");
     return modelAndView;
}
</code>```

My test.html content

```<code><h1> hello World </h1>
</code>```

答:
You just need to return the string with the name of the view. </p>

```<code>@RequestMapping("/showpage")
public String showpage1() {
      return "test";
}
</code>```

Title: Spring-boot restapi page call

Body:
I got a simple spring boot application. I am trying load the html file through a rest controller. Below is my folder structure. I am unable to load test.html (just as helloworld code inside it)

@RequestMapping("/show1")
public ModelAndView showpage1() {
    System.out.println("## show1");
    ModelAndView modelAndView = new ModelAndView();
     modelAndView.setViewName("test");
     return modelAndView;
}

My test.html content

 hello World

Body:
You just need to return the string with the name of the view.

@RequestMapping("/showpage")
public String showpage1() {
      return "test";
}


问:
how to retrofit and room handle nested object
```<code> "provinsi": [
        {
            "createdDate": 1490089930310,
            "createdBy": "SYSTEM",
            "updatedDate": 1490089930310,
            "updatedBy": "SYSTEM",
            "id": 31,
            "provinceName": "Kepulauan Riau",
            "provinceCode": "0",
            "mCities": [
                {
                    "createdDate": 1490092020000,
                    "createdBy": "SYSTEM",
                    "updatedDate": 1490092020000,
                    "updatedBy": "SYSTEM",
                    "provinceName": "Kepulauan Riau",
                    "id": 198,
                    "cityName": "KAB.BINTAN",
                    "cityCode": "2102",
                    "centralBankCode": ""
                },
                {
                    "createdDate": 1490092020000,
                    "createdBy": "SYSTEM",
                    "updatedDate": 1490092020000,
                    "updatedBy": "SYSTEM",
                    "provinceName": "Kepulauan Riau",
                    "id": 350,
                    "cityName": "KAB.KARIMUN",
                    "cityCode": "2101",
                    "centralBankCode": "3801"
                },

}
]
</code>```

<p>I tried to make it a relation table, or two tables. find good documentation for this but it's hard hahaha but can't find something like this </p>

答:
I think this will be a one-to-many relation. For example

Entity

@Entity
data class Dog(
    @PrimaryKey val dogId: Long,
    val dogOwnerId: Long,
    val name: String,
    val cuteness: Int,
    val barkVolume: Int,
    val breed: String
)

@Entity
data class Owner(@PrimaryKey val ownerId: Long, val name: String)

data class OwnerWithDogs(
    val owner: Owner,
    val dogs: List<Dog>
)

data class OwnerWithDogs(
     @Embedded val owner: Owner,
     @Relation(
          parentColumn = "ownerId",
          entityColumn = "dogOwnerId"
     )
     val dogs: List<Dog>
)
```

<p>Dao</p>

<pre class="lang-java prettyprint-override"><code>@Transaction
@Query("SELECT * FROM Owner")
fun getDogsAndOwners(): List<OwnerWithDogs>
</code>```

You can see a good article at here.

I hope this will be helpful.

Body:
 "provinsi": [
        {
            "createdDate": 1490089930310,
            "createdBy": "SYSTEM",
            "updatedDate": 1490089930310,
            "updatedBy": "SYSTEM",
            "id": 31,
            "provinceName": "Kepulauan Riau",
            "provinceCode": "0",
            "mCities": [
                {
                    "createdDate": 1490092020000,
                    "createdBy": "SYSTEM",
                    "updatedDate": 1490092020000,
                    "updatedBy": "SYSTEM",
                    "provinceName": "Kepulauan Riau",
                    "id": 198,
                    "cityName": "KAB.BINTAN",
                    "cityCode": "2102",
                    "centralBankCode": ""
                },
                {
                    "createdDate": 1490092020000,
                    "createdBy": "SYSTEM",
                    "updatedDate": 1490092020000,
                    "updatedBy": "SYSTEM",
                    "provinceName": "Kepulauan Riau",
                    "id": 350,
                    "cityName": "KAB.KARIMUN",
                    "cityCode": "2101",
                    "centralBankCode": "3801"
                },

}
]

I tried to make it a relation table, or two tables. find good documentation for this but it's hard hahaha but can't find something like this

Body:
I think this will be a one-to-many relation. For example

Entity

@Entity
data class Dog(
    @PrimaryKey val dogId: Long,
    val dogOwnerId: Long,
    val name: String,
    val cuteness: Int,
    val barkVolume: Int,
    val breed: String
)

@Entity
data class Owner(@PrimaryKey val ownerId: Long, val name: String)

data class OwnerWithDogs(
    val owner: Owner,
    val dogs: List<Dog>
)

data class OwnerWithDogs(
     @Embedded val owner: Owner,
     @Relation(
          parentColumn = "ownerId",
          entityColumn = "dogOwnerId"
     )
     val dogs: List<Dog>
)

Dao

@Transaction
@Query("SELECT * FROM Owner")
fun getDogsAndOwners(): List<OwnerWithDogs>

You can see a good article at here.

I hope this will be helpful.


问:
Controlled Natural Language scheme for describing system architectures?
Are there any good Controlled Natural Language models, written in something like W3C Metalog PNL, for describing system architectures?

I'm looking for a text-based alternative to UML diagrams... to represent System Components, Relationships, Dependencies, Use Cases, Data Flows, etc. The goal is to have a model that can be programatically queried (unlike a diagram) to answer simple questions like, "what other components connect to this component?".

Thanks

答:
The answer to your question is probably no.

But if you have an existing model (e.g. a UML file) and you are able to save it as OWL, then you can load this OWL file into a tool like ACE View which verbalizes it in controlled English (ACE) and lets you query and edit it also in controlled English.


答:
This error is often thrown due to duplications in your column names (not necessarily values)

First, just check if there is any duplication in your column names using the code:
df.columns.duplicated().any()

If it's true, then remove the duplicated columns

df.loc[:,~df.columns.duplicated()]

After you remove the duplicated columns, you should be able to run your groupby operation.

Title: ValueError: "cannot reindex from a duplicate axis" in groupby Pandas

Body:
My dataframe looks like this:

    SKU #    GRP    CATG   PRD
0   54995  9404000  4040  99999
1   54999  9404000  4040  99999
2   55037  9404000  4040  1556894
3   55148  9404000  4040  1556894
4   55254  9404000  4040  1556894
5   55291  9404000  4040  1556894
6   55294  9404000  4040  1556895
7   55445  9404000  4040  1556895
8   55807  9404001  4040  1556896
9   49021  9404002  4040  1556897
10  49035  9404002  4040  1556897
11  27538  9404000  4040  1556898
12  27539  9404000  4040  1556899
13  27540  9404000  4040  1556894
14  27542  9404000  4040  1556900
15  27543  9404000  4040  1556900
16  27544  9404003  4040  1556901
17  27546  9404004  4040  1556902
18  99111  9404005  4040  1556903
19  99112  9404006  4040  1556904
20  99113  9404007  4040  1556905
21  99116  9404008  4040  1556906
22  99119  9404009  4040  1556907
23  99122  94040010 4040  1556908
24  99125  94040011 4040  1556909
25  86007  94040012 4040  1556910
26  86010  94040013 4040  1556911

And when I try to perform a group by operation on the above dataframe, I get the "cannot reindex from a duplicate axis" error.

df.groupby(['GRP','CATG'],as_index=False)['PRD'].min()

I tried to find out the duplicate indices using:

df[df.index.duplicated()]

But didn't return any thing.
How can I go about resolving this issue?


问:
Authentication & Authorization with Azure AD for Angular - API application
I am developing Angular 6 & Web-API Core application & Now I have implemented Azure AD Authentication for my application. Till now authentication is successful. we are using ADAL-Angular 4 for handling the login, log-out in angular.

How to generate the access token from angular & how to identify the authenticated user has access or not. My user's, roles exist in DB, not in Azure AD.

I don't have Identity server in middle.

Please let me know.

答:
I have achieved this few months, forgot to share the approach.

Approach 1: Use ADAL.Js in your angular APP, it can establish direct integration between Azure AD & Angular.

Approach 2: You can use package "angular-auth-oidc-client" this is a very wonderful package and gives more functionality like [ refresh token, silent renew ]

I have used approach-2 and able to implement the authentication & authorization using Azure AD.

Thanks for your support.


问:
How can we create Boolean-like object in JavaScript?
I want to create my Boolean-like object.
But I don't want to pollute Boolean.prototype.
So I created MyBool like

```<code>MyBool = function (x) {
  this.value = x;
  this.valueOf = function () { return x; };
  this.toString = function () { return x; };
}
MyBool.prototype.and = function (y) {
  if (y.constructor !== MyBool) throw 'You cannot do that!';
  return this.value && y.value;
}
</code>```

and its instances

```<code>mytrue = new MyBool(true);
myfalse = new MyBool(false);
</code>```

But now, I noticed that

```<code>if (myfalse) {
  console.log ("myfalse is true!!!")
}
</code>```

prints that myfalse is true!!!

(Yet +myfalse (that is [[ToNumber]] conversion) comes to falsy, thanks to valueOf)

It's obvious because only following values are falsy in ECMAScript.

```<code>undefined, null, false, +0, -0, NaN, ''
</code>```

If Argument Type is Object, [[ToBoolean]] brings us true, in any case.
(see ECMA Type Conversion and Testing)

Is there any crafty way to create a falsy object?
It's ok if

```<code>myfalse.constructor is MyBool
(!! myfalse) is false
</code>```

Any cheat is welcome, including ECMA5's set/get/defineProperty or anything else.

Thanks in advance.

答: Understand what if(myfalse){} is doing. It is checking for the existence of myfalse, not whether its true or false. In this case, myfalse is an object and thus exists, and thus is true.

Body:
I want to create my Boolean-like object.
But I don't want to pollute Boolean.prototype.
So I created MyBool like

MyBool = function (x) {
  this.value = x;
  this.valueOf = function () { return x; };
  this.toString = function () { return x; };
}
MyBool.prototype.and = function (y) {
  if (y.constructor !== MyBool) throw 'You cannot do that!';
  return this.value && y.value;
}

and its instances

mytrue = new MyBool(true);
myfalse = new MyBool(false);

But now, I noticed that

if (myfalse) {
  console.log ("myfalse is true!!!")
}

prints that myfalse is true!!!

(Yet +myfalse (that is [[ToNumber]] conversion) comes to falsy, thanks to valueOf)

It's obvious because only following values are falsy in ECMAScript.

undefined, null, false, +0, -0, NaN, ''

If Argument Type is Object, [[ToBoolean]] brings us true, in any case.
(see ECMA Type Conversion and Testing)

Is there any crafty way to create a falsy object?
It's ok if

myfalse.constructor is MyBool
(!! myfalse) is false

Any cheat is welcome, including ECMA5's set/get/defineProperty or anything else.

Thanks in advance.


问:
Is there a way to add a ToolTip to an MDI Parent Form in VB6?
I'm currently working on a project that utilizes an MDI Form. What I would like to achieve is that when the user hovers over one of the menu options in the MDI menu, a ToolTipText appears describing what can be found in said menu. I'm aware of the fact that in some options for VisualBasic 6, ToolTip is supported. However, I can't seem to add this to the MDI Form, or add a label control for that matter. Has anyone ever run into this problem, and if so, is there a workaround or a solution?

Please let me know if you have any additional questions or comments. Thank you in advance.

答:
One other alternative that can be considered (but may be quite tedious to implement) could be reading the Mouse.X and Mouse.Y properties for each MDI menu and setting the captions of a Label control (or TextBox) using the Mouse Hover event.

You'd need to find the top left and bottom right points for each MDI menu and if it is within the box, you can show your label control with the intended caption. But note that you can't just put any controls on an MDI Form except maybe PictureBoxes, Toolbars and Coolbars, etc.

So the Label or TextBox control would have to be first placed on top of a PictureBox control which can be top aligned.